blob: d7a6349047bcd566979d0b7ad501c693cd187caa [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 {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001580 X86AVXABILevel AVXLevel;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001581public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001582 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1583 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)),
1584 AVXLevel(AVXLevel) {}
John McCallbeec5a02010-03-06 00:35:14 +00001585
John McCalla729c622012-02-17 03:33:10 +00001586 const X86_64ABIInfo &getABIInfo() const {
1587 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1588 }
1589
Craig Topper4f12f102014-03-12 06:41:41 +00001590 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001591 return 7;
1592 }
1593
1594 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001595 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001596 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001597
John McCall943fae92010-05-27 06:19:26 +00001598 // 0-15 are the 16 integer registers.
1599 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001600 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001601 return false;
1602 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001603
Jay Foad7c57be32011-07-11 09:56:20 +00001604 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001605 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001606 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001607 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1608 }
1609
John McCalla729c622012-02-17 03:33:10 +00001610 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001611 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001612 // The default CC on x86-64 sets %al to the number of SSA
1613 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001614 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001615 // that when AVX types are involved: the ABI explicitly states it is
1616 // undefined, and it doesn't work in practice because of how the ABI
1617 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001618 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001619 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001620 for (CallArgList::const_iterator
1621 it = args.begin(), ie = args.end(); it != ie; ++it) {
1622 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1623 HasAVXType = true;
1624 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001625 }
1626 }
John McCalla729c622012-02-17 03:33:10 +00001627
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001628 if (!HasAVXType)
1629 return true;
1630 }
John McCallcbc038a2011-09-21 08:08:30 +00001631
John McCalla729c622012-02-17 03:33:10 +00001632 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001633 }
1634
Craig Topper4f12f102014-03-12 06:41:41 +00001635 llvm::Constant *
1636 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001637 unsigned Sig;
1638 if (getABIInfo().has64BitPointers())
1639 Sig = (0xeb << 0) | // jmp rel8
1640 (0x0a << 8) | // .+0x0c
1641 ('F' << 16) |
1642 ('T' << 24);
1643 else
1644 Sig = (0xeb << 0) | // jmp rel8
1645 (0x06 << 8) | // .+0x08
1646 ('F' << 16) |
1647 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001648 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1649 }
1650
Alexander Musman09184fe2014-09-30 05:29:28 +00001651 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001652 return getNativeVectorSizeForAVXABI(AVXLevel) / 8;
Alexander Musman09184fe2014-09-30 05:29:28 +00001653 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001654};
1655
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001656class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1657public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001658 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1659 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001660
1661 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001662 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001663 Opt = "\01";
1664 Opt += Lib;
1665 }
1666};
1667
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001668static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001669 // If the argument does not end in .lib, automatically add the suffix.
1670 // If the argument contains a space, enclose it in quotes.
1671 // This matches the behavior of MSVC.
1672 bool Quote = (Lib.find(" ") != StringRef::npos);
1673 std::string ArgStr = Quote ? "\"" : "";
1674 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001675 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001676 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001677 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001678 return ArgStr;
1679}
1680
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001681class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1682public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001683 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1684 bool d, bool p, bool w, unsigned RegParms)
1685 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001686
Eric Christopher162c91c2015-06-05 22:03:00 +00001687 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001688 CodeGen::CodeGenModule &CGM) const override;
1689
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001690 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001691 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001692 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001693 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001694 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001695
1696 void getDetectMismatchOption(llvm::StringRef Name,
1697 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001698 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001699 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001700 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001701};
1702
Hans Wennborg77dc2362015-01-20 19:45:50 +00001703static void addStackProbeSizeTargetAttribute(const Decl *D,
1704 llvm::GlobalValue *GV,
1705 CodeGen::CodeGenModule &CGM) {
1706 if (isa<FunctionDecl>(D)) {
1707 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1708 llvm::Function *Fn = cast<llvm::Function>(GV);
1709
Eric Christopher7565e0d2015-05-29 23:09:49 +00001710 Fn->addFnAttr("stack-probe-size",
1711 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001712 }
1713 }
1714}
1715
Eric Christopher162c91c2015-06-05 22:03:00 +00001716void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001717 llvm::GlobalValue *GV,
1718 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001719 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001720
1721 addStackProbeSizeTargetAttribute(D, GV, CGM);
1722}
1723
Chris Lattner04dc9572010-08-31 16:44:54 +00001724class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001725 X86AVXABILevel AVXLevel;
Chris Lattner04dc9572010-08-31 16:44:54 +00001726public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001727 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1728 X86AVXABILevel AVXLevel)
1729 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), AVXLevel(AVXLevel) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001730
Eric Christopher162c91c2015-06-05 22:03:00 +00001731 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001732 CodeGen::CodeGenModule &CGM) const override;
1733
Craig Topper4f12f102014-03-12 06:41:41 +00001734 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001735 return 7;
1736 }
1737
1738 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001739 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001740 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001741
Chris Lattner04dc9572010-08-31 16:44:54 +00001742 // 0-15 are the 16 integer registers.
1743 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001744 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001745 return false;
1746 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001747
1748 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001749 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001750 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001751 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001752 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001753
1754 void getDetectMismatchOption(llvm::StringRef Name,
1755 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001756 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001757 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001758 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001759
1760 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001761 return getNativeVectorSizeForAVXABI(AVXLevel) / 8;
Alexander Musman09184fe2014-09-30 05:29:28 +00001762 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001763};
1764
Eric Christopher162c91c2015-06-05 22:03:00 +00001765void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001766 llvm::GlobalValue *GV,
1767 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001768 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001769
1770 addStackProbeSizeTargetAttribute(D, GV, CGM);
1771}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001772}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001773
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001774void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1775 Class &Hi) const {
1776 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1777 //
1778 // (a) If one of the classes is Memory, the whole argument is passed in
1779 // memory.
1780 //
1781 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1782 // memory.
1783 //
1784 // (c) If the size of the aggregate exceeds two eightbytes and the first
1785 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1786 // argument is passed in memory. NOTE: This is necessary to keep the
1787 // ABI working for processors that don't support the __m256 type.
1788 //
1789 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1790 //
1791 // Some of these are enforced by the merging logic. Others can arise
1792 // only with unions; for example:
1793 // union { _Complex double; unsigned; }
1794 //
1795 // Note that clauses (b) and (c) were added in 0.98.
1796 //
1797 if (Hi == Memory)
1798 Lo = Memory;
1799 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1800 Lo = Memory;
1801 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1802 Lo = Memory;
1803 if (Hi == SSEUp && Lo != SSE)
1804 Hi = SSE;
1805}
1806
Chris Lattnerd776fb12010-06-28 21:43:59 +00001807X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001808 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1809 // classified recursively so that always two fields are
1810 // considered. The resulting class is calculated according to
1811 // the classes of the fields in the eightbyte:
1812 //
1813 // (a) If both classes are equal, this is the resulting class.
1814 //
1815 // (b) If one of the classes is NO_CLASS, the resulting class is
1816 // the other class.
1817 //
1818 // (c) If one of the classes is MEMORY, the result is the MEMORY
1819 // class.
1820 //
1821 // (d) If one of the classes is INTEGER, the result is the
1822 // INTEGER.
1823 //
1824 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1825 // MEMORY is used as class.
1826 //
1827 // (f) Otherwise class SSE is used.
1828
1829 // Accum should never be memory (we should have returned) or
1830 // ComplexX87 (because this cannot be passed in a structure).
1831 assert((Accum != Memory && Accum != ComplexX87) &&
1832 "Invalid accumulated classification during merge.");
1833 if (Accum == Field || Field == NoClass)
1834 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001835 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001836 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001837 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001838 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001839 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001840 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001841 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1842 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001843 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001844 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001845}
1846
Chris Lattner5c740f12010-06-30 19:14:05 +00001847void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001848 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001849 // FIXME: This code can be simplified by introducing a simple value class for
1850 // Class pairs with appropriate constructor methods for the various
1851 // situations.
1852
1853 // FIXME: Some of the split computations are wrong; unaligned vectors
1854 // shouldn't be passed in registers for example, so there is no chance they
1855 // can straddle an eightbyte. Verify & simplify.
1856
1857 Lo = Hi = NoClass;
1858
1859 Class &Current = OffsetBase < 64 ? Lo : Hi;
1860 Current = Memory;
1861
John McCall9dd450b2009-09-21 23:43:11 +00001862 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001863 BuiltinType::Kind k = BT->getKind();
1864
1865 if (k == BuiltinType::Void) {
1866 Current = NoClass;
1867 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1868 Lo = Integer;
1869 Hi = Integer;
1870 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1871 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001872 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1873 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001874 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001875 Current = SSE;
1876 } else if (k == BuiltinType::LongDouble) {
1877 Lo = X87;
1878 Hi = X87Up;
1879 }
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);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001921 if (Size == 32) {
1922 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1923 // float> as integer.
1924 Current = Integer;
1925
1926 // If this type crosses an eightbyte boundary, it should be
1927 // split.
1928 uint64_t EB_Real = (OffsetBase) / 64;
1929 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1930 if (EB_Real != EB_Imag)
1931 Hi = Lo;
1932 } else if (Size == 64) {
1933 // gcc passes <1 x double> in memory. :(
1934 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1935 return;
1936
1937 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001938 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001939 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1940 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1941 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001942 Current = Integer;
1943 else
1944 Current = SSE;
1945
1946 // If this type crosses an eightbyte boundary, it should be
1947 // split.
1948 if (OffsetBase && OffsetBase != 64)
1949 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001950 } else if (Size == 128 ||
1951 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001952 // Arguments of 256-bits are split into four eightbyte chunks. The
1953 // least significant one belongs to class SSE and all the others to class
1954 // SSEUP. The original Lo and Hi design considers that types can't be
1955 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1956 // This design isn't correct for 256-bits, but since there're no cases
1957 // where the upper parts would need to be inspected, avoid adding
1958 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001959 //
1960 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1961 // registers if they are "named", i.e. not part of the "..." of a
1962 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001963 //
1964 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
1965 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001966 Lo = SSE;
1967 Hi = SSEUp;
1968 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001969 return;
1970 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001971
Chris Lattnerd776fb12010-06-28 21:43:59 +00001972 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001973 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001974
Chris Lattner2b037972010-07-29 02:01:43 +00001975 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001976 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001977 if (Size <= 64)
1978 Current = Integer;
1979 else if (Size <= 128)
1980 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001981 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001982 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001983 else if (ET == getContext().DoubleTy ||
1984 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001985 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001986 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001987 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001988 Current = ComplexX87;
1989
1990 // If this complex type crosses an eightbyte boundary then it
1991 // should be split.
1992 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001993 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001994 if (Hi == NoClass && EB_Real != EB_Imag)
1995 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001996
Chris Lattnerd776fb12010-06-28 21:43:59 +00001997 return;
1998 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001999
Chris Lattner2b037972010-07-29 02:01:43 +00002000 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002001 // Arrays are treated like structures.
2002
Chris Lattner2b037972010-07-29 02:01:43 +00002003 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002004
2005 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002006 // than four eightbytes, ..., it has class MEMORY.
2007 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002008 return;
2009
2010 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2011 // fields, it has class MEMORY.
2012 //
2013 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002014 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002015 return;
2016
2017 // Otherwise implement simplified merge. We could be smarter about
2018 // this, but it isn't worth it and would be harder to verify.
2019 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002020 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002021 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002022
2023 // The only case a 256-bit wide vector could be used is when the array
2024 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2025 // to work for sizes wider than 128, early check and fallback to memory.
2026 if (Size > 128 && EltSize != 256)
2027 return;
2028
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002029 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2030 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002031 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002032 Lo = merge(Lo, FieldLo);
2033 Hi = merge(Hi, FieldHi);
2034 if (Lo == Memory || Hi == Memory)
2035 break;
2036 }
2037
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002038 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002039 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002040 return;
2041 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002042
Chris Lattnerd776fb12010-06-28 21:43:59 +00002043 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002044 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002045
2046 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002047 // than four eightbytes, ..., it has class MEMORY.
2048 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002049 return;
2050
Anders Carlsson20759ad2009-09-16 15:53:40 +00002051 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2052 // copy constructor or a non-trivial destructor, it is passed by invisible
2053 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002054 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002055 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002056
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002057 const RecordDecl *RD = RT->getDecl();
2058
2059 // Assume variable sized types are passed in memory.
2060 if (RD->hasFlexibleArrayMember())
2061 return;
2062
Chris Lattner2b037972010-07-29 02:01:43 +00002063 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002064
2065 // Reset Lo class, this will be recomputed.
2066 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002067
2068 // If this is a C++ record, classify the bases first.
2069 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002070 for (const auto &I : CXXRD->bases()) {
2071 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002072 "Unexpected base class!");
2073 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002074 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002075
2076 // Classify this field.
2077 //
2078 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2079 // single eightbyte, each is classified separately. Each eightbyte gets
2080 // initialized to class NO_CLASS.
2081 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002082 uint64_t Offset =
2083 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002084 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002085 Lo = merge(Lo, FieldLo);
2086 Hi = merge(Hi, FieldHi);
2087 if (Lo == Memory || Hi == Memory)
2088 break;
2089 }
2090 }
2091
2092 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002093 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002094 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002095 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002096 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2097 bool BitField = i->isBitField();
2098
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002099 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2100 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002102 // The only case a 256-bit wide vector could be used is when the struct
2103 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2104 // to work for sizes wider than 128, early check and fallback to memory.
2105 //
2106 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2107 Lo = Memory;
2108 return;
2109 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002110 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002111 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002112 Lo = Memory;
2113 return;
2114 }
2115
2116 // Classify this field.
2117 //
2118 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2119 // exceeds a single eightbyte, each is classified
2120 // separately. Each eightbyte gets initialized to class
2121 // NO_CLASS.
2122 Class FieldLo, FieldHi;
2123
2124 // Bit-fields require special handling, they do not force the
2125 // structure to be passed in memory even if unaligned, and
2126 // therefore they can straddle an eightbyte.
2127 if (BitField) {
2128 // Ignore padding bit-fields.
2129 if (i->isUnnamedBitfield())
2130 continue;
2131
2132 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002133 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002134
2135 uint64_t EB_Lo = Offset / 64;
2136 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002137
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002138 if (EB_Lo) {
2139 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2140 FieldLo = NoClass;
2141 FieldHi = Integer;
2142 } else {
2143 FieldLo = Integer;
2144 FieldHi = EB_Hi ? Integer : NoClass;
2145 }
2146 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002147 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002148 Lo = merge(Lo, FieldLo);
2149 Hi = merge(Hi, FieldHi);
2150 if (Lo == Memory || Hi == Memory)
2151 break;
2152 }
2153
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002154 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002155 }
2156}
2157
Chris Lattner22a931e2010-06-29 06:01:59 +00002158ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002159 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2160 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002161 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002162 // Treat an enum type as its underlying type.
2163 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2164 Ty = EnumTy->getDecl()->getIntegerType();
2165
2166 return (Ty->isPromotableIntegerType() ?
2167 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2168 }
2169
2170 return ABIArgInfo::getIndirect(0);
2171}
2172
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002173bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2174 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2175 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002176 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002177 if (Size <= 64 || Size > LargestVector)
2178 return true;
2179 }
2180
2181 return false;
2182}
2183
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002184ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2185 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002186 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2187 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002188 //
2189 // This assumption is optimistic, as there could be free registers available
2190 // when we need to pass this argument in memory, and LLVM could try to pass
2191 // the argument in the free register. This does not seem to happen currently,
2192 // but this code would be much safer if we could mark the argument with
2193 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002194 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002195 // Treat an enum type as its underlying type.
2196 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2197 Ty = EnumTy->getDecl()->getIntegerType();
2198
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002199 return (Ty->isPromotableIntegerType() ?
2200 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002201 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002202
Mark Lacey3825e832013-10-06 01:33:34 +00002203 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002204 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002205
Chris Lattner44c2b902011-05-22 23:21:23 +00002206 // Compute the byval alignment. We specify the alignment of the byval in all
2207 // cases so that the mid-level optimizer knows the alignment of the byval.
2208 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002209
2210 // Attempt to avoid passing indirect results using byval when possible. This
2211 // is important for good codegen.
2212 //
2213 // We do this by coercing the value into a scalar type which the backend can
2214 // handle naturally (i.e., without using byval).
2215 //
2216 // For simplicity, we currently only do this when we have exhausted all of the
2217 // free integer registers. Doing this when there are free integer registers
2218 // would require more care, as we would have to ensure that the coerced value
2219 // did not claim the unused register. That would require either reording the
2220 // arguments to the function (so that any subsequent inreg values came first),
2221 // or only doing this optimization when there were no following arguments that
2222 // might be inreg.
2223 //
2224 // We currently expect it to be rare (particularly in well written code) for
2225 // arguments to be passed on the stack when there are still free integer
2226 // registers available (this would typically imply large structs being passed
2227 // by value), so this seems like a fair tradeoff for now.
2228 //
2229 // We can revisit this if the backend grows support for 'onstack' parameter
2230 // attributes. See PR12193.
2231 if (freeIntRegs == 0) {
2232 uint64_t Size = getContext().getTypeSize(Ty);
2233
2234 // If this type fits in an eightbyte, coerce it into the matching integral
2235 // type, which will end up on the stack (with alignment 8).
2236 if (Align == 8 && Size <= 64)
2237 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2238 Size));
2239 }
2240
Chris Lattner44c2b902011-05-22 23:21:23 +00002241 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002242}
2243
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002244/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2245/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002246llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002247 // Wrapper structs/arrays that only contain vectors are passed just like
2248 // vectors; strip them off if present.
2249 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2250 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002251
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002252 llvm::Type *IRType = CGT.ConvertType(Ty);
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002253 if(isa<llvm::VectorType>(IRType))
2254 return IRType;
2255
2256 // We couldn't find the preferred IR vector type for 'Ty'.
2257 uint64_t Size = getContext().getTypeSize(Ty);
2258 assert((Size == 128 || Size == 256) && "Invalid type found!");
2259
2260 // Return a LLVM IR vector type based on the size of 'Ty'.
2261 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2262 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002263}
2264
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002265/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2266/// is known to either be off the end of the specified type or being in
2267/// alignment padding. The user type specified is known to be at most 128 bits
2268/// in size, and have passed through X86_64ABIInfo::classify with a successful
2269/// classification that put one of the two halves in the INTEGER class.
2270///
2271/// It is conservatively correct to return false.
2272static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2273 unsigned EndBit, ASTContext &Context) {
2274 // If the bytes being queried are off the end of the type, there is no user
2275 // data hiding here. This handles analysis of builtins, vectors and other
2276 // types that don't contain interesting padding.
2277 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2278 if (TySize <= StartBit)
2279 return true;
2280
Chris Lattner98076a22010-07-29 07:43:55 +00002281 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2282 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2283 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2284
2285 // Check each element to see if the element overlaps with the queried range.
2286 for (unsigned i = 0; i != NumElts; ++i) {
2287 // If the element is after the span we care about, then we're done..
2288 unsigned EltOffset = i*EltSize;
2289 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002290
Chris Lattner98076a22010-07-29 07:43:55 +00002291 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2292 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2293 EndBit-EltOffset, Context))
2294 return false;
2295 }
2296 // If it overlaps no elements, then it is safe to process as padding.
2297 return true;
2298 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002299
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002300 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2301 const RecordDecl *RD = RT->getDecl();
2302 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002303
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002304 // If this is a C++ record, check the bases first.
2305 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002306 for (const auto &I : CXXRD->bases()) {
2307 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002308 "Unexpected base class!");
2309 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002310 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002311
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002312 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002313 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002314 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002315
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002316 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002317 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002318 EndBit-BaseOffset, Context))
2319 return false;
2320 }
2321 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002322
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002323 // Verify that no field has data that overlaps the region of interest. Yes
2324 // this could be sped up a lot by being smarter about queried fields,
2325 // however we're only looking at structs up to 16 bytes, so we don't care
2326 // much.
2327 unsigned idx = 0;
2328 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2329 i != e; ++i, ++idx) {
2330 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002331
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002332 // If we found a field after the region we care about, then we're done.
2333 if (FieldOffset >= EndBit) break;
2334
2335 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2336 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2337 Context))
2338 return false;
2339 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002340
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002341 // If nothing in this record overlapped the area of interest, then we're
2342 // clean.
2343 return true;
2344 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002345
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002346 return false;
2347}
2348
Chris Lattnere556a712010-07-29 18:39:32 +00002349/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2350/// float member at the specified offset. For example, {int,{float}} has a
2351/// float at offset 4. It is conservatively correct for this routine to return
2352/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002353static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002354 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002355 // Base case if we find a float.
2356 if (IROffset == 0 && IRType->isFloatTy())
2357 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002358
Chris Lattnere556a712010-07-29 18:39:32 +00002359 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002360 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002361 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2362 unsigned Elt = SL->getElementContainingOffset(IROffset);
2363 IROffset -= SL->getElementOffset(Elt);
2364 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2365 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002366
Chris Lattnere556a712010-07-29 18:39:32 +00002367 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002368 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2369 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002370 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2371 IROffset -= IROffset/EltSize*EltSize;
2372 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2373 }
2374
2375 return false;
2376}
2377
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002378
2379/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2380/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002381llvm::Type *X86_64ABIInfo::
2382GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002383 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002384 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002385 // pass as float if the last 4 bytes is just padding. This happens for
2386 // structs that contain 3 floats.
2387 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2388 SourceOffset*8+64, getContext()))
2389 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002390
Chris Lattnere556a712010-07-29 18:39:32 +00002391 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2392 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2393 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002394 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2395 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002396 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002397
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002398 return llvm::Type::getDoubleTy(getVMContext());
2399}
2400
2401
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002402/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2403/// an 8-byte GPR. This means that we either have a scalar or we are talking
2404/// about the high or low part of an up-to-16-byte struct. This routine picks
2405/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002406/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2407/// etc).
2408///
2409/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2410/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2411/// the 8-byte value references. PrefType may be null.
2412///
Alp Toker9907f082014-07-09 14:06:35 +00002413/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002414/// an offset into this that we're processing (which is always either 0 or 8).
2415///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002416llvm::Type *X86_64ABIInfo::
2417GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002418 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002419 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2420 // returning an 8-byte unit starting with it. See if we can safely use it.
2421 if (IROffset == 0) {
2422 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002423 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2424 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002425 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002426
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002427 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2428 // goodness in the source type is just tail padding. This is allowed to
2429 // kick in for struct {double,int} on the int, but not on
2430 // struct{double,int,int} because we wouldn't return the second int. We
2431 // have to do this analysis on the source type because we can't depend on
2432 // unions being lowered a specific way etc.
2433 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002434 IRType->isIntegerTy(32) ||
2435 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2436 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2437 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002438
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002439 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2440 SourceOffset*8+64, getContext()))
2441 return IRType;
2442 }
2443 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002444
Chris Lattner2192fe52011-07-18 04:24:23 +00002445 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002446 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002447 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002448 if (IROffset < SL->getSizeInBytes()) {
2449 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2450 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002451
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002452 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2453 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002454 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002455 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002456
Chris Lattner2192fe52011-07-18 04:24:23 +00002457 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002458 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002459 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002460 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002461 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2462 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002463 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002464
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002465 // Okay, we don't have any better idea of what to pass, so we pass this in an
2466 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002467 unsigned TySizeInBytes =
2468 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002469
Chris Lattner3f763422010-07-29 17:34:39 +00002470 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002471
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002472 // It is always safe to classify this as an integer type up to i64 that
2473 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002474 return llvm::IntegerType::get(getVMContext(),
2475 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002476}
2477
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002478
2479/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2480/// be used as elements of a two register pair to pass or return, return a
2481/// first class aggregate to represent them. For example, if the low part of
2482/// a by-value argument should be passed as i32* and the high part as float,
2483/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002484static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002485GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002486 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002487 // In order to correctly satisfy the ABI, we need to the high part to start
2488 // at offset 8. If the high and low parts we inferred are both 4-byte types
2489 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2490 // the second element at offset 8. Check for this:
2491 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2492 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002493 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002494 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002495
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002496 // To handle this, we have to increase the size of the low part so that the
2497 // second element will start at an 8 byte offset. We can't increase the size
2498 // of the second element because it might make us access off the end of the
2499 // struct.
2500 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002501 // There are usually two sorts of types the ABI generation code can produce
2502 // for the low part of a pair that aren't 8 bytes in size: float or
2503 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2504 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002505 // Promote these to a larger type.
2506 if (Lo->isFloatTy())
2507 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2508 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002509 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2510 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002511 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2512 }
2513 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002514
Reid Kleckneree7cf842014-12-01 22:02:27 +00002515 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002516
2517
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002518 // Verify that the second element is at an 8-byte offset.
2519 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2520 "Invalid x86-64 argument pair!");
2521 return Result;
2522}
2523
Chris Lattner31faff52010-07-28 23:06:14 +00002524ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002525classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002526 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2527 // classification algorithm.
2528 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002529 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002530
2531 // Check some invariants.
2532 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002533 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2534
Craig Topper8a13c412014-05-21 05:09:00 +00002535 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002536 switch (Lo) {
2537 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002538 if (Hi == NoClass)
2539 return ABIArgInfo::getIgnore();
2540 // If the low part is just padding, it takes no register, leave ResType
2541 // null.
2542 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2543 "Unknown missing lo part");
2544 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002545
2546 case SSEUp:
2547 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002548 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002549
2550 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2551 // hidden argument.
2552 case Memory:
2553 return getIndirectReturnResult(RetTy);
2554
2555 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2556 // available register of the sequence %rax, %rdx is used.
2557 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002558 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002559
Chris Lattner1f3a0632010-07-29 21:42:50 +00002560 // If we have a sign or zero extended integer, make sure to return Extend
2561 // so that the parameter gets the right LLVM IR attributes.
2562 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2563 // Treat an enum type as its underlying type.
2564 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2565 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002566
Chris Lattner1f3a0632010-07-29 21:42:50 +00002567 if (RetTy->isIntegralOrEnumerationType() &&
2568 RetTy->isPromotableIntegerType())
2569 return ABIArgInfo::getExtend();
2570 }
Chris Lattner31faff52010-07-28 23:06:14 +00002571 break;
2572
2573 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2574 // available SSE register of the sequence %xmm0, %xmm1 is used.
2575 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002576 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002577 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002578
2579 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2580 // returned on the X87 stack in %st0 as 80-bit x87 number.
2581 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002582 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002583 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002584
2585 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2586 // part of the value is returned in %st0 and the imaginary part in
2587 // %st1.
2588 case ComplexX87:
2589 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002590 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002591 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002592 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002593 break;
2594 }
2595
Craig Topper8a13c412014-05-21 05:09:00 +00002596 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002597 switch (Hi) {
2598 // Memory was handled previously and X87 should
2599 // never occur as a hi class.
2600 case Memory:
2601 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002602 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002603
2604 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002605 case NoClass:
2606 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002607
Chris Lattner52b3c132010-09-01 00:20:33 +00002608 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002609 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002610 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2611 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002612 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002613 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002614 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002615 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2616 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002617 break;
2618
2619 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002620 // is passed in the next available eightbyte chunk if the last used
2621 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002622 //
Chris Lattner57540c52011-04-15 05:22:18 +00002623 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002624 case SSEUp:
2625 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002626 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002627 break;
2628
2629 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2630 // returned together with the previous X87 value in %st0.
2631 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002632 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002633 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002634 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002635 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002636 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002637 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002638 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2639 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002640 }
Chris Lattner31faff52010-07-28 23:06:14 +00002641 break;
2642 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002643
Chris Lattner52b3c132010-09-01 00:20:33 +00002644 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002645 // known to pass in the high eightbyte of the result. We do this by forming a
2646 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002647 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002648 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002649
Chris Lattner1f3a0632010-07-29 21:42:50 +00002650 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002651}
2652
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002653ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002654 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2655 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002656 const
2657{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002658 Ty = useFirstFieldIfTransparentUnion(Ty);
2659
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002660 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002661 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002662
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002663 // Check some invariants.
2664 // FIXME: Enforce these by construction.
2665 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002666 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2667
2668 neededInt = 0;
2669 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002670 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002671 switch (Lo) {
2672 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002673 if (Hi == NoClass)
2674 return ABIArgInfo::getIgnore();
2675 // If the low part is just padding, it takes no register, leave ResType
2676 // null.
2677 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2678 "Unknown missing lo part");
2679 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002680
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002681 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2682 // on the stack.
2683 case Memory:
2684
2685 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2686 // COMPLEX_X87, it is passed in memory.
2687 case X87:
2688 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002689 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002690 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002691 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692
2693 case SSEUp:
2694 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002695 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002696
2697 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2698 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2699 // and %r9 is used.
2700 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002701 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002702
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002703 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002704 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002705
2706 // If we have a sign or zero extended integer, make sure to return Extend
2707 // so that the parameter gets the right LLVM IR attributes.
2708 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2709 // Treat an enum type as its underlying type.
2710 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2711 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002712
Chris Lattner1f3a0632010-07-29 21:42:50 +00002713 if (Ty->isIntegralOrEnumerationType() &&
2714 Ty->isPromotableIntegerType())
2715 return ABIArgInfo::getExtend();
2716 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002717
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002718 break;
2719
2720 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2721 // available SSE register is used, the registers are taken in the
2722 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002723 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002724 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002725 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002726 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727 break;
2728 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002729 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002730
Craig Topper8a13c412014-05-21 05:09:00 +00002731 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002732 switch (Hi) {
2733 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002734 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002735 // which is passed in memory.
2736 case Memory:
2737 case X87:
2738 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002739 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002740
2741 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002742
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002743 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002745 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002746 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002747
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002748 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2749 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750 break;
2751
2752 // X87Up generally doesn't occur here (long double is passed in
2753 // memory), except in situations involving unions.
2754 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002755 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002756 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002757
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002758 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2759 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002760
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002761 ++neededSSE;
2762 break;
2763
2764 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2765 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002766 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002767 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002768 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002769 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002770 break;
2771 }
2772
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002773 // If a high part was specified, merge it together with the low part. It is
2774 // known to pass in the high eightbyte of the result. We do this by forming a
2775 // first class struct aggregate with the high and low part: {low, high}
2776 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002777 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002778
Chris Lattner1f3a0632010-07-29 21:42:50 +00002779 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002780}
2781
Chris Lattner22326a12010-07-29 02:31:05 +00002782void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002783
Reid Kleckner40ca9132014-05-13 22:05:45 +00002784 if (!getCXXABI().classifyReturnType(FI))
2785 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002786
2787 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002788 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002789
2790 // If the return value is indirect, then the hidden argument is consuming one
2791 // integer register.
2792 if (FI.getReturnInfo().isIndirect())
2793 --freeIntRegs;
2794
Peter Collingbournef7706832014-12-12 23:41:25 +00002795 // The chain argument effectively gives us another free register.
2796 if (FI.isChainCall())
2797 ++freeIntRegs;
2798
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002799 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002800 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2801 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002802 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002804 it != ie; ++it, ++ArgNo) {
2805 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002806
Bill Wendling9987c0e2010-10-18 23:51:38 +00002807 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002808 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002809 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002810
2811 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2812 // eightbyte of an argument, the whole argument is passed on the
2813 // stack. If registers have already been assigned for some
2814 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002815 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002816 freeIntRegs -= neededInt;
2817 freeSSERegs -= neededSSE;
2818 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002819 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002820 }
2821 }
2822}
2823
2824static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2825 QualType Ty,
2826 CodeGenFunction &CGF) {
David Blaikie2e804282015-04-05 22:47:07 +00002827 llvm::Value *overflow_arg_area_p = CGF.Builder.CreateStructGEP(
2828 nullptr, VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002829 llvm::Value *overflow_arg_area =
2830 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2831
2832 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2833 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002834 // It isn't stated explicitly in the standard, but in practice we use
2835 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002836 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2837 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002838 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002839 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002840 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2842 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002843 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002844 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002845 overflow_arg_area =
2846 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2847 overflow_arg_area->getType(),
2848 "overflow_arg_area.align");
2849 }
2850
2851 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002852 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002853 llvm::Value *Res =
2854 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002855 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002856
2857 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2858 // l->overflow_arg_area + sizeof(type).
2859 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2860 // an 8 byte boundary.
2861
2862 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002863 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002864 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002865 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2866 "overflow_arg_area.next");
2867 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2868
2869 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2870 return Res;
2871}
2872
2873llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2874 CodeGenFunction &CGF) const {
2875 // Assume that va_list type is correct; should be pointer to LLVM type:
2876 // struct {
2877 // i32 gp_offset;
2878 // i32 fp_offset;
2879 // i8* overflow_arg_area;
2880 // i8* reg_save_area;
2881 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002882 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002883
Chris Lattner9723d6c2010-03-11 18:19:55 +00002884 Ty = CGF.getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00002885 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002886 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002887
2888 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2889 // in the registers. If not go to step 7.
2890 if (!neededInt && !neededSSE)
2891 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2892
2893 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2894 // general purpose registers needed to pass type and num_fp to hold
2895 // the number of floating point registers needed.
2896
2897 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2898 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2899 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2900 //
2901 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2902 // register save space).
2903
Craig Topper8a13c412014-05-21 05:09:00 +00002904 llvm::Value *InRegs = nullptr;
2905 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2906 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002908 gp_offset_p =
2909 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002910 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002911 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2912 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002913 }
2914
2915 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00002916 fp_offset_p =
2917 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002918 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2919 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002920 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2921 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002922 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2923 }
2924
2925 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2926 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2927 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2928 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2929
2930 // Emit code to load the value if it was passed in registers.
2931
2932 CGF.EmitBlock(InRegBlock);
2933
2934 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2935 // an offset of l->gp_offset and/or l->fp_offset. This may require
2936 // copying to a temporary location in case the parameter is passed
2937 // in different register classes or requires an alignment greater
2938 // than 8 for general purpose registers and 16 for XMM registers.
2939 //
2940 // FIXME: This really results in shameful code when we end up needing to
2941 // collect arguments from different places; often what should result in a
2942 // simple assembling of a structure from scattered addresses has many more
2943 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002944 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
David Blaikie1ed728c2015-04-05 22:45:47 +00002945 llvm::Value *RegAddr = CGF.Builder.CreateLoad(
2946 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3), "reg_save_area");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002947 if (neededInt && neededSSE) {
2948 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002949 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002950 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002951 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2952 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002953 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002954 llvm::Type *TyLo = ST->getElementType(0);
2955 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002956 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002957 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002958 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2959 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002960 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2961 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002962 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2963 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002964 llvm::Value *V =
2965 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
David Blaikie1ed728c2015-04-05 22:45:47 +00002966 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002967 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
David Blaikie1ed728c2015-04-05 22:45:47 +00002968 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002969
Owen Anderson170229f2009-07-14 23:10:40 +00002970 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002971 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002972 } else if (neededInt) {
2973 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2974 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002975 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002976
2977 // Copy to a temporary if necessary to ensure the appropriate alignment.
2978 std::pair<CharUnits, CharUnits> SizeAlign =
2979 CGF.getContext().getTypeInfoInChars(Ty);
2980 uint64_t TySize = SizeAlign.first.getQuantity();
2981 unsigned TyAlign = SizeAlign.second.getQuantity();
2982 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002983 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2984 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2985 RegAddr = Tmp;
2986 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002987 } else if (neededSSE == 1) {
2988 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2989 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2990 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002991 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002992 assert(neededSSE == 2 && "Invalid number of needed registers!");
2993 // SSE registers are spaced 16 bytes apart in the register save
2994 // area, we need to collect the two eightbytes together.
2995 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002996 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002997 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002998 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002999 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003000 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003001 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
3002 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00003003 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
3004 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00003005 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 0));
Chris Lattner0cf24192010-06-28 20:05:43 +00003006 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
3007 DblPtrTy));
David Blaikie1ed728c2015-04-05 22:45:47 +00003008 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(ST, Tmp, 1));
Chris Lattner0cf24192010-06-28 20:05:43 +00003009 RegAddr = CGF.Builder.CreateBitCast(Tmp,
3010 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003011 }
3012
3013 // AMD64-ABI 3.5.7p5: Step 5. Set:
3014 // l->gp_offset = l->gp_offset + num_gp * 8
3015 // l->fp_offset = l->fp_offset + num_fp * 16.
3016 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003017 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003018 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3019 gp_offset_p);
3020 }
3021 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003022 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003023 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3024 fp_offset_p);
3025 }
3026 CGF.EmitBranch(ContBlock);
3027
3028 // Emit code to load the value if it was passed in memory.
3029
3030 CGF.EmitBlock(InMemBlock);
3031 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
3032
3033 // Return the appropriate result.
3034
3035 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00003036 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003037 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003038 ResAddr->addIncoming(RegAddr, InRegBlock);
3039 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003040 return ResAddr;
3041}
3042
Reid Kleckner80944df2014-10-31 22:00:51 +00003043ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3044 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003045
3046 if (Ty->isVoidType())
3047 return ABIArgInfo::getIgnore();
3048
3049 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3050 Ty = EnumTy->getDecl()->getIntegerType();
3051
Reid Kleckner80944df2014-10-31 22:00:51 +00003052 TypeInfo Info = getContext().getTypeInfo(Ty);
3053 uint64_t Width = Info.Width;
3054 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003055
Reid Kleckner9005f412014-05-02 00:51:20 +00003056 const RecordType *RT = Ty->getAs<RecordType>();
3057 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003058 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003059 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003060 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3061 }
3062
3063 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003064 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3065
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003066 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003067 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003068 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003069 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003070 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003071
Reid Kleckner80944df2014-10-31 22:00:51 +00003072 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3073 // other targets.
3074 const Type *Base = nullptr;
3075 uint64_t NumElts = 0;
3076 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3077 if (FreeSSERegs >= NumElts) {
3078 FreeSSERegs -= NumElts;
3079 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3080 return ABIArgInfo::getDirect();
3081 return ABIArgInfo::getExpand();
3082 }
3083 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3084 }
3085
3086
Reid Klecknerec87fec2014-05-02 01:17:12 +00003087 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003088 // If the member pointer is represented by an LLVM int or ptr, pass it
3089 // directly.
3090 llvm::Type *LLTy = CGT.ConvertType(Ty);
3091 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3092 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003093 }
3094
Michael Kuperstein4f818702015-02-24 09:35:58 +00003095 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003096 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3097 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003098 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003099 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003100
Reid Kleckner9005f412014-05-02 00:51:20 +00003101 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003102 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003103 }
3104
Julien Lerouge10dcff82014-08-27 00:36:55 +00003105 // Bool type is always extended to the ABI, other builtin types are not
3106 // extended.
3107 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3108 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003109 return ABIArgInfo::getExtend();
3110
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003111 return ABIArgInfo::getDirect();
3112}
3113
3114void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003115 bool IsVectorCall =
3116 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003117
Reid Kleckner80944df2014-10-31 22:00:51 +00003118 // We can use up to 4 SSE return registers with vectorcall.
3119 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3120 if (!getCXXABI().classifyReturnType(FI))
3121 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3122
3123 // We can use up to 6 SSE register parameters with vectorcall.
3124 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003125 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003126 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003127}
3128
Chris Lattner04dc9572010-08-31 16:44:54 +00003129llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3130 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003131 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003132
Chris Lattner04dc9572010-08-31 16:44:54 +00003133 CGBuilderTy &Builder = CGF.Builder;
3134 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3135 "ap");
3136 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3137 llvm::Type *PTy =
3138 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3139 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3140
3141 uint64_t Offset =
3142 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3143 llvm::Value *NextAddr =
3144 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3145 "ap.next");
3146 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3147
3148 return AddrTyped;
3149}
Chris Lattner0cf24192010-06-28 20:05:43 +00003150
John McCallea8d8bb2010-03-11 00:10:12 +00003151// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003152namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003153/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3154class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003155public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003156 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3157
3158 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3159 CodeGenFunction &CGF) const override;
3160};
3161
3162class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3163public:
Eric Christopher7565e0d2015-05-29 23:09:49 +00003164 PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
3165 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003166
Craig Topper4f12f102014-03-12 06:41:41 +00003167 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003168 // This is recovered from gcc output.
3169 return 1; // r1 is the dedicated stack pointer
3170 }
3171
3172 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003173 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003174
3175 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3176 return 16; // Natural alignment for Altivec vectors.
3177 }
John McCallea8d8bb2010-03-11 00:10:12 +00003178};
3179
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003180}
John McCallea8d8bb2010-03-11 00:10:12 +00003181
Roman Divacky8a12d842014-11-03 18:32:54 +00003182llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3183 QualType Ty,
3184 CodeGenFunction &CGF) const {
3185 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3186 // TODO: Implement this. For now ignore.
3187 (void)CTy;
3188 return nullptr;
3189 }
3190
3191 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003192 bool isInt =
3193 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003194 llvm::Type *CharPtr = CGF.Int8PtrTy;
3195 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3196
3197 CGBuilderTy &Builder = CGF.Builder;
3198 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3199 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003200 llvm::Value *FPRPtrAsInt =
3201 Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
Roman Divacky8a12d842014-11-03 18:32:54 +00003202 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003203 llvm::Value *OverflowAreaPtrAsInt =
3204 Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3205 llvm::Value *OverflowAreaPtr =
3206 Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3207 llvm::Value *RegsaveAreaPtrAsInt =
3208 Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3209 llvm::Value *RegsaveAreaPtr =
3210 Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003211 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3212 // Align GPR when TY is i64.
3213 if (isI64) {
3214 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3215 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3216 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3217 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3218 }
3219 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
Eric Christopher7565e0d2015-05-29 23:09:49 +00003220 llvm::Value *OverflowArea =
3221 Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3222 llvm::Value *OverflowAreaAsInt =
3223 Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3224 llvm::Value *RegsaveArea =
3225 Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3226 llvm::Value *RegsaveAreaAsInt =
3227 Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
Roman Divacky8a12d842014-11-03 18:32:54 +00003228
Eric Christopher7565e0d2015-05-29 23:09:49 +00003229 llvm::Value *CC =
3230 Builder.CreateICmpULT(isInt ? GPR : FPR, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003231
Eric Christopher7565e0d2015-05-29 23:09:49 +00003232 llvm::Value *RegConstant =
3233 Builder.CreateMul(isInt ? GPR : FPR, Builder.getInt8(isInt ? 4 : 8));
Roman Divacky8a12d842014-11-03 18:32:54 +00003234
Eric Christopher7565e0d2015-05-29 23:09:49 +00003235 llvm::Value *OurReg = Builder.CreateAdd(
3236 RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003237
3238 if (Ty->isFloatingType())
3239 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3240
3241 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3242 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3243 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3244
3245 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3246
3247 CGF.EmitBlock(UsingRegs);
3248
3249 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3250 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3251 // Increase the GPR/FPR indexes.
3252 if (isInt) {
3253 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3254 Builder.CreateStore(GPR, GPRPtr);
3255 } else {
3256 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3257 Builder.CreateStore(FPR, FPRPtr);
3258 }
3259 CGF.EmitBranch(Cont);
3260
3261 CGF.EmitBlock(UsingOverflow);
3262
3263 // Increase the overflow area.
3264 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003265 OverflowAreaAsInt =
3266 Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3267 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr),
3268 OverflowAreaPtr);
Roman Divacky8a12d842014-11-03 18:32:54 +00003269 CGF.EmitBranch(Cont);
3270
3271 CGF.EmitBlock(Cont);
3272
3273 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3274 Result->addIncoming(Result1, UsingRegs);
3275 Result->addIncoming(Result2, UsingOverflow);
3276
3277 if (Ty->isAggregateType()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003278 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003279 return Builder.CreateLoad(AGGPtr, false, "aggr");
3280 }
3281
3282 return Result;
3283}
3284
John McCallea8d8bb2010-03-11 00:10:12 +00003285bool
3286PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3287 llvm::Value *Address) const {
3288 // This is calculated from the LLVM and GCC tables and verified
3289 // against gcc output. AFAIK all ABIs use the same encoding.
3290
3291 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003292
Chris Lattnerece04092012-02-07 00:39:47 +00003293 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003294 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3295 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3296 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3297
3298 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003299 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003300
3301 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003302 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003303
3304 // 64-76 are various 4-byte special-purpose registers:
3305 // 64: mq
3306 // 65: lr
3307 // 66: ctr
3308 // 67: ap
3309 // 68-75 cr0-7
3310 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003311 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003312
3313 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003314 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003315
3316 // 109: vrsave
3317 // 110: vscr
3318 // 111: spe_acc
3319 // 112: spefscr
3320 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003321 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003322
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003323 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003324}
3325
Roman Divackyd966e722012-05-09 18:22:46 +00003326// PowerPC-64
3327
3328namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003329/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3330class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003331public:
3332 enum ABIKind {
3333 ELFv1 = 0,
3334 ELFv2
3335 };
3336
3337private:
3338 static const unsigned GPRBits = 64;
3339 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003340 bool HasQPX;
3341
3342 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3343 // will be passed in a QPX register.
3344 bool IsQPXVectorTy(const Type *Ty) const {
3345 if (!HasQPX)
3346 return false;
3347
3348 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3349 unsigned NumElements = VT->getNumElements();
3350 if (NumElements == 1)
3351 return false;
3352
3353 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3354 if (getContext().getTypeSize(Ty) <= 256)
3355 return true;
3356 } else if (VT->getElementType()->
3357 isSpecificBuiltinType(BuiltinType::Float)) {
3358 if (getContext().getTypeSize(Ty) <= 128)
3359 return true;
3360 }
3361 }
3362
3363 return false;
3364 }
3365
3366 bool IsQPXVectorTy(QualType Ty) const {
3367 return IsQPXVectorTy(Ty.getTypePtr());
3368 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003369
3370public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003371 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3372 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003373
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003374 bool isPromotableTypeForABI(QualType Ty) const;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003375 bool isAlignedParamType(QualType Ty, bool &Align32) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003376
3377 ABIArgInfo classifyReturnType(QualType RetTy) const;
3378 ABIArgInfo classifyArgumentType(QualType Ty) const;
3379
Reid Klecknere9f6a712014-10-31 17:10:41 +00003380 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3381 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3382 uint64_t Members) const override;
3383
Bill Schmidt84d37792012-10-12 19:26:17 +00003384 // TODO: We can add more logic to computeInfo to improve performance.
3385 // Example: For aggregate arguments that fit in a register, we could
3386 // use getDirectInReg (as is done below for structs containing a single
3387 // floating-point value) to avoid pushing them to memory on function
3388 // entry. This would require changing the logic in PPCISelLowering
3389 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003390 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003391 if (!getCXXABI().classifyReturnType(FI))
3392 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003393 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003394 // We rely on the default argument classification for the most part.
3395 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003396 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003397 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003398 if (T) {
3399 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003400 if (IsQPXVectorTy(T) ||
3401 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003402 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003403 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003404 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003405 continue;
3406 }
3407 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003408 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003409 }
3410 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003411
Craig Topper4f12f102014-03-12 06:41:41 +00003412 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3413 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003414};
3415
3416class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003417 bool HasQPX;
3418
Bill Schmidt25cb3492012-10-03 19:18:57 +00003419public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003420 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003421 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
3422 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)),
3423 HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003424
Craig Topper4f12f102014-03-12 06:41:41 +00003425 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003426 // This is recovered from gcc output.
3427 return 1; // r1 is the dedicated stack pointer
3428 }
3429
3430 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003431 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003432
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003433 unsigned getOpenMPSimdDefaultAlignment(QualType QT) const override {
3434 if (HasQPX)
3435 if (const PointerType *PT = QT->getAs<PointerType>())
3436 if (PT->getPointeeType()->isSpecificBuiltinType(BuiltinType::Double))
3437 return 32; // Natural alignment for QPX doubles.
3438
Hal Finkel92e31a52014-10-03 17:45:20 +00003439 return 16; // Natural alignment for Altivec and VSX vectors.
3440 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003441};
3442
Roman Divackyd966e722012-05-09 18:22:46 +00003443class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3444public:
3445 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3446
Craig Topper4f12f102014-03-12 06:41:41 +00003447 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003448 // This is recovered from gcc output.
3449 return 1; // r1 is the dedicated stack pointer
3450 }
3451
3452 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003453 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003454
3455 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3456 return 16; // Natural alignment for Altivec vectors.
3457 }
Roman Divackyd966e722012-05-09 18:22:46 +00003458};
3459
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003460}
Roman Divackyd966e722012-05-09 18:22:46 +00003461
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003462// Return true if the ABI requires Ty to be passed sign- or zero-
3463// extended to 64 bits.
3464bool
3465PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3466 // Treat an enum type as its underlying type.
3467 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3468 Ty = EnumTy->getDecl()->getIntegerType();
3469
3470 // Promotable integer types are required to be promoted by the ABI.
3471 if (Ty->isPromotableIntegerType())
3472 return true;
3473
3474 // In addition to the usual promotable integer types, we also need to
3475 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3476 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3477 switch (BT->getKind()) {
3478 case BuiltinType::Int:
3479 case BuiltinType::UInt:
3480 return true;
3481 default:
3482 break;
3483 }
3484
3485 return false;
3486}
3487
Ulrich Weigand581badc2014-07-10 17:20:07 +00003488/// isAlignedParamType - Determine whether a type requires 16-byte
3489/// alignment in the parameter area.
3490bool
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003491PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty, bool &Align32) const {
3492 Align32 = false;
3493
Ulrich Weigand581badc2014-07-10 17:20:07 +00003494 // Complex types are passed just like their elements.
3495 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3496 Ty = CTy->getElementType();
3497
3498 // Only vector types of size 16 bytes need alignment (larger types are
3499 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003500 if (IsQPXVectorTy(Ty)) {
3501 if (getContext().getTypeSize(Ty) > 128)
3502 Align32 = true;
3503
3504 return true;
3505 } else if (Ty->isVectorType()) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003506 return getContext().getTypeSize(Ty) == 128;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003507 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003508
3509 // For single-element float/vector structs, we consider the whole type
3510 // to have the same alignment requirements as its single element.
3511 const Type *AlignAsType = nullptr;
3512 const Type *EltType = isSingleElementStruct(Ty, getContext());
3513 if (EltType) {
3514 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003515 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003516 getContext().getTypeSize(EltType) == 128) ||
3517 (BT && BT->isFloatingPoint()))
3518 AlignAsType = EltType;
3519 }
3520
Ulrich Weigandb7122372014-07-21 00:48:09 +00003521 // Likewise for ELFv2 homogeneous aggregates.
3522 const Type *Base = nullptr;
3523 uint64_t Members = 0;
3524 if (!AlignAsType && Kind == ELFv2 &&
3525 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3526 AlignAsType = Base;
3527
Ulrich Weigand581badc2014-07-10 17:20:07 +00003528 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003529 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3530 if (getContext().getTypeSize(AlignAsType) > 128)
3531 Align32 = true;
3532
3533 return true;
3534 } else if (AlignAsType) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003535 return AlignAsType->isVectorType();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003536 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003537
3538 // Otherwise, we only need alignment for any aggregate type that
3539 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003540 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3541 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
3542 Align32 = true;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003543 return true;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003544 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003545
3546 return false;
3547}
3548
Ulrich Weigandb7122372014-07-21 00:48:09 +00003549/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3550/// aggregate. Base is set to the base element type, and Members is set
3551/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003552bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3553 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003554 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3555 uint64_t NElements = AT->getSize().getZExtValue();
3556 if (NElements == 0)
3557 return false;
3558 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3559 return false;
3560 Members *= NElements;
3561 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3562 const RecordDecl *RD = RT->getDecl();
3563 if (RD->hasFlexibleArrayMember())
3564 return false;
3565
3566 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003567
3568 // If this is a C++ record, check the bases first.
3569 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3570 for (const auto &I : CXXRD->bases()) {
3571 // Ignore empty records.
3572 if (isEmptyRecord(getContext(), I.getType(), true))
3573 continue;
3574
3575 uint64_t FldMembers;
3576 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3577 return false;
3578
3579 Members += FldMembers;
3580 }
3581 }
3582
Ulrich Weigandb7122372014-07-21 00:48:09 +00003583 for (const auto *FD : RD->fields()) {
3584 // Ignore (non-zero arrays of) empty records.
3585 QualType FT = FD->getType();
3586 while (const ConstantArrayType *AT =
3587 getContext().getAsConstantArrayType(FT)) {
3588 if (AT->getSize().getZExtValue() == 0)
3589 return false;
3590 FT = AT->getElementType();
3591 }
3592 if (isEmptyRecord(getContext(), FT, true))
3593 continue;
3594
3595 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3596 if (getContext().getLangOpts().CPlusPlus &&
3597 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3598 continue;
3599
3600 uint64_t FldMembers;
3601 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3602 return false;
3603
3604 Members = (RD->isUnion() ?
3605 std::max(Members, FldMembers) : Members + FldMembers);
3606 }
3607
3608 if (!Base)
3609 return false;
3610
3611 // Ensure there is no padding.
3612 if (getContext().getTypeSize(Base) * Members !=
3613 getContext().getTypeSize(Ty))
3614 return false;
3615 } else {
3616 Members = 1;
3617 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3618 Members = 2;
3619 Ty = CT->getElementType();
3620 }
3621
Reid Klecknere9f6a712014-10-31 17:10:41 +00003622 // Most ABIs only support float, double, and some vector type widths.
3623 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003624 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003625
3626 // The base type must be the same for all members. Types that
3627 // agree in both total size and mode (float vs. vector) are
3628 // treated as being equivalent here.
3629 const Type *TyPtr = Ty.getTypePtr();
3630 if (!Base)
3631 Base = TyPtr;
3632
3633 if (Base->isVectorType() != TyPtr->isVectorType() ||
3634 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3635 return false;
3636 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003637 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3638}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003639
Reid Klecknere9f6a712014-10-31 17:10:41 +00003640bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3641 // Homogeneous aggregates for ELFv2 must have base types of float,
3642 // double, long double, or 128-bit vectors.
3643 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3644 if (BT->getKind() == BuiltinType::Float ||
3645 BT->getKind() == BuiltinType::Double ||
3646 BT->getKind() == BuiltinType::LongDouble)
3647 return true;
3648 }
3649 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003650 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003651 return true;
3652 }
3653 return false;
3654}
3655
3656bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3657 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003658 // Vector types require one register, floating point types require one
3659 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003660 uint32_t NumRegs =
3661 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003662
3663 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003664 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003665}
3666
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003667ABIArgInfo
3668PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003669 Ty = useFirstFieldIfTransparentUnion(Ty);
3670
Bill Schmidt90b22c92012-11-27 02:46:43 +00003671 if (Ty->isAnyComplexType())
3672 return ABIArgInfo::getDirect();
3673
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003674 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3675 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003676 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003677 uint64_t Size = getContext().getTypeSize(Ty);
3678 if (Size > 128)
3679 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3680 else if (Size < 128) {
3681 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3682 return ABIArgInfo::getDirect(CoerceTy);
3683 }
3684 }
3685
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003686 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003687 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003688 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003689
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003690 bool Align32;
3691 uint64_t ABIAlign = isAlignedParamType(Ty, Align32) ?
3692 (Align32 ? 32 : 16) : 8;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003693 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003694
3695 // ELFv2 homogeneous aggregates are passed as array types.
3696 const Type *Base = nullptr;
3697 uint64_t Members = 0;
3698 if (Kind == ELFv2 &&
3699 isHomogeneousAggregate(Ty, Base, Members)) {
3700 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3701 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3702 return ABIArgInfo::getDirect(CoerceTy);
3703 }
3704
Ulrich Weigand601957f2014-07-21 00:56:36 +00003705 // If an aggregate may end up fully in registers, we do not
3706 // use the ByVal method, but pass the aggregate as array.
3707 // This is usually beneficial since we avoid forcing the
3708 // back-end to store the argument to memory.
3709 uint64_t Bits = getContext().getTypeSize(Ty);
3710 if (Bits > 0 && Bits <= 8 * GPRBits) {
3711 llvm::Type *CoerceTy;
3712
3713 // Types up to 8 bytes are passed as integer type (which will be
3714 // properly aligned in the argument save area doubleword).
3715 if (Bits <= GPRBits)
3716 CoerceTy = llvm::IntegerType::get(getVMContext(),
3717 llvm::RoundUpToAlignment(Bits, 8));
3718 // Larger types are passed as arrays, with the base type selected
3719 // according to the required alignment in the save area.
3720 else {
3721 uint64_t RegBits = ABIAlign * 8;
3722 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3723 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3724 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3725 }
3726
3727 return ABIArgInfo::getDirect(CoerceTy);
3728 }
3729
Ulrich Weigandb7122372014-07-21 00:48:09 +00003730 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003731 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3732 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003733 }
3734
3735 return (isPromotableTypeForABI(Ty) ?
3736 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3737}
3738
3739ABIArgInfo
3740PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3741 if (RetTy->isVoidType())
3742 return ABIArgInfo::getIgnore();
3743
Bill Schmidta3d121c2012-12-17 04:20:17 +00003744 if (RetTy->isAnyComplexType())
3745 return ABIArgInfo::getDirect();
3746
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003747 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3748 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003749 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003750 uint64_t Size = getContext().getTypeSize(RetTy);
3751 if (Size > 128)
3752 return ABIArgInfo::getIndirect(0);
3753 else if (Size < 128) {
3754 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3755 return ABIArgInfo::getDirect(CoerceTy);
3756 }
3757 }
3758
Ulrich Weigandb7122372014-07-21 00:48:09 +00003759 if (isAggregateTypeForABI(RetTy)) {
3760 // ELFv2 homogeneous aggregates are returned as array types.
3761 const Type *Base = nullptr;
3762 uint64_t Members = 0;
3763 if (Kind == ELFv2 &&
3764 isHomogeneousAggregate(RetTy, Base, Members)) {
3765 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3766 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3767 return ABIArgInfo::getDirect(CoerceTy);
3768 }
3769
3770 // ELFv2 small aggregates are returned in up to two registers.
3771 uint64_t Bits = getContext().getTypeSize(RetTy);
3772 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3773 if (Bits == 0)
3774 return ABIArgInfo::getIgnore();
3775
3776 llvm::Type *CoerceTy;
3777 if (Bits > GPRBits) {
3778 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003779 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003780 } else
3781 CoerceTy = llvm::IntegerType::get(getVMContext(),
3782 llvm::RoundUpToAlignment(Bits, 8));
3783 return ABIArgInfo::getDirect(CoerceTy);
3784 }
3785
3786 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003787 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003788 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003789
3790 return (isPromotableTypeForABI(RetTy) ?
3791 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3792}
3793
Bill Schmidt25cb3492012-10-03 19:18:57 +00003794// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3795llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3796 QualType Ty,
3797 CodeGenFunction &CGF) const {
3798 llvm::Type *BP = CGF.Int8PtrTy;
3799 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3800
3801 CGBuilderTy &Builder = CGF.Builder;
3802 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3803 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3804
Ulrich Weigand581badc2014-07-10 17:20:07 +00003805 // Handle types that require 16-byte alignment in the parameter save area.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003806 bool Align32;
3807 if (isAlignedParamType(Ty, Align32)) {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003808 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003809 AddrAsInt = Builder.CreateAdd(AddrAsInt,
3810 Builder.getInt64(Align32 ? 31 : 15));
3811 AddrAsInt = Builder.CreateAnd(AddrAsInt,
3812 Builder.getInt64(Align32 ? -32 : -16));
Ulrich Weigand581badc2014-07-10 17:20:07 +00003813 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3814 }
3815
Bill Schmidt924c4782013-01-14 17:45:36 +00003816 // Update the va_list pointer. The pointer should be bumped by the
3817 // size of the object. We can trust getTypeSize() except for a complex
3818 // type whose base type is smaller than a doubleword. For these, the
3819 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003820 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003821 QualType BaseTy;
3822 unsigned CplxBaseSize = 0;
3823
3824 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3825 BaseTy = CTy->getElementType();
3826 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3827 if (CplxBaseSize < 8)
3828 SizeInBytes = 16;
3829 }
3830
Bill Schmidt25cb3492012-10-03 19:18:57 +00003831 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3832 llvm::Value *NextAddr =
3833 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3834 "ap.next");
3835 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3836
Bill Schmidt924c4782013-01-14 17:45:36 +00003837 // If we have a complex type and the base type is smaller than 8 bytes,
3838 // the ABI calls for the real and imaginary parts to be right-adjusted
3839 // in separate doublewords. However, Clang expects us to produce a
3840 // pointer to a structure with the two parts packed tightly. So generate
3841 // loads of the real and imaginary parts relative to the va_list pointer,
3842 // and store them to a temporary structure.
3843 if (CplxBaseSize && CplxBaseSize < 8) {
3844 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3845 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003846 if (CGF.CGM.getDataLayout().isBigEndian()) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00003847 RealAddr =
3848 Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3849 ImagAddr =
3850 Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003851 } else {
3852 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3853 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003854 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3855 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3856 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3857 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3858 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
David Blaikie2e804282015-04-05 22:47:07 +00003859 llvm::AllocaInst *Ptr =
3860 CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty), "vacplx");
3861 llvm::Value *RealPtr =
3862 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 0, ".real");
3863 llvm::Value *ImagPtr =
3864 Builder.CreateStructGEP(Ptr->getAllocatedType(), Ptr, 1, ".imag");
Bill Schmidt924c4782013-01-14 17:45:36 +00003865 Builder.CreateStore(Real, RealPtr, false);
3866 Builder.CreateStore(Imag, ImagPtr, false);
3867 return Ptr;
3868 }
3869
Bill Schmidt25cb3492012-10-03 19:18:57 +00003870 // If the argument is smaller than 8 bytes, it is right-adjusted in
3871 // its doubleword slot. Adjust the pointer to pick it up from the
3872 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003873 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003874 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3875 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3876 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3877 }
3878
3879 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3880 return Builder.CreateBitCast(Addr, PTy);
3881}
3882
3883static bool
3884PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3885 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003886 // This is calculated from the LLVM and GCC tables and verified
3887 // against gcc output. AFAIK all ABIs use the same encoding.
3888
3889 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3890
3891 llvm::IntegerType *i8 = CGF.Int8Ty;
3892 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3893 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3894 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3895
3896 // 0-31: r0-31, the 8-byte general-purpose registers
3897 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3898
3899 // 32-63: fp0-31, the 8-byte floating-point registers
3900 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3901
3902 // 64-76 are various 4-byte special-purpose registers:
3903 // 64: mq
3904 // 65: lr
3905 // 66: ctr
3906 // 67: ap
3907 // 68-75 cr0-7
3908 // 76: xer
3909 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3910
3911 // 77-108: v0-31, the 16-byte vector registers
3912 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3913
3914 // 109: vrsave
3915 // 110: vscr
3916 // 111: spe_acc
3917 // 112: spefscr
3918 // 113: sfp
3919 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3920
3921 return false;
3922}
John McCallea8d8bb2010-03-11 00:10:12 +00003923
Bill Schmidt25cb3492012-10-03 19:18:57 +00003924bool
3925PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3926 CodeGen::CodeGenFunction &CGF,
3927 llvm::Value *Address) const {
3928
3929 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3930}
3931
3932bool
3933PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3934 llvm::Value *Address) const {
3935
3936 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3937}
3938
Chris Lattner0cf24192010-06-28 20:05:43 +00003939//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003940// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003941//===----------------------------------------------------------------------===//
3942
3943namespace {
3944
Tim Northover573cbee2014-05-24 12:52:07 +00003945class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003946public:
3947 enum ABIKind {
3948 AAPCS = 0,
3949 DarwinPCS
3950 };
3951
3952private:
3953 ABIKind Kind;
3954
3955public:
Tim Northover573cbee2014-05-24 12:52:07 +00003956 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003957
3958private:
3959 ABIKind getABIKind() const { return Kind; }
3960 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3961
3962 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003963 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003964 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3965 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3966 uint64_t Members) const override;
3967
Tim Northovera2ee4332014-03-29 15:09:45 +00003968 bool isIllegalVectorType(QualType Ty) const;
3969
David Blaikie1cbb9712014-11-14 19:09:44 +00003970 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003971 if (!getCXXABI().classifyReturnType(FI))
3972 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003973
Tim Northoverb047bfa2014-11-27 21:02:49 +00003974 for (auto &it : FI.arguments())
3975 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003976 }
3977
3978 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3979 CodeGenFunction &CGF) const;
3980
3981 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3982 CodeGenFunction &CGF) const;
3983
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003984 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3985 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003986 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3987 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3988 }
3989};
3990
Tim Northover573cbee2014-05-24 12:52:07 +00003991class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003992public:
Tim Northover573cbee2014-05-24 12:52:07 +00003993 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3994 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003995
Alexander Kornienko34eb2072015-04-11 02:00:23 +00003996 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003997 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3998 }
3999
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004000 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4001 return 31;
4002 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004003
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004004 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004005};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004006}
Tim Northovera2ee4332014-03-29 15:09:45 +00004007
Tim Northoverb047bfa2014-11-27 21:02:49 +00004008ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004009 Ty = useFirstFieldIfTransparentUnion(Ty);
4010
Tim Northovera2ee4332014-03-29 15:09:45 +00004011 // Handle illegal vector types here.
4012 if (isIllegalVectorType(Ty)) {
4013 uint64_t Size = getContext().getTypeSize(Ty);
4014 if (Size <= 32) {
4015 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004016 return ABIArgInfo::getDirect(ResType);
4017 }
4018 if (Size == 64) {
4019 llvm::Type *ResType =
4020 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004021 return ABIArgInfo::getDirect(ResType);
4022 }
4023 if (Size == 128) {
4024 llvm::Type *ResType =
4025 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004026 return ABIArgInfo::getDirect(ResType);
4027 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004028 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4029 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004030
4031 if (!isAggregateTypeForABI(Ty)) {
4032 // Treat an enum type as its underlying type.
4033 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4034 Ty = EnumTy->getDecl()->getIntegerType();
4035
Tim Northovera2ee4332014-03-29 15:09:45 +00004036 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4037 ? ABIArgInfo::getExtend()
4038 : ABIArgInfo::getDirect());
4039 }
4040
4041 // Structures with either a non-trivial destructor or a non-trivial
4042 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004043 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004044 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00004045 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004046 }
4047
4048 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4049 // elsewhere for GNU compatibility.
4050 if (isEmptyRecord(getContext(), Ty, true)) {
4051 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4052 return ABIArgInfo::getIgnore();
4053
Tim Northovera2ee4332014-03-29 15:09:45 +00004054 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4055 }
4056
4057 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004058 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004059 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004060 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004061 return ABIArgInfo::getDirect(
4062 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004063 }
4064
4065 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4066 uint64_t Size = getContext().getTypeSize(Ty);
4067 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004068 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004069 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004070
Tim Northovera2ee4332014-03-29 15:09:45 +00004071 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4072 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004073 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004074 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4075 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4076 }
4077 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4078 }
4079
Tim Northovera2ee4332014-03-29 15:09:45 +00004080 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4081}
4082
Tim Northover573cbee2014-05-24 12:52:07 +00004083ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004084 if (RetTy->isVoidType())
4085 return ABIArgInfo::getIgnore();
4086
4087 // Large vector types should be returned via memory.
4088 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4089 return ABIArgInfo::getIndirect(0);
4090
4091 if (!isAggregateTypeForABI(RetTy)) {
4092 // Treat an enum type as its underlying type.
4093 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4094 RetTy = EnumTy->getDecl()->getIntegerType();
4095
Tim Northover4dab6982014-04-18 13:46:08 +00004096 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4097 ? ABIArgInfo::getExtend()
4098 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004099 }
4100
Tim Northovera2ee4332014-03-29 15:09:45 +00004101 if (isEmptyRecord(getContext(), RetTy, true))
4102 return ABIArgInfo::getIgnore();
4103
Craig Topper8a13c412014-05-21 05:09:00 +00004104 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004105 uint64_t Members = 0;
4106 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004107 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4108 return ABIArgInfo::getDirect();
4109
4110 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4111 uint64_t Size = getContext().getTypeSize(RetTy);
4112 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004113 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004114 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004115
4116 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4117 // For aggregates with 16-byte alignment, we use i128.
4118 if (Alignment < 128 && Size == 128) {
4119 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4120 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4121 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004122 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4123 }
4124
4125 return ABIArgInfo::getIndirect(0);
4126}
4127
Tim Northover573cbee2014-05-24 12:52:07 +00004128/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4129bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004130 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4131 // Check whether VT is legal.
4132 unsigned NumElements = VT->getNumElements();
4133 uint64_t Size = getContext().getTypeSize(VT);
4134 // NumElements should be power of 2 between 1 and 16.
4135 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4136 return true;
4137 return Size != 64 && (Size != 128 || NumElements == 1);
4138 }
4139 return false;
4140}
4141
Reid Klecknere9f6a712014-10-31 17:10:41 +00004142bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4143 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4144 // point type or a short-vector type. This is the same as the 32-bit ABI,
4145 // but with the difference that any floating-point type is allowed,
4146 // including __fp16.
4147 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4148 if (BT->isFloatingPoint())
4149 return true;
4150 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4151 unsigned VecSize = getContext().getTypeSize(VT);
4152 if (VecSize == 64 || VecSize == 128)
4153 return true;
4154 }
4155 return false;
4156}
4157
4158bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4159 uint64_t Members) const {
4160 return Members <= 4;
4161}
4162
Tim Northoverb047bfa2014-11-27 21:02:49 +00004163llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4164 QualType Ty,
4165 CodeGenFunction &CGF) const {
4166 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004167 bool IsIndirect = AI.isIndirect();
4168
Tim Northoverb047bfa2014-11-27 21:02:49 +00004169 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4170 if (IsIndirect)
4171 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4172 else if (AI.getCoerceToType())
4173 BaseTy = AI.getCoerceToType();
4174
4175 unsigned NumRegs = 1;
4176 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4177 BaseTy = ArrTy->getElementType();
4178 NumRegs = ArrTy->getNumElements();
4179 }
4180 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4181
Tim Northovera2ee4332014-03-29 15:09:45 +00004182 // The AArch64 va_list type and handling is specified in the Procedure Call
4183 // Standard, section B.4:
4184 //
4185 // struct {
4186 // void *__stack;
4187 // void *__gr_top;
4188 // void *__vr_top;
4189 // int __gr_offs;
4190 // int __vr_offs;
4191 // };
4192
4193 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4194 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4195 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4196 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4197 auto &Ctx = CGF.getContext();
4198
Craig Topper8a13c412014-05-21 05:09:00 +00004199 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004200 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004201 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4202 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004203 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004204 reg_offs_p =
4205 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004206 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4207 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004208 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004209 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004210 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004211 reg_offs_p =
4212 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004213 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4214 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004215 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004216 }
4217
4218 //=======================================
4219 // Find out where argument was passed
4220 //=======================================
4221
4222 // If reg_offs >= 0 we're already using the stack for this type of
4223 // argument. We don't want to keep updating reg_offs (in case it overflows,
4224 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4225 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004226 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004227 UsingStack = CGF.Builder.CreateICmpSGE(
4228 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4229
4230 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4231
4232 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004233 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004234 CGF.EmitBlock(MaybeRegBlock);
4235
4236 // Integer arguments may need to correct register alignment (for example a
4237 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4238 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004239 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004240 int Align = Ctx.getTypeAlign(Ty) / 8;
4241
4242 reg_offs = CGF.Builder.CreateAdd(
4243 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4244 "align_regoffs");
4245 reg_offs = CGF.Builder.CreateAnd(
4246 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4247 "aligned_regoffs");
4248 }
4249
4250 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004251 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004252 NewOffset = CGF.Builder.CreateAdd(
4253 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4254 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4255
4256 // Now we're in a position to decide whether this argument really was in
4257 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004258 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004259 InRegs = CGF.Builder.CreateICmpSLE(
4260 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4261
4262 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4263
4264 //=======================================
4265 // Argument was in registers
4266 //=======================================
4267
4268 // Now we emit the code for if the argument was originally passed in
4269 // registers. First start the appropriate block:
4270 CGF.EmitBlock(InRegBlock);
4271
Craig Topper8a13c412014-05-21 05:09:00 +00004272 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
David Blaikie2e804282015-04-05 22:47:07 +00004273 reg_top_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, reg_top_index,
4274 "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004275 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4276 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004277 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004278 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4279
4280 if (IsIndirect) {
4281 // If it's been passed indirectly (actually a struct), whatever we find from
4282 // stored registers or on the stack will actually be a struct **.
4283 MemTy = llvm::PointerType::getUnqual(MemTy);
4284 }
4285
Craig Topper8a13c412014-05-21 05:09:00 +00004286 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004287 uint64_t NumMembers = 0;
4288 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004289 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004290 // Homogeneous aggregates passed in registers will have their elements split
4291 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4292 // qN+1, ...). We reload and store into a temporary local variable
4293 // contiguously.
4294 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4295 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4296 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
David Blaikie1ed728c2015-04-05 22:45:47 +00004297 llvm::AllocaInst *Tmp = CGF.CreateTempAlloca(HFATy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004298 int Offset = 0;
4299
4300 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4301 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4302 for (unsigned i = 0; i < NumMembers; ++i) {
4303 llvm::Value *BaseOffset =
4304 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4305 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4306 LoadAddr = CGF.Builder.CreateBitCast(
4307 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
David Blaikie2e804282015-04-05 22:47:07 +00004308 llvm::Value *StoreAddr =
4309 CGF.Builder.CreateStructGEP(Tmp->getAllocatedType(), Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00004310
4311 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4312 CGF.Builder.CreateStore(Elem, StoreAddr);
4313 }
4314
4315 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4316 } else {
4317 // Otherwise the object is contiguous in memory
4318 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004319 if (CGF.CGM.getDataLayout().isBigEndian() &&
4320 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004321 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4322 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4323 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4324
4325 BaseAddr = CGF.Builder.CreateAdd(
4326 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4327
4328 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4329 }
4330
4331 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4332 }
4333
4334 CGF.EmitBranch(ContBlock);
4335
4336 //=======================================
4337 // Argument was on the stack
4338 //=======================================
4339 CGF.EmitBlock(OnStackBlock);
4340
Craig Topper8a13c412014-05-21 05:09:00 +00004341 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
David Blaikie1ed728c2015-04-05 22:45:47 +00004342 stack_p = CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 0, "stack_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004343 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4344
4345 // Again, stack arguments may need realigmnent. In this case both integer and
4346 // floating-point ones might be affected.
4347 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4348 int Align = Ctx.getTypeAlign(Ty) / 8;
4349
4350 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4351
4352 OnStackAddr = CGF.Builder.CreateAdd(
4353 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4354 "align_stack");
4355 OnStackAddr = CGF.Builder.CreateAnd(
4356 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4357 "align_stack");
4358
4359 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4360 }
4361
4362 uint64_t StackSize;
4363 if (IsIndirect)
4364 StackSize = 8;
4365 else
4366 StackSize = Ctx.getTypeSize(Ty) / 8;
4367
4368 // All stack slots are 8 bytes
4369 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4370
4371 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4372 llvm::Value *NewStack =
4373 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4374
4375 // Write the new value of __stack for the next call to va_arg
4376 CGF.Builder.CreateStore(NewStack, stack_p);
4377
4378 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4379 Ctx.getTypeSize(Ty) < 64) {
4380 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4381 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4382
4383 OnStackAddr = CGF.Builder.CreateAdd(
4384 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4385
4386 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4387 }
4388
4389 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4390
4391 CGF.EmitBranch(ContBlock);
4392
4393 //=======================================
4394 // Tidy up
4395 //=======================================
4396 CGF.EmitBlock(ContBlock);
4397
4398 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4399 ResAddr->addIncoming(RegAddr, InRegBlock);
4400 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4401
4402 if (IsIndirect)
4403 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4404
4405 return ResAddr;
4406}
4407
Eric Christopher7565e0d2015-05-29 23:09:49 +00004408llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr,
4409 QualType Ty,
4410 CodeGenFunction &CGF) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004411 // We do not support va_arg for aggregates or illegal vector types.
4412 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4413 // other cases.
4414 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004415 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004416
4417 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4418 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4419
Craig Topper8a13c412014-05-21 05:09:00 +00004420 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004421 uint64_t Members = 0;
4422 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004423
4424 bool isIndirect = false;
4425 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4426 // be passed indirectly.
4427 if (Size > 16 && !isHA) {
4428 isIndirect = true;
4429 Size = 8;
4430 Align = 8;
4431 }
4432
4433 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4434 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4435
4436 CGBuilderTy &Builder = CGF.Builder;
4437 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4438 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4439
4440 if (isEmptyRecord(getContext(), Ty, true)) {
4441 // These are ignored for parameter passing purposes.
4442 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4443 return Builder.CreateBitCast(Addr, PTy);
4444 }
4445
4446 const uint64_t MinABIAlign = 8;
4447 if (Align > MinABIAlign) {
4448 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4449 Addr = Builder.CreateGEP(Addr, Offset);
4450 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4451 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4452 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4453 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4454 }
4455
4456 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4457 llvm::Value *NextAddr = Builder.CreateGEP(
4458 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4459 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4460
4461 if (isIndirect)
4462 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4463 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4464 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4465
4466 return AddrTyped;
4467}
4468
4469//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004470// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004471//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004472
4473namespace {
4474
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004475class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004476public:
4477 enum ABIKind {
4478 APCS = 0,
4479 AAPCS = 1,
4480 AAPCS_VFP
4481 };
4482
4483private:
4484 ABIKind Kind;
4485
4486public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004487 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004488 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004489 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004490
John McCall3480ef22011-08-30 01:42:09 +00004491 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004492 switch (getTarget().getTriple().getEnvironment()) {
4493 case llvm::Triple::Android:
4494 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004495 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004496 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004497 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004498 return true;
4499 default:
4500 return false;
4501 }
John McCall3480ef22011-08-30 01:42:09 +00004502 }
4503
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004504 bool isEABIHF() const {
4505 switch (getTarget().getTriple().getEnvironment()) {
4506 case llvm::Triple::EABIHF:
4507 case llvm::Triple::GNUEABIHF:
4508 return true;
4509 default:
4510 return false;
4511 }
4512 }
4513
Daniel Dunbar020daa92009-09-12 01:00:39 +00004514 ABIKind getABIKind() const { return Kind; }
4515
Tim Northovera484bc02013-10-01 14:34:25 +00004516private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004517 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004518 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004519 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004520
Reid Klecknere9f6a712014-10-31 17:10:41 +00004521 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4522 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4523 uint64_t Members) const override;
4524
Craig Topper4f12f102014-03-12 06:41:41 +00004525 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004526
Craig Topper4f12f102014-03-12 06:41:41 +00004527 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4528 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004529
4530 llvm::CallingConv::ID getLLVMDefaultCC() const;
4531 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004532 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004533};
4534
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004535class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4536public:
Chris Lattner2b037972010-07-29 02:01:43 +00004537 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4538 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004539
John McCall3480ef22011-08-30 01:42:09 +00004540 const ARMABIInfo &getABIInfo() const {
4541 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4542 }
4543
Craig Topper4f12f102014-03-12 06:41:41 +00004544 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004545 return 13;
4546 }
Roman Divackyc1617352011-05-18 19:36:54 +00004547
Craig Topper4f12f102014-03-12 06:41:41 +00004548 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004549 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4550 }
4551
Roman Divackyc1617352011-05-18 19:36:54 +00004552 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004553 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004554 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004555
4556 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004557 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004558 return false;
4559 }
John McCall3480ef22011-08-30 01:42:09 +00004560
Craig Topper4f12f102014-03-12 06:41:41 +00004561 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004562 if (getABIInfo().isEABI()) return 88;
4563 return TargetCodeGenInfo::getSizeOfUnwindException();
4564 }
Tim Northovera484bc02013-10-01 14:34:25 +00004565
Eric Christopher162c91c2015-06-05 22:03:00 +00004566 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004567 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004568 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4569 if (!FD)
4570 return;
4571
4572 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4573 if (!Attr)
4574 return;
4575
4576 const char *Kind;
4577 switch (Attr->getInterrupt()) {
4578 case ARMInterruptAttr::Generic: Kind = ""; break;
4579 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4580 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4581 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4582 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4583 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4584 }
4585
4586 llvm::Function *Fn = cast<llvm::Function>(GV);
4587
4588 Fn->addFnAttr("interrupt", Kind);
4589
4590 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4591 return;
4592
4593 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4594 // however this is not necessarily true on taking any interrupt. Instruct
4595 // the backend to perform a realignment as part of the function prologue.
4596 llvm::AttrBuilder B;
4597 B.addStackAlignmentAttr(8);
4598 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4599 llvm::AttributeSet::get(CGM.getLLVMContext(),
4600 llvm::AttributeSet::FunctionIndex,
4601 B));
4602 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004603};
4604
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004605class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4606 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4607 CodeGen::CodeGenModule &CGM) const;
4608
4609public:
4610 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4611 : ARMTargetCodeGenInfo(CGT, K) {}
4612
Eric Christopher162c91c2015-06-05 22:03:00 +00004613 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004614 CodeGen::CodeGenModule &CGM) const override;
4615};
4616
4617void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4618 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4619 if (!isa<FunctionDecl>(D))
4620 return;
4621 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4622 return;
4623
4624 llvm::Function *F = cast<llvm::Function>(GV);
4625 F->addFnAttr("stack-probe-size",
4626 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4627}
4628
Eric Christopher162c91c2015-06-05 22:03:00 +00004629void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004630 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004631 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004632 addStackProbeSizeTargetAttribute(D, GV, CGM);
4633}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004634}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004635
Chris Lattner22326a12010-07-29 02:31:05 +00004636void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004637 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004638 FI.getReturnInfo() =
4639 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004640
Tim Northoverbc784d12015-02-24 17:22:40 +00004641 for (auto &I : FI.arguments())
4642 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004643
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004644 // Always honor user-specified calling convention.
4645 if (FI.getCallingConvention() != llvm::CallingConv::C)
4646 return;
4647
John McCall882987f2013-02-28 19:01:20 +00004648 llvm::CallingConv::ID cc = getRuntimeCC();
4649 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004650 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004651}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004652
John McCall882987f2013-02-28 19:01:20 +00004653/// Return the default calling convention that LLVM will use.
4654llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4655 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004656 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004657 return llvm::CallingConv::ARM_AAPCS_VFP;
4658 else if (isEABI())
4659 return llvm::CallingConv::ARM_AAPCS;
4660 else
4661 return llvm::CallingConv::ARM_APCS;
4662}
4663
4664/// Return the calling convention that our ABI would like us to use
4665/// as the C calling convention.
4666llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004667 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004668 case APCS: return llvm::CallingConv::ARM_APCS;
4669 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4670 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004671 }
John McCall882987f2013-02-28 19:01:20 +00004672 llvm_unreachable("bad ABI kind");
4673}
4674
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004675void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004676 assert(getRuntimeCC() == llvm::CallingConv::C);
4677
4678 // Don't muddy up the IR with a ton of explicit annotations if
4679 // they'd just match what LLVM will infer from the triple.
4680 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4681 if (abiCC != getLLVMDefaultCC())
4682 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004683
4684 BuiltinCC = (getABIKind() == APCS ?
4685 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004686}
4687
Tim Northoverbc784d12015-02-24 17:22:40 +00004688ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4689 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004690 // 6.1.2.1 The following argument types are VFP CPRCs:
4691 // A single-precision floating-point type (including promoted
4692 // half-precision types); A double-precision floating-point type;
4693 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4694 // with a Base Type of a single- or double-precision floating-point type,
4695 // 64-bit containerized vectors or 128-bit containerized vectors with one
4696 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004697 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004698
Reid Klecknerb1be6832014-11-15 01:41:41 +00004699 Ty = useFirstFieldIfTransparentUnion(Ty);
4700
Manman Renfef9e312012-10-16 19:18:39 +00004701 // Handle illegal vector types here.
4702 if (isIllegalVectorType(Ty)) {
4703 uint64_t Size = getContext().getTypeSize(Ty);
4704 if (Size <= 32) {
4705 llvm::Type *ResType =
4706 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004707 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004708 }
4709 if (Size == 64) {
4710 llvm::Type *ResType = llvm::VectorType::get(
4711 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004712 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004713 }
4714 if (Size == 128) {
4715 llvm::Type *ResType = llvm::VectorType::get(
4716 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004717 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004718 }
4719 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4720 }
4721
John McCalla1dee5302010-08-22 10:59:02 +00004722 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004723 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004724 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004725 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004726 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004727
Tim Northover5a1558e2014-11-07 22:30:50 +00004728 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4729 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004730 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004731
Oliver Stannard405bded2014-02-11 09:25:50 +00004732 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004733 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004734 }
Tim Northover1060eae2013-06-21 22:49:34 +00004735
Daniel Dunbar09d33622009-09-14 21:54:03 +00004736 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004737 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004738 return ABIArgInfo::getIgnore();
4739
Tim Northover5a1558e2014-11-07 22:30:50 +00004740 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004741 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4742 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004743 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004744 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004745 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004746 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004747 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004748 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004749 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004750 }
4751
Manman Ren6c30e132012-08-13 21:23:55 +00004752 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004753 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4754 // most 8-byte. We realign the indirect argument if type alignment is bigger
4755 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004756 uint64_t ABIAlign = 4;
4757 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4758 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004759 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004760 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004761
Manman Ren8cd99812012-11-06 04:58:01 +00004762 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004763 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004764 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004765 }
4766
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004767 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004768 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004769 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004770 // FIXME: Try to match the types of the arguments more accurately where
4771 // we can.
4772 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004773 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4774 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004775 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004776 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4777 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004778 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004779
Tim Northover5a1558e2014-11-07 22:30:50 +00004780 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004781}
4782
Chris Lattner458b2aa2010-07-29 02:16:43 +00004783static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004784 llvm::LLVMContext &VMContext) {
4785 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4786 // is called integer-like if its size is less than or equal to one word, and
4787 // the offset of each of its addressable sub-fields is zero.
4788
4789 uint64_t Size = Context.getTypeSize(Ty);
4790
4791 // Check that the type fits in a word.
4792 if (Size > 32)
4793 return false;
4794
4795 // FIXME: Handle vector types!
4796 if (Ty->isVectorType())
4797 return false;
4798
Daniel Dunbard53bac72009-09-14 02:20:34 +00004799 // Float types are never treated as "integer like".
4800 if (Ty->isRealFloatingType())
4801 return false;
4802
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004803 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004804 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004805 return true;
4806
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004807 // Small complex integer types are "integer like".
4808 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4809 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004810
4811 // Single element and zero sized arrays should be allowed, by the definition
4812 // above, but they are not.
4813
4814 // Otherwise, it must be a record type.
4815 const RecordType *RT = Ty->getAs<RecordType>();
4816 if (!RT) return false;
4817
4818 // Ignore records with flexible arrays.
4819 const RecordDecl *RD = RT->getDecl();
4820 if (RD->hasFlexibleArrayMember())
4821 return false;
4822
4823 // Check that all sub-fields are at offset 0, and are themselves "integer
4824 // like".
4825 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4826
4827 bool HadField = false;
4828 unsigned idx = 0;
4829 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4830 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004831 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004832
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004833 // Bit-fields are not addressable, we only need to verify they are "integer
4834 // like". We still have to disallow a subsequent non-bitfield, for example:
4835 // struct { int : 0; int x }
4836 // is non-integer like according to gcc.
4837 if (FD->isBitField()) {
4838 if (!RD->isUnion())
4839 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004840
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004841 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4842 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004843
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004844 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004845 }
4846
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004847 // Check if this field is at offset 0.
4848 if (Layout.getFieldOffset(idx) != 0)
4849 return false;
4850
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004851 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4852 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004853
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004854 // Only allow at most one field in a structure. This doesn't match the
4855 // wording above, but follows gcc in situations with a field following an
4856 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004857 if (!RD->isUnion()) {
4858 if (HadField)
4859 return false;
4860
4861 HadField = true;
4862 }
4863 }
4864
4865 return true;
4866}
4867
Oliver Stannard405bded2014-02-11 09:25:50 +00004868ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4869 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004870 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004871
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004872 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004873 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004874
Daniel Dunbar19964db2010-09-23 01:54:32 +00004875 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004876 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004877 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004878 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004879
John McCalla1dee5302010-08-22 10:59:02 +00004880 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004881 // Treat an enum type as its underlying type.
4882 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4883 RetTy = EnumTy->getDecl()->getIntegerType();
4884
Tim Northover5a1558e2014-11-07 22:30:50 +00004885 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4886 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004887 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004888
4889 // Are we following APCS?
4890 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004891 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004892 return ABIArgInfo::getIgnore();
4893
Daniel Dunbareedf1512010-02-01 23:31:19 +00004894 // Complex types are all returned as packed integers.
4895 //
4896 // FIXME: Consider using 2 x vector types if the back end handles them
4897 // correctly.
4898 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004899 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4900 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004901
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004902 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004903 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004904 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004905 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004906 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004907 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004908 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004909 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4910 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004911 }
4912
4913 // Otherwise return in memory.
4914 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004915 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004916
4917 // Otherwise this is an AAPCS variant.
4918
Chris Lattner458b2aa2010-07-29 02:16:43 +00004919 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004920 return ABIArgInfo::getIgnore();
4921
Bob Wilson1d9269a2011-11-02 04:51:36 +00004922 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004923 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004924 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004925 uint64_t Members;
4926 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004927 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004928 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004929 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004930 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004931 }
4932
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004933 // Aggregates <= 4 bytes are returned in r0; other aggregates
4934 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004935 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004936 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004937 if (getDataLayout().isBigEndian())
4938 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004939 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004940
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004941 // Return in the smallest viable integer type.
4942 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004943 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004944 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004945 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4946 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004947 }
4948
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004949 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004950}
4951
Manman Renfef9e312012-10-16 19:18:39 +00004952/// isIllegalVector - check whether Ty is an illegal vector type.
4953bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4954 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4955 // Check whether VT is legal.
4956 unsigned NumElements = VT->getNumElements();
4957 uint64_t Size = getContext().getTypeSize(VT);
4958 // NumElements should be power of 2.
4959 if ((NumElements & (NumElements - 1)) != 0)
4960 return true;
4961 // Size should be greater than 32 bits.
4962 return Size <= 32;
4963 }
4964 return false;
4965}
4966
Reid Klecknere9f6a712014-10-31 17:10:41 +00004967bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4968 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4969 // double, or 64-bit or 128-bit vectors.
4970 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4971 if (BT->getKind() == BuiltinType::Float ||
4972 BT->getKind() == BuiltinType::Double ||
4973 BT->getKind() == BuiltinType::LongDouble)
4974 return true;
4975 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4976 unsigned VecSize = getContext().getTypeSize(VT);
4977 if (VecSize == 64 || VecSize == 128)
4978 return true;
4979 }
4980 return false;
4981}
4982
4983bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4984 uint64_t Members) const {
4985 return Members <= 4;
4986}
4987
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004988llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004989 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004990 llvm::Type *BP = CGF.Int8PtrTy;
4991 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004992
4993 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004994 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004995 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004996
Tim Northover1711cc92013-06-21 23:05:33 +00004997 if (isEmptyRecord(getContext(), Ty, true)) {
4998 // These are ignored for parameter passing purposes.
4999 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5000 return Builder.CreateBitCast(Addr, PTy);
5001 }
5002
Manman Rencca54d02012-10-16 19:01:37 +00005003 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00005004 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00005005 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00005006
5007 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5008 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00005009 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5010 getABIKind() == ARMABIInfo::AAPCS)
5011 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5012 else
5013 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00005014 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5015 if (isIllegalVectorType(Ty) && Size > 16) {
5016 IsIndirect = true;
5017 Size = 4;
5018 TyAlign = 4;
5019 }
Manman Rencca54d02012-10-16 19:01:37 +00005020
5021 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00005022 if (TyAlign > 4) {
5023 assert((TyAlign & (TyAlign - 1)) == 0 &&
5024 "Alignment is not power of 2!");
5025 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5026 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5027 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005028 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005029 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005030
5031 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005032 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005033 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005034 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005035 "ap.next");
5036 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5037
Manman Renfef9e312012-10-16 19:18:39 +00005038 if (IsIndirect)
5039 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005040 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005041 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5042 // may not be correctly aligned for the vector type. We create an aligned
5043 // temporary space and copy the content over from ap.cur to the temporary
5044 // space. This is necessary if the natural alignment of the type is greater
5045 // than the ABI alignment.
5046 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5047 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5048 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5049 "var.align");
5050 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5051 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5052 Builder.CreateMemCpy(Dst, Src,
5053 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5054 TyAlign, false);
5055 Addr = AlignedTemp; //The content is in aligned location.
5056 }
5057 llvm::Type *PTy =
5058 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5059 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5060
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005061 return AddrTyped;
5062}
5063
Chris Lattner0cf24192010-06-28 20:05:43 +00005064//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005065// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005066//===----------------------------------------------------------------------===//
5067
5068namespace {
5069
Justin Holewinski83e96682012-05-24 17:43:12 +00005070class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005071public:
Justin Holewinski36837432013-03-30 14:38:24 +00005072 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005073
5074 ABIArgInfo classifyReturnType(QualType RetTy) const;
5075 ABIArgInfo classifyArgumentType(QualType Ty) const;
5076
Craig Topper4f12f102014-03-12 06:41:41 +00005077 void computeInfo(CGFunctionInfo &FI) const override;
5078 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5079 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005080};
5081
Justin Holewinski83e96682012-05-24 17:43:12 +00005082class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005083public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005084 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5085 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005086
Eric Christopher162c91c2015-06-05 22:03:00 +00005087 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005088 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005089private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005090 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5091 // resulting MDNode to the nvvm.annotations MDNode.
5092 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005093};
5094
Justin Holewinski83e96682012-05-24 17:43:12 +00005095ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005096 if (RetTy->isVoidType())
5097 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005098
5099 // note: this is different from default ABI
5100 if (!RetTy->isScalarType())
5101 return ABIArgInfo::getDirect();
5102
5103 // Treat an enum type as its underlying type.
5104 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5105 RetTy = EnumTy->getDecl()->getIntegerType();
5106
5107 return (RetTy->isPromotableIntegerType() ?
5108 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005109}
5110
Justin Holewinski83e96682012-05-24 17:43:12 +00005111ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005112 // Treat an enum type as its underlying type.
5113 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5114 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005115
Eli Bendersky95338a02014-10-29 13:43:21 +00005116 // Return aggregates type as indirect by value
5117 if (isAggregateTypeForABI(Ty))
5118 return ABIArgInfo::getIndirect(0, /* byval */ true);
5119
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005120 return (Ty->isPromotableIntegerType() ?
5121 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005122}
5123
Justin Holewinski83e96682012-05-24 17:43:12 +00005124void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005125 if (!getCXXABI().classifyReturnType(FI))
5126 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005127 for (auto &I : FI.arguments())
5128 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005129
5130 // Always honor user-specified calling convention.
5131 if (FI.getCallingConvention() != llvm::CallingConv::C)
5132 return;
5133
John McCall882987f2013-02-28 19:01:20 +00005134 FI.setEffectiveCallingConvention(getRuntimeCC());
5135}
5136
Justin Holewinski83e96682012-05-24 17:43:12 +00005137llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5138 CodeGenFunction &CFG) const {
5139 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005140}
5141
Justin Holewinski83e96682012-05-24 17:43:12 +00005142void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005143setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005144 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005145 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5146 if (!FD) return;
5147
5148 llvm::Function *F = cast<llvm::Function>(GV);
5149
5150 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005151 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005152 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005153 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005154 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005155 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005156 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5157 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005158 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005159 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005160 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005161 }
Justin Holewinski38031972011-10-05 17:58:44 +00005162
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005163 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005164 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005165 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005166 // __global__ functions cannot be called from the device, we do not
5167 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005168 if (FD->hasAttr<CUDAGlobalAttr>()) {
5169 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5170 addNVVMMetadata(F, "kernel", 1);
5171 }
Artem Belevich7093e402015-04-21 22:55:54 +00005172 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005173 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005174 llvm::APSInt MaxThreads(32);
5175 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5176 if (MaxThreads > 0)
5177 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5178
5179 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5180 // not specified in __launch_bounds__ or if the user specified a 0 value,
5181 // we don't have to add a PTX directive.
5182 if (Attr->getMinBlocks()) {
5183 llvm::APSInt MinBlocks(32);
5184 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5185 if (MinBlocks > 0)
5186 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5187 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005188 }
5189 }
Justin Holewinski38031972011-10-05 17:58:44 +00005190 }
5191}
5192
Eli Benderskye06a2c42014-04-15 16:57:05 +00005193void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5194 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005195 llvm::Module *M = F->getParent();
5196 llvm::LLVMContext &Ctx = M->getContext();
5197
5198 // Get "nvvm.annotations" metadata node
5199 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5200
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005201 llvm::Metadata *MDVals[] = {
5202 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5203 llvm::ConstantAsMetadata::get(
5204 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005205 // Append metadata to nvvm.annotations
5206 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5207}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005208}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005209
5210//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005211// SystemZ ABI Implementation
5212//===----------------------------------------------------------------------===//
5213
5214namespace {
5215
5216class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005217 bool HasVector;
5218
Ulrich Weigand47445072013-05-06 16:26:41 +00005219public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005220 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5221 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005222
5223 bool isPromotableIntegerType(QualType Ty) const;
5224 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005225 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005226 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005227 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005228
5229 ABIArgInfo classifyReturnType(QualType RetTy) const;
5230 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5231
Craig Topper4f12f102014-03-12 06:41:41 +00005232 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005233 if (!getCXXABI().classifyReturnType(FI))
5234 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005235 for (auto &I : FI.arguments())
5236 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005237 }
5238
Craig Topper4f12f102014-03-12 06:41:41 +00005239 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5240 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005241};
5242
5243class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5244public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005245 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5246 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005247};
5248
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005249}
Ulrich Weigand47445072013-05-06 16:26:41 +00005250
5251bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5252 // Treat an enum type as its underlying type.
5253 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5254 Ty = EnumTy->getDecl()->getIntegerType();
5255
5256 // Promotable integer types are required to be promoted by the ABI.
5257 if (Ty->isPromotableIntegerType())
5258 return true;
5259
5260 // 32-bit values must also be promoted.
5261 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5262 switch (BT->getKind()) {
5263 case BuiltinType::Int:
5264 case BuiltinType::UInt:
5265 return true;
5266 default:
5267 return false;
5268 }
5269 return false;
5270}
5271
5272bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005273 return (Ty->isAnyComplexType() ||
5274 Ty->isVectorType() ||
5275 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005276}
5277
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005278bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5279 return (HasVector &&
5280 Ty->isVectorType() &&
5281 getContext().getTypeSize(Ty) <= 128);
5282}
5283
Ulrich Weigand47445072013-05-06 16:26:41 +00005284bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5285 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5286 switch (BT->getKind()) {
5287 case BuiltinType::Float:
5288 case BuiltinType::Double:
5289 return true;
5290 default:
5291 return false;
5292 }
5293
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005294 return false;
5295}
5296
5297QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005298 if (const RecordType *RT = Ty->getAsStructureType()) {
5299 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005300 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005301
5302 // If this is a C++ record, check the bases first.
5303 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005304 for (const auto &I : CXXRD->bases()) {
5305 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005306
5307 // Empty bases don't affect things either way.
5308 if (isEmptyRecord(getContext(), Base, true))
5309 continue;
5310
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005311 if (!Found.isNull())
5312 return Ty;
5313 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005314 }
5315
5316 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005317 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005318 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005319 // Unlike isSingleElementStruct(), empty structure and array fields
5320 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005321 if (getContext().getLangOpts().CPlusPlus &&
5322 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5323 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005324
5325 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005326 // Nested structures still do though.
5327 if (!Found.isNull())
5328 return Ty;
5329 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005330 }
5331
5332 // Unlike isSingleElementStruct(), trailing padding is allowed.
5333 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005334 if (!Found.isNull())
5335 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005336 }
5337
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005338 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005339}
5340
5341llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5342 CodeGenFunction &CGF) const {
5343 // Assume that va_list type is correct; should be pointer to LLVM type:
5344 // struct {
5345 // i64 __gpr;
5346 // i64 __fpr;
5347 // i8 *__overflow_arg_area;
5348 // i8 *__reg_save_area;
5349 // };
5350
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005351 // Every non-vector argument occupies 8 bytes and is passed by preference
5352 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5353 // always passed on the stack.
Ulrich Weigand47445072013-05-06 16:26:41 +00005354 Ty = CGF.getContext().getCanonicalType(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005355 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
5356 llvm::Type *APTy = llvm::PointerType::getUnqual(ArgTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005357 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005358 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005359 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005360 bool IsVector = false;
Ulrich Weigand47445072013-05-06 16:26:41 +00005361 unsigned UnpaddedBitSize;
5362 if (IsIndirect) {
5363 APTy = llvm::PointerType::getUnqual(APTy);
5364 UnpaddedBitSize = 64;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005365 } else {
5366 if (AI.getCoerceToType())
5367 ArgTy = AI.getCoerceToType();
5368 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005369 IsVector = ArgTy->isVectorTy();
Ulrich Weigand47445072013-05-06 16:26:41 +00005370 UnpaddedBitSize = getContext().getTypeSize(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005371 }
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005372 unsigned PaddedBitSize = (IsVector && UnpaddedBitSize > 64) ? 128 : 64;
Ulrich Weigand47445072013-05-06 16:26:41 +00005373 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5374
5375 unsigned PaddedSize = PaddedBitSize / 8;
5376 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5377
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005378 llvm::Type *IndexTy = CGF.Int64Ty;
5379 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5380
5381 if (IsVector) {
5382 // Work out the address of a vector argument on the stack.
5383 // Vector arguments are always passed in the high bits of a
5384 // single (8 byte) or double (16 byte) stack slot.
5385 llvm::Value *OverflowArgAreaPtr =
5386 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 2,
5387 "overflow_arg_area_ptr");
5388 llvm::Value *OverflowArgArea =
5389 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5390 llvm::Value *MemAddr =
5391 CGF.Builder.CreateBitCast(OverflowArgArea, APTy, "mem_addr");
5392
5393 // Update overflow_arg_area_ptr pointer
5394 llvm::Value *NewOverflowArgArea =
5395 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5396 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5397
5398 return MemAddr;
5399 }
5400
Ulrich Weigand47445072013-05-06 16:26:41 +00005401 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5402 if (InFPRs) {
5403 MaxRegs = 4; // Maximum of 4 FPR arguments
5404 RegCountField = 1; // __fpr
5405 RegSaveIndex = 16; // save offset for f0
5406 RegPadding = 0; // floats are passed in the high bits of an FPR
5407 } else {
5408 MaxRegs = 5; // Maximum of 5 GPR arguments
5409 RegCountField = 0; // __gpr
5410 RegSaveIndex = 2; // save offset for r2
5411 RegPadding = Padding; // values are passed in the low bits of a GPR
5412 }
5413
David Blaikie2e804282015-04-05 22:47:07 +00005414 llvm::Value *RegCountPtr = CGF.Builder.CreateStructGEP(
5415 nullptr, VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005416 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005417 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5418 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005419 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005420
5421 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5422 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5423 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5424 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5425
5426 // Emit code to load the value if it was passed in registers.
5427 CGF.EmitBlock(InRegBlock);
5428
5429 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005430 llvm::Value *ScaledRegCount =
5431 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5432 llvm::Value *RegBase =
5433 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5434 llvm::Value *RegOffset =
5435 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5436 llvm::Value *RegSaveAreaPtr =
David Blaikie2e804282015-04-05 22:47:07 +00005437 CGF.Builder.CreateStructGEP(nullptr, VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005438 llvm::Value *RegSaveArea =
5439 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5440 llvm::Value *RawRegAddr =
5441 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5442 llvm::Value *RegAddr =
5443 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5444
5445 // Update the register count
5446 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5447 llvm::Value *NewRegCount =
5448 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5449 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5450 CGF.EmitBranch(ContBlock);
5451
5452 // Emit code to load the value if it was passed in memory.
5453 CGF.EmitBlock(InMemBlock);
5454
5455 // Work out the address of a stack argument.
David Blaikie2e804282015-04-05 22:47:07 +00005456 llvm::Value *OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5457 nullptr, VAListAddr, 2, "overflow_arg_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005458 llvm::Value *OverflowArgArea =
5459 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5460 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5461 llvm::Value *RawMemAddr =
5462 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5463 llvm::Value *MemAddr =
5464 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5465
5466 // Update overflow_arg_area_ptr pointer
5467 llvm::Value *NewOverflowArgArea =
5468 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5469 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5470 CGF.EmitBranch(ContBlock);
5471
5472 // Return the appropriate result.
5473 CGF.EmitBlock(ContBlock);
5474 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5475 ResAddr->addIncoming(RegAddr, InRegBlock);
5476 ResAddr->addIncoming(MemAddr, InMemBlock);
5477
5478 if (IsIndirect)
5479 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5480
5481 return ResAddr;
5482}
5483
Ulrich Weigand47445072013-05-06 16:26:41 +00005484ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5485 if (RetTy->isVoidType())
5486 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005487 if (isVectorArgumentType(RetTy))
5488 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005489 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5490 return ABIArgInfo::getIndirect(0);
5491 return (isPromotableIntegerType(RetTy) ?
5492 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5493}
5494
5495ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5496 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005497 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005498 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5499
5500 // Integers and enums are extended to full register width.
5501 if (isPromotableIntegerType(Ty))
5502 return ABIArgInfo::getExtend();
5503
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005504 // Handle vector types and vector-like structure types. Note that
5505 // as opposed to float-like structure types, we do not allow any
5506 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005507 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005508 QualType SingleElementTy = GetSingleElementType(Ty);
5509 if (isVectorArgumentType(SingleElementTy) &&
5510 getContext().getTypeSize(SingleElementTy) == Size)
5511 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5512
5513 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005514 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005515 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005516
5517 // Handle small structures.
5518 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5519 // Structures with flexible arrays have variable length, so really
5520 // fail the size test above.
5521 const RecordDecl *RD = RT->getDecl();
5522 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005523 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005524
5525 // The structure is passed as an unextended integer, a float, or a double.
5526 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005527 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005528 assert(Size == 32 || Size == 64);
5529 if (Size == 32)
5530 PassTy = llvm::Type::getFloatTy(getVMContext());
5531 else
5532 PassTy = llvm::Type::getDoubleTy(getVMContext());
5533 } else
5534 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5535 return ABIArgInfo::getDirect(PassTy);
5536 }
5537
5538 // Non-structure compounds are passed indirectly.
5539 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005540 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005541
Craig Topper8a13c412014-05-21 05:09:00 +00005542 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005543}
5544
5545//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005546// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005547//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005548
5549namespace {
5550
5551class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5552public:
Chris Lattner2b037972010-07-29 02:01:43 +00005553 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5554 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005555 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005556 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005557};
5558
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005559}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005560
Eric Christopher162c91c2015-06-05 22:03:00 +00005561void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005562 llvm::GlobalValue *GV,
5563 CodeGen::CodeGenModule &M) const {
5564 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5565 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5566 // Handle 'interrupt' attribute:
5567 llvm::Function *F = cast<llvm::Function>(GV);
5568
5569 // Step 1: Set ISR calling convention.
5570 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5571
5572 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005573 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005574
5575 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005576 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005577 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5578 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005579 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005580 }
5581}
5582
Chris Lattner0cf24192010-06-28 20:05:43 +00005583//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005584// MIPS ABI Implementation. This works for both little-endian and
5585// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005586//===----------------------------------------------------------------------===//
5587
John McCall943fae92010-05-27 06:19:26 +00005588namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005589class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005590 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005591 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5592 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005593 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005594 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005595 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005596 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005597public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005598 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005599 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005600 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005601
5602 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005603 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005604 void computeInfo(CGFunctionInfo &FI) const override;
5605 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5606 CodeGenFunction &CGF) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005607 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005608};
5609
John McCall943fae92010-05-27 06:19:26 +00005610class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005611 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005612public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005613 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5614 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005615 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005616
Craig Topper4f12f102014-03-12 06:41:41 +00005617 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005618 return 29;
5619 }
5620
Eric Christopher162c91c2015-06-05 22:03:00 +00005621 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005622 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005623 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5624 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005625 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005626 if (FD->hasAttr<Mips16Attr>()) {
5627 Fn->addFnAttr("mips16");
5628 }
5629 else if (FD->hasAttr<NoMips16Attr>()) {
5630 Fn->addFnAttr("nomips16");
5631 }
Reed Kotler373feca2013-01-16 17:10:28 +00005632 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005633
John McCall943fae92010-05-27 06:19:26 +00005634 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005635 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005636
Craig Topper4f12f102014-03-12 06:41:41 +00005637 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005638 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005639 }
John McCall943fae92010-05-27 06:19:26 +00005640};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005641}
John McCall943fae92010-05-27 06:19:26 +00005642
Eric Christopher7565e0d2015-05-29 23:09:49 +00005643void MipsABIInfo::CoerceToIntArgs(
5644 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005645 llvm::IntegerType *IntTy =
5646 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005647
5648 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5649 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5650 ArgList.push_back(IntTy);
5651
5652 // If necessary, add one more integer type to ArgList.
5653 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5654
5655 if (R)
5656 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005657}
5658
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005659// In N32/64, an aligned double precision floating point field is passed in
5660// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005661llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005662 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5663
5664 if (IsO32) {
5665 CoerceToIntArgs(TySize, ArgList);
5666 return llvm::StructType::get(getVMContext(), ArgList);
5667 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005668
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005669 if (Ty->isComplexType())
5670 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005671
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005672 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005673
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005674 // Unions/vectors are passed in integer registers.
5675 if (!RT || !RT->isStructureOrClassType()) {
5676 CoerceToIntArgs(TySize, ArgList);
5677 return llvm::StructType::get(getVMContext(), ArgList);
5678 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005679
5680 const RecordDecl *RD = RT->getDecl();
5681 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005682 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00005683
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005684 uint64_t LastOffset = 0;
5685 unsigned idx = 0;
5686 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5687
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005688 // Iterate over fields in the struct/class and check if there are any aligned
5689 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005690 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5691 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005692 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005693 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5694
5695 if (!BT || BT->getKind() != BuiltinType::Double)
5696 continue;
5697
5698 uint64_t Offset = Layout.getFieldOffset(idx);
5699 if (Offset % 64) // Ignore doubles that are not aligned.
5700 continue;
5701
5702 // Add ((Offset - LastOffset) / 64) args of type i64.
5703 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5704 ArgList.push_back(I64);
5705
5706 // Add double type.
5707 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5708 LastOffset = Offset + 64;
5709 }
5710
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005711 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5712 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005713
5714 return llvm::StructType::get(getVMContext(), ArgList);
5715}
5716
Akira Hatanakaddd66342013-10-29 18:41:15 +00005717llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5718 uint64_t Offset) const {
5719 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005720 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005721
Akira Hatanakaddd66342013-10-29 18:41:15 +00005722 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005723}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005724
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005725ABIArgInfo
5726MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005727 Ty = useFirstFieldIfTransparentUnion(Ty);
5728
Akira Hatanaka1632af62012-01-09 19:31:25 +00005729 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005730 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005731 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005732
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005733 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5734 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005735 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5736 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005737
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005738 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005739 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005740 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005741 return ABIArgInfo::getIgnore();
5742
Mark Lacey3825e832013-10-06 01:33:34 +00005743 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005744 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005745 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005746 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005747
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005748 // If we have reached here, aggregates are passed directly by coercing to
5749 // another structure type. Padding is inserted if the offset of the
5750 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005751 ABIArgInfo ArgInfo =
5752 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5753 getPaddingType(OrigOffset, CurrOffset));
5754 ArgInfo.setInReg(true);
5755 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005756 }
5757
5758 // Treat an enum type as its underlying type.
5759 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5760 Ty = EnumTy->getDecl()->getIntegerType();
5761
Daniel Sanders5b445b32014-10-24 14:42:42 +00005762 // All integral types are promoted to the GPR width.
5763 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005764 return ABIArgInfo::getExtend();
5765
Akira Hatanakaddd66342013-10-29 18:41:15 +00005766 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005767 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005768}
5769
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005770llvm::Type*
5771MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005772 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005773 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005774
Akira Hatanakab6f74432012-02-09 18:49:26 +00005775 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005776 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005777 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5778 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005779
Akira Hatanakab6f74432012-02-09 18:49:26 +00005780 // N32/64 returns struct/classes in floating point registers if the
5781 // following conditions are met:
5782 // 1. The size of the struct/class is no larger than 128-bit.
5783 // 2. The struct/class has one or two fields all of which are floating
5784 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005785 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00005786 //
5787 // Any other composite results are returned in integer registers.
5788 //
5789 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5790 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5791 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005792 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005793
Akira Hatanakab6f74432012-02-09 18:49:26 +00005794 if (!BT || !BT->isFloatingPoint())
5795 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005796
David Blaikie2d7c57e2012-04-30 02:36:29 +00005797 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005798 }
5799
5800 if (b == e)
5801 return llvm::StructType::get(getVMContext(), RTList,
5802 RD->hasAttr<PackedAttr>());
5803
5804 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005805 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005806 }
5807
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005808 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005809 return llvm::StructType::get(getVMContext(), RTList);
5810}
5811
Akira Hatanakab579fe52011-06-02 00:09:17 +00005812ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005813 uint64_t Size = getContext().getTypeSize(RetTy);
5814
Daniel Sandersed39f582014-09-04 13:28:14 +00005815 if (RetTy->isVoidType())
5816 return ABIArgInfo::getIgnore();
5817
5818 // O32 doesn't treat zero-sized structs differently from other structs.
5819 // However, N32/N64 ignores zero sized return values.
5820 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005821 return ABIArgInfo::getIgnore();
5822
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005823 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005824 if (Size <= 128) {
5825 if (RetTy->isAnyComplexType())
5826 return ABIArgInfo::getDirect();
5827
Daniel Sanderse5018b62014-09-04 15:05:39 +00005828 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005829 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005830 if (!IsO32 ||
5831 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5832 ABIArgInfo ArgInfo =
5833 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5834 ArgInfo.setInReg(true);
5835 return ArgInfo;
5836 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005837 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005838
5839 return ABIArgInfo::getIndirect(0);
5840 }
5841
5842 // Treat an enum type as its underlying type.
5843 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5844 RetTy = EnumTy->getDecl()->getIntegerType();
5845
5846 return (RetTy->isPromotableIntegerType() ?
5847 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5848}
5849
5850void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005851 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005852 if (!getCXXABI().classifyReturnType(FI))
5853 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005854
Eric Christopher7565e0d2015-05-29 23:09:49 +00005855 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005856 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005857
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005858 for (auto &I : FI.arguments())
5859 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005860}
5861
5862llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5863 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005864 llvm::Type *BP = CGF.Int8PtrTy;
5865 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005866
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005867 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5868 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005869 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005870 unsigned PtrWidth = getTarget().getPointerWidth(0);
5871 if ((Ty->isIntegerType() &&
5872 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5873 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005874 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5875 Ty->isSignedIntegerType());
5876 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00005877
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005878 CGBuilderTy &Builder = CGF.Builder;
5879 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5880 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005881 int64_t TypeAlign =
5882 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005883 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5884 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005885 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5886
5887 if (TypeAlign > MinABIStackAlignInBytes) {
5888 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5889 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5890 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5891 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5892 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5893 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5894 }
5895 else
Eric Christopher7565e0d2015-05-29 23:09:49 +00005896 AddrTyped = Builder.CreateBitCast(Addr, PTy);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005897
5898 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5899 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005900 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5901 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005902 llvm::Value *NextAddr =
5903 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5904 "ap.next");
5905 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005906
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005907 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005908}
5909
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005910bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
5911 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005912
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005913 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
5914 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
5915 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00005916
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005917 return false;
5918}
5919
John McCall943fae92010-05-27 06:19:26 +00005920bool
5921MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5922 llvm::Value *Address) const {
5923 // This information comes from gcc's implementation, which seems to
5924 // as canonical as it gets.
5925
John McCall943fae92010-05-27 06:19:26 +00005926 // Everything on MIPS is 4 bytes. Double-precision FP registers
5927 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005928 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005929
5930 // 0-31 are the general purpose registers, $0 - $31.
5931 // 32-63 are the floating-point registers, $f0 - $f31.
5932 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5933 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005934 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005935
5936 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5937 // They are one bit wide and ignored here.
5938
5939 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5940 // (coprocessor 1 is the FP unit)
5941 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5942 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5943 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005944 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005945 return false;
5946}
5947
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005948//===----------------------------------------------------------------------===//
5949// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005950// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005951// handling.
5952//===----------------------------------------------------------------------===//
5953
5954namespace {
5955
5956class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5957public:
5958 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5959 : DefaultTargetCodeGenInfo(CGT) {}
5960
Eric Christopher162c91c2015-06-05 22:03:00 +00005961 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005962 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005963};
5964
Eric Christopher162c91c2015-06-05 22:03:00 +00005965void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00005966 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005967 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5968 if (!FD) return;
5969
5970 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00005971
David Blaikiebbafb8a2012-03-11 07:00:24 +00005972 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005973 if (FD->hasAttr<OpenCLKernelAttr>()) {
5974 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005975 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005976 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5977 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005978 // Convert the reqd_work_group_size() attributes to metadata.
5979 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00005980 llvm::NamedMDNode *OpenCLMetadata =
5981 M.getModule().getOrInsertNamedMetadata(
5982 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005983
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005984 SmallVector<llvm::Metadata *, 5> Operands;
5985 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005986
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005987 Operands.push_back(
5988 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5989 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5990 Operands.push_back(
5991 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5992 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5993 Operands.push_back(
5994 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5995 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005996
Eric Christopher7565e0d2015-05-29 23:09:49 +00005997 // Add a boolean constant operand for "required" (true) or "hint"
5998 // (false) for implementing the work_group_size_hint attr later.
5999 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006000 Operands.push_back(
6001 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006002 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6003 }
6004 }
6005 }
6006}
6007
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006008}
John McCall943fae92010-05-27 06:19:26 +00006009
Tony Linthicum76329bf2011-12-12 21:14:55 +00006010//===----------------------------------------------------------------------===//
6011// Hexagon ABI Implementation
6012//===----------------------------------------------------------------------===//
6013
6014namespace {
6015
6016class HexagonABIInfo : public ABIInfo {
6017
6018
6019public:
6020 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6021
6022private:
6023
6024 ABIArgInfo classifyReturnType(QualType RetTy) const;
6025 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6026
Craig Topper4f12f102014-03-12 06:41:41 +00006027 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006028
Craig Topper4f12f102014-03-12 06:41:41 +00006029 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6030 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006031};
6032
6033class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6034public:
6035 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6036 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6037
Craig Topper4f12f102014-03-12 06:41:41 +00006038 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006039 return 29;
6040 }
6041};
6042
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006043}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006044
6045void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006046 if (!getCXXABI().classifyReturnType(FI))
6047 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006048 for (auto &I : FI.arguments())
6049 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006050}
6051
6052ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6053 if (!isAggregateTypeForABI(Ty)) {
6054 // Treat an enum type as its underlying type.
6055 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6056 Ty = EnumTy->getDecl()->getIntegerType();
6057
6058 return (Ty->isPromotableIntegerType() ?
6059 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6060 }
6061
6062 // Ignore empty records.
6063 if (isEmptyRecord(getContext(), Ty, true))
6064 return ABIArgInfo::getIgnore();
6065
Mark Lacey3825e832013-10-06 01:33:34 +00006066 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006067 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006068
6069 uint64_t Size = getContext().getTypeSize(Ty);
6070 if (Size > 64)
6071 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6072 // Pass in the smallest viable integer type.
6073 else if (Size > 32)
6074 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6075 else if (Size > 16)
6076 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6077 else if (Size > 8)
6078 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6079 else
6080 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6081}
6082
6083ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6084 if (RetTy->isVoidType())
6085 return ABIArgInfo::getIgnore();
6086
6087 // Large vector types should be returned via memory.
6088 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6089 return ABIArgInfo::getIndirect(0);
6090
6091 if (!isAggregateTypeForABI(RetTy)) {
6092 // Treat an enum type as its underlying type.
6093 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6094 RetTy = EnumTy->getDecl()->getIntegerType();
6095
6096 return (RetTy->isPromotableIntegerType() ?
6097 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6098 }
6099
Tony Linthicum76329bf2011-12-12 21:14:55 +00006100 if (isEmptyRecord(getContext(), RetTy, true))
6101 return ABIArgInfo::getIgnore();
6102
6103 // Aggregates <= 8 bytes are returned in r0; other aggregates
6104 // are returned indirectly.
6105 uint64_t Size = getContext().getTypeSize(RetTy);
6106 if (Size <= 64) {
6107 // Return in the smallest viable integer type.
6108 if (Size <= 8)
6109 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6110 if (Size <= 16)
6111 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6112 if (Size <= 32)
6113 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6114 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6115 }
6116
6117 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6118}
6119
6120llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006121 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006122 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006123 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006124
6125 CGBuilderTy &Builder = CGF.Builder;
6126 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6127 "ap");
6128 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6129 llvm::Type *PTy =
6130 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6131 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6132
6133 uint64_t Offset =
6134 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6135 llvm::Value *NextAddr =
6136 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6137 "ap.next");
6138 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6139
6140 return AddrTyped;
6141}
6142
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006143//===----------------------------------------------------------------------===//
6144// AMDGPU ABI Implementation
6145//===----------------------------------------------------------------------===//
6146
6147namespace {
6148
6149class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6150public:
6151 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6152 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006153 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006154 CodeGen::CodeGenModule &M) const override;
6155};
6156
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006157}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006158
Eric Christopher162c91c2015-06-05 22:03:00 +00006159void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006160 const Decl *D,
6161 llvm::GlobalValue *GV,
6162 CodeGen::CodeGenModule &M) const {
6163 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6164 if (!FD)
6165 return;
6166
6167 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6168 llvm::Function *F = cast<llvm::Function>(GV);
6169 uint32_t NumVGPR = Attr->getNumVGPR();
6170 if (NumVGPR != 0)
6171 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6172 }
6173
6174 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6175 llvm::Function *F = cast<llvm::Function>(GV);
6176 unsigned NumSGPR = Attr->getNumSGPR();
6177 if (NumSGPR != 0)
6178 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6179 }
6180}
6181
Tony Linthicum76329bf2011-12-12 21:14:55 +00006182
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006183//===----------------------------------------------------------------------===//
6184// SPARC v9 ABI Implementation.
6185// Based on the SPARC Compliance Definition version 2.4.1.
6186//
6187// Function arguments a mapped to a nominal "parameter array" and promoted to
6188// registers depending on their type. Each argument occupies 8 or 16 bytes in
6189// the array, structs larger than 16 bytes are passed indirectly.
6190//
6191// One case requires special care:
6192//
6193// struct mixed {
6194// int i;
6195// float f;
6196// };
6197//
6198// When a struct mixed is passed by value, it only occupies 8 bytes in the
6199// parameter array, but the int is passed in an integer register, and the float
6200// is passed in a floating point register. This is represented as two arguments
6201// with the LLVM IR inreg attribute:
6202//
6203// declare void f(i32 inreg %i, float inreg %f)
6204//
6205// The code generator will only allocate 4 bytes from the parameter array for
6206// the inreg arguments. All other arguments are allocated a multiple of 8
6207// bytes.
6208//
6209namespace {
6210class SparcV9ABIInfo : public ABIInfo {
6211public:
6212 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6213
6214private:
6215 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006216 void computeInfo(CGFunctionInfo &FI) const override;
6217 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6218 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006219
6220 // Coercion type builder for structs passed in registers. The coercion type
6221 // serves two purposes:
6222 //
6223 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6224 // in registers.
6225 // 2. Expose aligned floating point elements as first-level elements, so the
6226 // code generator knows to pass them in floating point registers.
6227 //
6228 // We also compute the InReg flag which indicates that the struct contains
6229 // aligned 32-bit floats.
6230 //
6231 struct CoerceBuilder {
6232 llvm::LLVMContext &Context;
6233 const llvm::DataLayout &DL;
6234 SmallVector<llvm::Type*, 8> Elems;
6235 uint64_t Size;
6236 bool InReg;
6237
6238 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6239 : Context(c), DL(dl), Size(0), InReg(false) {}
6240
6241 // Pad Elems with integers until Size is ToSize.
6242 void pad(uint64_t ToSize) {
6243 assert(ToSize >= Size && "Cannot remove elements");
6244 if (ToSize == Size)
6245 return;
6246
6247 // Finish the current 64-bit word.
6248 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6249 if (Aligned > Size && Aligned <= ToSize) {
6250 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6251 Size = Aligned;
6252 }
6253
6254 // Add whole 64-bit words.
6255 while (Size + 64 <= ToSize) {
6256 Elems.push_back(llvm::Type::getInt64Ty(Context));
6257 Size += 64;
6258 }
6259
6260 // Final in-word padding.
6261 if (Size < ToSize) {
6262 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6263 Size = ToSize;
6264 }
6265 }
6266
6267 // Add a floating point element at Offset.
6268 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6269 // Unaligned floats are treated as integers.
6270 if (Offset % Bits)
6271 return;
6272 // The InReg flag is only required if there are any floats < 64 bits.
6273 if (Bits < 64)
6274 InReg = true;
6275 pad(Offset);
6276 Elems.push_back(Ty);
6277 Size = Offset + Bits;
6278 }
6279
6280 // Add a struct type to the coercion type, starting at Offset (in bits).
6281 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6282 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6283 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6284 llvm::Type *ElemTy = StrTy->getElementType(i);
6285 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6286 switch (ElemTy->getTypeID()) {
6287 case llvm::Type::StructTyID:
6288 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6289 break;
6290 case llvm::Type::FloatTyID:
6291 addFloat(ElemOffset, ElemTy, 32);
6292 break;
6293 case llvm::Type::DoubleTyID:
6294 addFloat(ElemOffset, ElemTy, 64);
6295 break;
6296 case llvm::Type::FP128TyID:
6297 addFloat(ElemOffset, ElemTy, 128);
6298 break;
6299 case llvm::Type::PointerTyID:
6300 if (ElemOffset % 64 == 0) {
6301 pad(ElemOffset);
6302 Elems.push_back(ElemTy);
6303 Size += 64;
6304 }
6305 break;
6306 default:
6307 break;
6308 }
6309 }
6310 }
6311
6312 // Check if Ty is a usable substitute for the coercion type.
6313 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006314 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006315 }
6316
6317 // Get the coercion type as a literal struct type.
6318 llvm::Type *getType() const {
6319 if (Elems.size() == 1)
6320 return Elems.front();
6321 else
6322 return llvm::StructType::get(Context, Elems);
6323 }
6324 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006325};
6326} // end anonymous namespace
6327
6328ABIArgInfo
6329SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6330 if (Ty->isVoidType())
6331 return ABIArgInfo::getIgnore();
6332
6333 uint64_t Size = getContext().getTypeSize(Ty);
6334
6335 // Anything too big to fit in registers is passed with an explicit indirect
6336 // pointer / sret pointer.
6337 if (Size > SizeLimit)
6338 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6339
6340 // Treat an enum type as its underlying type.
6341 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6342 Ty = EnumTy->getDecl()->getIntegerType();
6343
6344 // Integer types smaller than a register are extended.
6345 if (Size < 64 && Ty->isIntegerType())
6346 return ABIArgInfo::getExtend();
6347
6348 // Other non-aggregates go in registers.
6349 if (!isAggregateTypeForABI(Ty))
6350 return ABIArgInfo::getDirect();
6351
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006352 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6353 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6354 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6355 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6356
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006357 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006358 // Build a coercion type from the LLVM struct type.
6359 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6360 if (!StrTy)
6361 return ABIArgInfo::getDirect();
6362
6363 CoerceBuilder CB(getVMContext(), getDataLayout());
6364 CB.addStruct(0, StrTy);
6365 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6366
6367 // Try to use the original type for coercion.
6368 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6369
6370 if (CB.InReg)
6371 return ABIArgInfo::getDirectInReg(CoerceTy);
6372 else
6373 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006374}
6375
6376llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6377 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006378 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6379 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6380 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6381 AI.setCoerceToType(ArgTy);
6382
6383 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6384 CGBuilderTy &Builder = CGF.Builder;
6385 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6386 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6387 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6388 llvm::Value *ArgAddr;
6389 unsigned Stride;
6390
6391 switch (AI.getKind()) {
6392 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006393 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006394 llvm_unreachable("Unsupported ABI kind for va_arg");
6395
6396 case ABIArgInfo::Extend:
6397 Stride = 8;
6398 ArgAddr = Builder
6399 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6400 "extend");
6401 break;
6402
6403 case ABIArgInfo::Direct:
6404 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6405 ArgAddr = Addr;
6406 break;
6407
6408 case ABIArgInfo::Indirect:
6409 Stride = 8;
6410 ArgAddr = Builder.CreateBitCast(Addr,
6411 llvm::PointerType::getUnqual(ArgPtrTy),
6412 "indirect");
6413 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6414 break;
6415
6416 case ABIArgInfo::Ignore:
6417 return llvm::UndefValue::get(ArgPtrTy);
6418 }
6419
6420 // Update VAList.
6421 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6422 Builder.CreateStore(Addr, VAListAddrAsBPP);
6423
6424 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006425}
6426
6427void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6428 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006429 for (auto &I : FI.arguments())
6430 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006431}
6432
6433namespace {
6434class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6435public:
6436 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6437 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006438
Craig Topper4f12f102014-03-12 06:41:41 +00006439 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006440 return 14;
6441 }
6442
6443 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006444 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006445};
6446} // end anonymous namespace
6447
Roman Divackyf02c9942014-02-24 18:46:27 +00006448bool
6449SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6450 llvm::Value *Address) const {
6451 // This is calculated from the LLVM and GCC tables and verified
6452 // against gcc output. AFAIK all ABIs use the same encoding.
6453
6454 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6455
6456 llvm::IntegerType *i8 = CGF.Int8Ty;
6457 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6458 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6459
6460 // 0-31: the 8-byte general-purpose registers
6461 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6462
6463 // 32-63: f0-31, the 4-byte floating-point registers
6464 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6465
6466 // Y = 64
6467 // PSR = 65
6468 // WIM = 66
6469 // TBR = 67
6470 // PC = 68
6471 // NPC = 69
6472 // FSR = 70
6473 // CSR = 71
6474 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006475
Roman Divackyf02c9942014-02-24 18:46:27 +00006476 // 72-87: d0-15, the 8-byte floating-point registers
6477 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6478
6479 return false;
6480}
6481
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006482
Robert Lytton0e076492013-08-13 09:43:10 +00006483//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006484// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006485//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006486
Robert Lytton0e076492013-08-13 09:43:10 +00006487namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006488
6489/// A SmallStringEnc instance is used to build up the TypeString by passing
6490/// it by reference between functions that append to it.
6491typedef llvm::SmallString<128> SmallStringEnc;
6492
6493/// TypeStringCache caches the meta encodings of Types.
6494///
6495/// The reason for caching TypeStrings is two fold:
6496/// 1. To cache a type's encoding for later uses;
6497/// 2. As a means to break recursive member type inclusion.
6498///
6499/// A cache Entry can have a Status of:
6500/// NonRecursive: The type encoding is not recursive;
6501/// Recursive: The type encoding is recursive;
6502/// Incomplete: An incomplete TypeString;
6503/// IncompleteUsed: An incomplete TypeString that has been used in a
6504/// Recursive type encoding.
6505///
6506/// A NonRecursive entry will have all of its sub-members expanded as fully
6507/// as possible. Whilst it may contain types which are recursive, the type
6508/// itself is not recursive and thus its encoding may be safely used whenever
6509/// the type is encountered.
6510///
6511/// A Recursive entry will have all of its sub-members expanded as fully as
6512/// possible. The type itself is recursive and it may contain other types which
6513/// are recursive. The Recursive encoding must not be used during the expansion
6514/// of a recursive type's recursive branch. For simplicity the code uses
6515/// IncompleteCount to reject all usage of Recursive encodings for member types.
6516///
6517/// An Incomplete entry is always a RecordType and only encodes its
6518/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6519/// are placed into the cache during type expansion as a means to identify and
6520/// handle recursive inclusion of types as sub-members. If there is recursion
6521/// the entry becomes IncompleteUsed.
6522///
6523/// During the expansion of a RecordType's members:
6524///
6525/// If the cache contains a NonRecursive encoding for the member type, the
6526/// cached encoding is used;
6527///
6528/// If the cache contains a Recursive encoding for the member type, the
6529/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6530///
6531/// If the member is a RecordType, an Incomplete encoding is placed into the
6532/// cache to break potential recursive inclusion of itself as a sub-member;
6533///
6534/// Once a member RecordType has been expanded, its temporary incomplete
6535/// entry is removed from the cache. If a Recursive encoding was swapped out
6536/// it is swapped back in;
6537///
6538/// If an incomplete entry is used to expand a sub-member, the incomplete
6539/// entry is marked as IncompleteUsed. The cache keeps count of how many
6540/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6541///
6542/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6543/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6544/// Else the member is part of a recursive type and thus the recursion has
6545/// been exited too soon for the encoding to be correct for the member.
6546///
6547class TypeStringCache {
6548 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6549 struct Entry {
6550 std::string Str; // The encoded TypeString for the type.
6551 enum Status State; // Information about the encoding in 'Str'.
6552 std::string Swapped; // A temporary place holder for a Recursive encoding
6553 // during the expansion of RecordType's members.
6554 };
6555 std::map<const IdentifierInfo *, struct Entry> Map;
6556 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6557 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6558public:
Robert Lyttond263f142014-05-06 09:38:54 +00006559 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006560 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6561 bool removeIncomplete(const IdentifierInfo *ID);
6562 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6563 bool IsRecursive);
6564 StringRef lookupStr(const IdentifierInfo *ID);
6565};
6566
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006567/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006568/// FieldEncoding is a helper for this ordering process.
6569class FieldEncoding {
6570 bool HasName;
6571 std::string Enc;
6572public:
6573 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6574 StringRef str() {return Enc.c_str();};
6575 bool operator<(const FieldEncoding &rhs) const {
6576 if (HasName != rhs.HasName) return HasName;
6577 return Enc < rhs.Enc;
6578 }
6579};
6580
Robert Lytton7d1db152013-08-19 09:46:39 +00006581class XCoreABIInfo : public DefaultABIInfo {
6582public:
6583 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006584 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6585 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006586};
6587
Robert Lyttond21e2d72014-03-03 13:45:29 +00006588class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006589 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006590public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006591 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006592 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006593 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6594 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006595};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006596
Robert Lytton2d196952013-10-11 10:29:34 +00006597} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006598
Robert Lytton7d1db152013-08-19 09:46:39 +00006599llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6600 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006601 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006602
Robert Lytton2d196952013-10-11 10:29:34 +00006603 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006604 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6605 CGF.Int8PtrPtrTy);
6606 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006607
Robert Lytton2d196952013-10-11 10:29:34 +00006608 // Handle the argument.
6609 ABIArgInfo AI = classifyArgumentType(Ty);
6610 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6611 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6612 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006613 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006614 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006615 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006616 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006617 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006618 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006619 llvm_unreachable("Unsupported ABI kind for va_arg");
6620 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006621 Val = llvm::UndefValue::get(ArgPtrTy);
6622 ArgSize = 0;
6623 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006624 case ABIArgInfo::Extend:
6625 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006626 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6627 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6628 if (ArgSize < 4)
6629 ArgSize = 4;
6630 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006631 case ABIArgInfo::Indirect:
6632 llvm::Value *ArgAddr;
6633 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6634 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006635 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6636 ArgSize = 4;
6637 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006638 }
Robert Lytton2d196952013-10-11 10:29:34 +00006639
6640 // Increment the VAList.
6641 if (ArgSize) {
6642 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6643 Builder.CreateStore(APN, VAListAddrAsBPP);
6644 }
6645 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006646}
Robert Lytton0e076492013-08-13 09:43:10 +00006647
Robert Lytton844aeeb2014-05-02 09:33:20 +00006648/// During the expansion of a RecordType, an incomplete TypeString is placed
6649/// into the cache as a means to identify and break recursion.
6650/// If there is a Recursive encoding in the cache, it is swapped out and will
6651/// be reinserted by removeIncomplete().
6652/// All other types of encoding should have been used rather than arriving here.
6653void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6654 std::string StubEnc) {
6655 if (!ID)
6656 return;
6657 Entry &E = Map[ID];
6658 assert( (E.Str.empty() || E.State == Recursive) &&
6659 "Incorrectly use of addIncomplete");
6660 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6661 E.Swapped.swap(E.Str); // swap out the Recursive
6662 E.Str.swap(StubEnc);
6663 E.State = Incomplete;
6664 ++IncompleteCount;
6665}
6666
6667/// Once the RecordType has been expanded, the temporary incomplete TypeString
6668/// must be removed from the cache.
6669/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6670/// Returns true if the RecordType was defined recursively.
6671bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6672 if (!ID)
6673 return false;
6674 auto I = Map.find(ID);
6675 assert(I != Map.end() && "Entry not present");
6676 Entry &E = I->second;
6677 assert( (E.State == Incomplete ||
6678 E.State == IncompleteUsed) &&
6679 "Entry must be an incomplete type");
6680 bool IsRecursive = false;
6681 if (E.State == IncompleteUsed) {
6682 // We made use of our Incomplete encoding, thus we are recursive.
6683 IsRecursive = true;
6684 --IncompleteUsedCount;
6685 }
6686 if (E.Swapped.empty())
6687 Map.erase(I);
6688 else {
6689 // Swap the Recursive back.
6690 E.Swapped.swap(E.Str);
6691 E.Swapped.clear();
6692 E.State = Recursive;
6693 }
6694 --IncompleteCount;
6695 return IsRecursive;
6696}
6697
6698/// Add the encoded TypeString to the cache only if it is NonRecursive or
6699/// Recursive (viz: all sub-members were expanded as fully as possible).
6700void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6701 bool IsRecursive) {
6702 if (!ID || IncompleteUsedCount)
6703 return; // No key or it is is an incomplete sub-type so don't add.
6704 Entry &E = Map[ID];
6705 if (IsRecursive && !E.Str.empty()) {
6706 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6707 "This is not the same Recursive entry");
6708 // The parent container was not recursive after all, so we could have used
6709 // this Recursive sub-member entry after all, but we assumed the worse when
6710 // we started viz: IncompleteCount!=0.
6711 return;
6712 }
6713 assert(E.Str.empty() && "Entry already present");
6714 E.Str = Str.str();
6715 E.State = IsRecursive? Recursive : NonRecursive;
6716}
6717
6718/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6719/// are recursively expanding a type (IncompleteCount != 0) and the cached
6720/// encoding is Recursive, return an empty StringRef.
6721StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6722 if (!ID)
6723 return StringRef(); // We have no key.
6724 auto I = Map.find(ID);
6725 if (I == Map.end())
6726 return StringRef(); // We have no encoding.
6727 Entry &E = I->second;
6728 if (E.State == Recursive && IncompleteCount)
6729 return StringRef(); // We don't use Recursive encodings for member types.
6730
6731 if (E.State == Incomplete) {
6732 // The incomplete type is being used to break out of recursion.
6733 E.State = IncompleteUsed;
6734 ++IncompleteUsedCount;
6735 }
6736 return E.Str.c_str();
6737}
6738
6739/// The XCore ABI includes a type information section that communicates symbol
6740/// type information to the linker. The linker uses this information to verify
6741/// safety/correctness of things such as array bound and pointers et al.
6742/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6743/// This type information (TypeString) is emitted into meta data for all global
6744/// symbols: definitions, declarations, functions & variables.
6745///
6746/// The TypeString carries type, qualifier, name, size & value details.
6747/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00006748/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00006749/// The output is tested by test/CodeGen/xcore-stringtype.c.
6750///
6751static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6752 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6753
6754/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6755void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6756 CodeGen::CodeGenModule &CGM) const {
6757 SmallStringEnc Enc;
6758 if (getTypeString(Enc, D, CGM, TSC)) {
6759 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006760 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6761 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006762 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6763 llvm::NamedMDNode *MD =
6764 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6765 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6766 }
6767}
6768
6769static bool appendType(SmallStringEnc &Enc, QualType QType,
6770 const CodeGen::CodeGenModule &CGM,
6771 TypeStringCache &TSC);
6772
6773/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00006774/// Builds a SmallVector containing the encoded field types in declaration
6775/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006776static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6777 const RecordDecl *RD,
6778 const CodeGen::CodeGenModule &CGM,
6779 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006780 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006781 SmallStringEnc Enc;
6782 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006783 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006784 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006785 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006786 Enc += "b(";
6787 llvm::raw_svector_ostream OS(Enc);
6788 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006789 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006790 OS.flush();
6791 Enc += ':';
6792 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006793 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006794 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006795 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006796 Enc += ')';
6797 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00006798 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006799 }
6800 return true;
6801}
6802
6803/// Appends structure and union types to Enc and adds encoding to cache.
6804/// Recursively calls appendType (via extractFieldType) for each field.
6805/// Union types have their fields ordered according to the ABI.
6806static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6807 const CodeGen::CodeGenModule &CGM,
6808 TypeStringCache &TSC, const IdentifierInfo *ID) {
6809 // Append the cached TypeString if we have one.
6810 StringRef TypeString = TSC.lookupStr(ID);
6811 if (!TypeString.empty()) {
6812 Enc += TypeString;
6813 return true;
6814 }
6815
6816 // Start to emit an incomplete TypeString.
6817 size_t Start = Enc.size();
6818 Enc += (RT->isUnionType()? 'u' : 's');
6819 Enc += '(';
6820 if (ID)
6821 Enc += ID->getName();
6822 Enc += "){";
6823
6824 // We collect all encoded fields and order as necessary.
6825 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006826 const RecordDecl *RD = RT->getDecl()->getDefinition();
6827 if (RD && !RD->field_empty()) {
6828 // An incomplete TypeString stub is placed in the cache for this RecordType
6829 // so that recursive calls to this RecordType will use it whilst building a
6830 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006831 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006832 std::string StubEnc(Enc.substr(Start).str());
6833 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6834 TSC.addIncomplete(ID, std::move(StubEnc));
6835 if (!extractFieldType(FE, RD, CGM, TSC)) {
6836 (void) TSC.removeIncomplete(ID);
6837 return false;
6838 }
6839 IsRecursive = TSC.removeIncomplete(ID);
6840 // The ABI requires unions to be sorted but not structures.
6841 // See FieldEncoding::operator< for sort algorithm.
6842 if (RT->isUnionType())
6843 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006844 // We can now complete the TypeString.
6845 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006846 for (unsigned I = 0; I != E; ++I) {
6847 if (I)
6848 Enc += ',';
6849 Enc += FE[I].str();
6850 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006851 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006852 Enc += '}';
6853 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6854 return true;
6855}
6856
6857/// Appends enum types to Enc and adds the encoding to the cache.
6858static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6859 TypeStringCache &TSC,
6860 const IdentifierInfo *ID) {
6861 // Append the cached TypeString if we have one.
6862 StringRef TypeString = TSC.lookupStr(ID);
6863 if (!TypeString.empty()) {
6864 Enc += TypeString;
6865 return true;
6866 }
6867
6868 size_t Start = Enc.size();
6869 Enc += "e(";
6870 if (ID)
6871 Enc += ID->getName();
6872 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006873
6874 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006875 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006876 SmallVector<FieldEncoding, 16> FE;
6877 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6878 ++I) {
6879 SmallStringEnc EnumEnc;
6880 EnumEnc += "m(";
6881 EnumEnc += I->getName();
6882 EnumEnc += "){";
6883 I->getInitVal().toString(EnumEnc);
6884 EnumEnc += '}';
6885 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6886 }
6887 std::sort(FE.begin(), FE.end());
6888 unsigned E = FE.size();
6889 for (unsigned I = 0; I != E; ++I) {
6890 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006891 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006892 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006893 }
6894 }
6895 Enc += '}';
6896 TSC.addIfComplete(ID, Enc.substr(Start), false);
6897 return true;
6898}
6899
6900/// Appends type's qualifier to Enc.
6901/// This is done prior to appending the type's encoding.
6902static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6903 // Qualifiers are emitted in alphabetical order.
6904 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6905 int Lookup = 0;
6906 if (QT.isConstQualified())
6907 Lookup += 1<<0;
6908 if (QT.isRestrictQualified())
6909 Lookup += 1<<1;
6910 if (QT.isVolatileQualified())
6911 Lookup += 1<<2;
6912 Enc += Table[Lookup];
6913}
6914
6915/// Appends built-in types to Enc.
6916static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6917 const char *EncType;
6918 switch (BT->getKind()) {
6919 case BuiltinType::Void:
6920 EncType = "0";
6921 break;
6922 case BuiltinType::Bool:
6923 EncType = "b";
6924 break;
6925 case BuiltinType::Char_U:
6926 EncType = "uc";
6927 break;
6928 case BuiltinType::UChar:
6929 EncType = "uc";
6930 break;
6931 case BuiltinType::SChar:
6932 EncType = "sc";
6933 break;
6934 case BuiltinType::UShort:
6935 EncType = "us";
6936 break;
6937 case BuiltinType::Short:
6938 EncType = "ss";
6939 break;
6940 case BuiltinType::UInt:
6941 EncType = "ui";
6942 break;
6943 case BuiltinType::Int:
6944 EncType = "si";
6945 break;
6946 case BuiltinType::ULong:
6947 EncType = "ul";
6948 break;
6949 case BuiltinType::Long:
6950 EncType = "sl";
6951 break;
6952 case BuiltinType::ULongLong:
6953 EncType = "ull";
6954 break;
6955 case BuiltinType::LongLong:
6956 EncType = "sll";
6957 break;
6958 case BuiltinType::Float:
6959 EncType = "ft";
6960 break;
6961 case BuiltinType::Double:
6962 EncType = "d";
6963 break;
6964 case BuiltinType::LongDouble:
6965 EncType = "ld";
6966 break;
6967 default:
6968 return false;
6969 }
6970 Enc += EncType;
6971 return true;
6972}
6973
6974/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6975static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6976 const CodeGen::CodeGenModule &CGM,
6977 TypeStringCache &TSC) {
6978 Enc += "p(";
6979 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6980 return false;
6981 Enc += ')';
6982 return true;
6983}
6984
6985/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006986static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6987 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006988 const CodeGen::CodeGenModule &CGM,
6989 TypeStringCache &TSC, StringRef NoSizeEnc) {
6990 if (AT->getSizeModifier() != ArrayType::Normal)
6991 return false;
6992 Enc += "a(";
6993 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6994 CAT->getSize().toStringUnsigned(Enc);
6995 else
6996 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6997 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006998 // The Qualifiers should be attached to the type rather than the array.
6999 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007000 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7001 return false;
7002 Enc += ')';
7003 return true;
7004}
7005
7006/// Appends a function encoding to Enc, calling appendType for the return type
7007/// and the arguments.
7008static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7009 const CodeGen::CodeGenModule &CGM,
7010 TypeStringCache &TSC) {
7011 Enc += "f{";
7012 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7013 return false;
7014 Enc += "}(";
7015 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7016 // N.B. we are only interested in the adjusted param types.
7017 auto I = FPT->param_type_begin();
7018 auto E = FPT->param_type_end();
7019 if (I != E) {
7020 do {
7021 if (!appendType(Enc, *I, CGM, TSC))
7022 return false;
7023 ++I;
7024 if (I != E)
7025 Enc += ',';
7026 } while (I != E);
7027 if (FPT->isVariadic())
7028 Enc += ",va";
7029 } else {
7030 if (FPT->isVariadic())
7031 Enc += "va";
7032 else
7033 Enc += '0';
7034 }
7035 }
7036 Enc += ')';
7037 return true;
7038}
7039
7040/// Handles the type's qualifier before dispatching a call to handle specific
7041/// type encodings.
7042static bool appendType(SmallStringEnc &Enc, QualType QType,
7043 const CodeGen::CodeGenModule &CGM,
7044 TypeStringCache &TSC) {
7045
7046 QualType QT = QType.getCanonicalType();
7047
Robert Lytton6adb20f2014-06-05 09:06:21 +00007048 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7049 // The Qualifiers should be attached to the type rather than the array.
7050 // Thus we don't call appendQualifier() here.
7051 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7052
Robert Lytton844aeeb2014-05-02 09:33:20 +00007053 appendQualifier(Enc, QT);
7054
7055 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7056 return appendBuiltinType(Enc, BT);
7057
Robert Lytton844aeeb2014-05-02 09:33:20 +00007058 if (const PointerType *PT = QT->getAs<PointerType>())
7059 return appendPointerType(Enc, PT, CGM, TSC);
7060
7061 if (const EnumType *ET = QT->getAs<EnumType>())
7062 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7063
7064 if (const RecordType *RT = QT->getAsStructureType())
7065 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7066
7067 if (const RecordType *RT = QT->getAsUnionType())
7068 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7069
7070 if (const FunctionType *FT = QT->getAs<FunctionType>())
7071 return appendFunctionType(Enc, FT, CGM, TSC);
7072
7073 return false;
7074}
7075
7076static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7077 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7078 if (!D)
7079 return false;
7080
7081 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7082 if (FD->getLanguageLinkage() != CLanguageLinkage)
7083 return false;
7084 return appendType(Enc, FD->getType(), CGM, TSC);
7085 }
7086
7087 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7088 if (VD->getLanguageLinkage() != CLanguageLinkage)
7089 return false;
7090 QualType QT = VD->getType().getCanonicalType();
7091 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7092 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007093 // The Qualifiers should be attached to the type rather than the array.
7094 // Thus we don't call appendQualifier() here.
7095 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007096 }
7097 return appendType(Enc, QT, CGM, TSC);
7098 }
7099 return false;
7100}
7101
7102
Robert Lytton0e076492013-08-13 09:43:10 +00007103//===----------------------------------------------------------------------===//
7104// Driver code
7105//===----------------------------------------------------------------------===//
7106
Rafael Espindola9f834732014-09-19 01:54:22 +00007107const llvm::Triple &CodeGenModule::getTriple() const {
7108 return getTarget().getTriple();
7109}
7110
7111bool CodeGenModule::supportsCOMDAT() const {
7112 return !getTriple().isOSBinFormatMachO();
7113}
7114
Chris Lattner2b037972010-07-29 02:01:43 +00007115const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007116 if (TheTargetCodeGenInfo)
7117 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007118
John McCallc8e01702013-04-16 22:48:15 +00007119 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007120 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007121 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007122 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007123
Derek Schuff09338a22012-09-06 17:37:28 +00007124 case llvm::Triple::le32:
7125 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007126 case llvm::Triple::mips:
7127 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007128 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7129
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007130 case llvm::Triple::mips64:
7131 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007132 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7133
Tim Northover25e8a672014-05-24 12:51:25 +00007134 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007135 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007136 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007137 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007138 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007139
Tim Northover573cbee2014-05-24 12:52:07 +00007140 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007141 }
7142
Daniel Dunbard59655c2009-09-12 00:59:49 +00007143 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007144 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007145 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007146 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007147 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007148 if (Triple.getOS() == llvm::Triple::Win32) {
7149 TheTargetCodeGenInfo =
7150 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7151 return *TheTargetCodeGenInfo;
7152 }
7153
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007154 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007155 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007156 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007157 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007158 (CodeGenOpts.FloatABI != "soft" &&
7159 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007160 Kind = ARMABIInfo::AAPCS_VFP;
7161
Derek Schuff71658bd2015-01-29 00:47:04 +00007162 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007163 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007164
John McCallea8d8bb2010-03-11 00:10:12 +00007165 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007166 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007167 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007168 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007169 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007170 if (getTarget().getABI() == "elfv2")
7171 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007172 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007173
Ulrich Weigandb7122372014-07-21 00:48:09 +00007174 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007175 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007176 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007177 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007178 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007179 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007180 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007181 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007182 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007183 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007184
Ulrich Weigandb7122372014-07-21 00:48:09 +00007185 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007186 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007187 }
John McCallea8d8bb2010-03-11 00:10:12 +00007188
Peter Collingbournec947aae2012-05-20 23:28:41 +00007189 case llvm::Triple::nvptx:
7190 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007191 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007192
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007193 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007194 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007195
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007196 case llvm::Triple::systemz: {
7197 bool HasVector = getTarget().getABI() == "vector";
7198 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7199 HasVector));
7200 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007201
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007202 case llvm::Triple::tce:
7203 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7204
Eli Friedman33465822011-07-08 23:31:17 +00007205 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007206 bool IsDarwinVectorABI = Triple.isOSDarwin();
7207 bool IsSmallStructInRegABI =
7208 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007209 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007210
John McCall1fe2a8c2013-06-18 02:46:29 +00007211 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007212 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
7213 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7214 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007215 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007216 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
7217 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7218 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007219 }
Eli Friedman33465822011-07-08 23:31:17 +00007220 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007221
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007222 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007223 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007224 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7225 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007226 X86AVXABILevel::None);
7227
Chris Lattner04dc9572010-08-31 16:44:54 +00007228 switch (Triple.getOS()) {
7229 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007230 return *(TheTargetCodeGenInfo =
7231 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007232 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007233 return *(TheTargetCodeGenInfo =
7234 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007235 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007236 return *(TheTargetCodeGenInfo =
7237 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007238 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007239 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007240 case llvm::Triple::hexagon:
7241 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007242 case llvm::Triple::r600:
7243 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007244 case llvm::Triple::amdgcn:
7245 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007246 case llvm::Triple::sparcv9:
7247 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007248 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007249 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007250 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007251}