blob: 44bc36f514ed4547a2f3689e21bd8a89895a3c64 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000023#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000026#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000027
28#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
40 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
41 Builder.CreateStore(Value, Cell);
42 }
43}
44
John McCalla1dee5302010-08-22 10:59:02 +000045static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000046 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000047 T->isMemberFunctionPointerType();
48}
49
Anton Korobeynikov244360d2009-06-05 22:08:42 +000050ABIInfo::~ABIInfo() {}
51
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000052static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000053 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000054 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
55 if (!RD)
56 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000057 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000058}
59
60static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000061 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062 const RecordType *RT = T->getAs<RecordType>();
63 if (!RT)
64 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000065 return getRecordArgABI(RT, CXXABI);
66}
67
68CGCXXABI &ABIInfo::getCXXABI() const {
69 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070}
71
Chris Lattner2b037972010-07-29 02:01:43 +000072ASTContext &ABIInfo::getContext() const {
73 return CGT.getContext();
74}
75
76llvm::LLVMContext &ABIInfo::getVMContext() const {
77 return CGT.getLLVMContext();
78}
79
Micah Villmowdd31ca12012-10-08 16:25:52 +000080const llvm::DataLayout &ABIInfo::getDataLayout() const {
81 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000082}
83
John McCallc8e01702013-04-16 22:48:15 +000084const TargetInfo &ABIInfo::getTarget() const {
85 return CGT.getTarget();
86}
Chris Lattner2b037972010-07-29 02:01:43 +000087
Anton Korobeynikov244360d2009-06-05 22:08:42 +000088void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000089 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +000090 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +000091 switch (TheKind) {
92 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +000093 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +000094 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +000095 Ty->print(OS);
96 else
97 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +000098 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +000099 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000100 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000101 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000102 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000103 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000104 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000105 case InAlloca:
106 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
107 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000108 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000109 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000110 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000111 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000112 break;
113 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000114 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000115 break;
116 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000117 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000118}
119
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000120TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
121
John McCall3480ef22011-08-30 01:42:09 +0000122// If someone can figure out a general rule for this, that would be great.
123// It's probably just doomed to be platform-dependent, though.
124unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
125 // Verified for:
126 // x86-64 FreeBSD, Linux, Darwin
127 // x86-32 FreeBSD, Linux, Darwin
128 // PowerPC Linux, Darwin
129 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000130 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000131 return 32;
132}
133
John McCalla729c622012-02-17 03:33:10 +0000134bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
135 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000136 // The following conventions are known to require this to be false:
137 // x86_stdcall
138 // MIPS
139 // For everything else, we just prefer false unless we opt out.
140 return false;
141}
142
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000143void
144TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
145 llvm::SmallString<24> &Opt) const {
146 // This assumes the user is passing a library name like "rt" instead of a
147 // filename like "librt.a/so", and that they don't care whether it's static or
148 // dynamic.
149 Opt = "-l";
150 Opt += Lib;
151}
152
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000153static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000154
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000155/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000156/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000157static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
158 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000159 if (FD->isUnnamedBitfield())
160 return true;
161
162 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163
Eli Friedman0b3f2012011-11-18 03:47:20 +0000164 // Constant arrays of empty records count as empty, strip them off.
165 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000166 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000167 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
168 if (AT->getSize() == 0)
169 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000170 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000171 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000172
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000173 const RecordType *RT = FT->getAs<RecordType>();
174 if (!RT)
175 return false;
176
177 // C++ record fields are never empty, at least in the Itanium ABI.
178 //
179 // FIXME: We should use a predicate for whether this behavior is true in the
180 // current ABI.
181 if (isa<CXXRecordDecl>(RT->getDecl()))
182 return false;
183
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000185}
186
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000187/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000188/// fields. Note that a structure with a flexible array member is not
189/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000190static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000191 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000192 if (!RT)
193 return 0;
194 const RecordDecl *RD = RT->getDecl();
195 if (RD->hasFlexibleArrayMember())
196 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000197
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000198 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000199 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000200 for (const auto &I : CXXRD->bases())
201 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000202 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000203
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000204 for (const auto *I : RD->fields())
205 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000206 return false;
207 return true;
208}
209
210/// isSingleElementStruct - Determine if a structure is a "single
211/// element struct", i.e. it has exactly one non-empty field or
212/// exactly one field which is itself a single element
213/// struct. Structures with flexible array members are never
214/// considered single element structs.
215///
216/// \return The field declaration for the single non-empty field, if
217/// it exists.
218static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
219 const RecordType *RT = T->getAsStructureType();
220 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000221 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000222
223 const RecordDecl *RD = RT->getDecl();
224 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000225 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000226
Craig Topper8a13c412014-05-21 05:09:00 +0000227 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000228
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000229 // If this is a C++ record, check the bases first.
230 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000231 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000232 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000233 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000234 continue;
235
236 // If we already found an element then this isn't a single-element struct.
237 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000238 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000239
240 // If this is non-empty and not a single element struct, the composite
241 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000242 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000243 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000244 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000245 }
246 }
247
248 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000249 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000250 QualType FT = FD->getType();
251
252 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000253 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000254 continue;
255
256 // If we already found an element then this isn't a single-element
257 // struct.
258 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000259 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000260
261 // Treat single element arrays as the element.
262 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
263 if (AT->getSize().getZExtValue() != 1)
264 break;
265 FT = AT->getElementType();
266 }
267
John McCalla1dee5302010-08-22 10:59:02 +0000268 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000269 Found = FT.getTypePtr();
270 } else {
271 Found = isSingleElementStruct(FT, Context);
272 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000273 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000274 }
275 }
276
Eli Friedmanee945342011-11-18 01:25:50 +0000277 // We don't consider a struct a single-element struct if it has
278 // padding beyond the element type.
279 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000280 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000281
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000282 return Found;
283}
284
285static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000286 // Treat complex types as the element type.
287 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
288 Ty = CTy->getElementType();
289
290 // Check for a type which we know has a simple scalar argument-passing
291 // convention without any padding. (We're specifically looking for 32
292 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000293 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000294 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000295 return false;
296
297 uint64_t Size = Context.getTypeSize(Ty);
298 return Size == 32 || Size == 64;
299}
300
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000301/// canExpandIndirectArgument - Test whether an argument type which is to be
302/// passed indirectly (on the stack) would have the equivalent layout if it was
303/// expanded into separate arguments. If so, we prefer to do the latter to avoid
304/// inhibiting optimizations.
305///
306// FIXME: This predicate is missing many cases, currently it just follows
307// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
308// should probably make this smarter, or better yet make the LLVM backend
309// capable of handling it.
310static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
311 // We can only expand structure types.
312 const RecordType *RT = Ty->getAs<RecordType>();
313 if (!RT)
314 return false;
315
316 // We can only expand (C) structures.
317 //
318 // FIXME: This needs to be generalized to handle classes as well.
319 const RecordDecl *RD = RT->getDecl();
320 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
321 return false;
322
Eli Friedmane5c85622011-11-18 01:32:26 +0000323 uint64_t Size = 0;
324
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000325 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000326 if (!is32Or64BitBasicType(FD->getType(), Context))
327 return false;
328
329 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
330 // how to expand them yet, and the predicate for telling if a bitfield still
331 // counts as "basic" is more complicated than what we were doing previously.
332 if (FD->isBitField())
333 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000334
335 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000336 }
337
Eli Friedmane5c85622011-11-18 01:32:26 +0000338 // Make sure there are not any holes in the struct.
339 if (Size != Context.getTypeSize(Ty))
340 return false;
341
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000342 return true;
343}
344
345namespace {
346/// DefaultABIInfo - The default implementation for ABI specific
347/// details. This implementation provides information which results in
348/// self-consistent and sensible LLVM IR generation, but does not
349/// conform to any particular ABI.
350class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000351public:
352 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000353
Chris Lattner458b2aa2010-07-29 02:16:43 +0000354 ABIArgInfo classifyReturnType(QualType RetTy) const;
355 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000356
Craig Topper4f12f102014-03-12 06:41:41 +0000357 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000358 if (!getCXXABI().classifyReturnType(FI))
359 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000360 for (auto &I : FI.arguments())
361 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000362 }
363
Craig Topper4f12f102014-03-12 06:41:41 +0000364 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
365 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000366};
367
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000368class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
369public:
Chris Lattner2b037972010-07-29 02:01:43 +0000370 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
371 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000372};
373
374llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
375 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000376 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000377}
378
Chris Lattner458b2aa2010-07-29 02:16:43 +0000379ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000380 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000381 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000382
Chris Lattner9723d6c2010-03-11 18:19:55 +0000383 // Treat an enum type as its underlying type.
384 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
385 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000386
Chris Lattner9723d6c2010-03-11 18:19:55 +0000387 return (Ty->isPromotableIntegerType() ?
388 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000389}
390
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000391ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
392 if (RetTy->isVoidType())
393 return ABIArgInfo::getIgnore();
394
395 if (isAggregateTypeForABI(RetTy))
396 return ABIArgInfo::getIndirect(0);
397
398 // Treat an enum type as its underlying type.
399 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
400 RetTy = EnumTy->getDecl()->getIntegerType();
401
402 return (RetTy->isPromotableIntegerType() ?
403 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
404}
405
Derek Schuff09338a22012-09-06 17:37:28 +0000406//===----------------------------------------------------------------------===//
407// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000408//
409// This is a simplified version of the x86_32 ABI. Arguments and return values
410// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000411//===----------------------------------------------------------------------===//
412
413class PNaClABIInfo : public ABIInfo {
414 public:
415 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
416
417 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000418 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000419
Craig Topper4f12f102014-03-12 06:41:41 +0000420 void computeInfo(CGFunctionInfo &FI) const override;
421 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
422 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000423};
424
425class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
426 public:
427 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
428 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
429};
430
431void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000432 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000433 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
434
Reid Kleckner40ca9132014-05-13 22:05:45 +0000435 for (auto &I : FI.arguments())
436 I.info = classifyArgumentType(I.type);
437}
Derek Schuff09338a22012-09-06 17:37:28 +0000438
439llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
440 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000441 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000442}
443
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000444/// \brief Classify argument of given type \p Ty.
445ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000446 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000447 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000448 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000449 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000450 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
451 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000452 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000453 } else if (Ty->isFloatingType()) {
454 // Floating-point types don't go inreg.
455 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000456 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000457
458 return (Ty->isPromotableIntegerType() ?
459 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000460}
461
462ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
463 if (RetTy->isVoidType())
464 return ABIArgInfo::getIgnore();
465
Eli Benderskye20dad62013-04-04 22:49:35 +0000466 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000467 if (isAggregateTypeForABI(RetTy))
468 return ABIArgInfo::getIndirect(0);
469
470 // Treat an enum type as its underlying type.
471 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
472 RetTy = EnumTy->getDecl()->getIntegerType();
473
474 return (RetTy->isPromotableIntegerType() ?
475 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
476}
477
Chad Rosier651c1832013-03-25 21:00:27 +0000478/// IsX86_MMXType - Return true if this is an MMX type.
479bool IsX86_MMXType(llvm::Type *IRType) {
480 // 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 +0000481 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
482 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
483 IRType->getScalarSizeInBits() != 64;
484}
485
Jay Foad7c57be32011-07-11 09:56:20 +0000486static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000488 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000489 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
490 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
491 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000492 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000493 }
494
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000495 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000496 }
497
498 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000499 return Ty;
500}
501
Chris Lattner0cf24192010-06-28 20:05:43 +0000502//===----------------------------------------------------------------------===//
503// X86-32 ABI Implementation
504//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000505
Reid Kleckner661f35b2014-01-18 01:12:41 +0000506/// \brief Similar to llvm::CCState, but for Clang.
507struct CCState {
508 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
509
510 unsigned CC;
511 unsigned FreeRegs;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000512 unsigned StackOffset;
513 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000514};
515
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000516/// X86_32ABIInfo - The X86-32 ABI information.
517class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000518 enum Class {
519 Integer,
520 Float
521 };
522
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000523 static const unsigned MinABIStackAlignInBytes = 4;
524
David Chisnallde3a0692009-08-17 23:08:21 +0000525 bool IsDarwinVectorABI;
526 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000527 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000528 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000529
530 static bool isRegisterSize(unsigned Size) {
531 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
532 }
533
Reid Kleckner40ca9132014-05-13 22:05:45 +0000534 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000535
Daniel Dunbar557893d2010-04-21 19:10:51 +0000536 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
537 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000538 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
539
540 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000541
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000542 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000543 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000544
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000545 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000546 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000547 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
548 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000549
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000550 /// \brief Rewrite the function info so that all memory arguments use
551 /// inalloca.
552 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
553
554 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
555 unsigned &StackOffset, ABIArgInfo &Info,
556 QualType Type) const;
557
Rafael Espindola75419dc2012-07-23 23:30:29 +0000558public:
559
Craig Topper4f12f102014-03-12 06:41:41 +0000560 void computeInfo(CGFunctionInfo &FI) const override;
561 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
562 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000563
Chad Rosier651c1832013-03-25 21:00:27 +0000564 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000565 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000566 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000567 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000568};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000569
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000570class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
571public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000572 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000573 bool d, bool p, bool w, unsigned r)
574 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000575
John McCall1fe2a8c2013-06-18 02:46:29 +0000576 static bool isStructReturnInRegABI(
577 const llvm::Triple &Triple, const CodeGenOptions &Opts);
578
Charles Davis4ea31ab2010-02-13 15:54:06 +0000579 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000580 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000581
Craig Topper4f12f102014-03-12 06:41:41 +0000582 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000583 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000584 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000585 return 4;
586 }
587
588 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000589 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000590
Jay Foad7c57be32011-07-11 09:56:20 +0000591 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000592 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000593 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000594 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
595 }
596
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000597 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
598 std::string &Constraints,
599 std::vector<llvm::Type *> &ResultRegTypes,
600 std::vector<llvm::Type *> &ResultTruncRegTypes,
601 std::vector<LValue> &ResultRegDests,
602 std::string &AsmString,
603 unsigned NumOutputs) const override;
604
Craig Topper4f12f102014-03-12 06:41:41 +0000605 llvm::Constant *
606 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000607 unsigned Sig = (0xeb << 0) | // jmp rel8
608 (0x06 << 8) | // .+0x08
609 ('F' << 16) |
610 ('T' << 24);
611 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
612 }
613
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000614};
615
616}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000617
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000618/// Rewrite input constraint references after adding some output constraints.
619/// In the case where there is one output and one input and we add one output,
620/// we need to replace all operand references greater than or equal to 1:
621/// mov $0, $1
622/// mov eax, $1
623/// The result will be:
624/// mov $0, $2
625/// mov eax, $2
626static void rewriteInputConstraintReferences(unsigned FirstIn,
627 unsigned NumNewOuts,
628 std::string &AsmString) {
629 std::string Buf;
630 llvm::raw_string_ostream OS(Buf);
631 size_t Pos = 0;
632 while (Pos < AsmString.size()) {
633 size_t DollarStart = AsmString.find('$', Pos);
634 if (DollarStart == std::string::npos)
635 DollarStart = AsmString.size();
636 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
637 if (DollarEnd == std::string::npos)
638 DollarEnd = AsmString.size();
639 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
640 Pos = DollarEnd;
641 size_t NumDollars = DollarEnd - DollarStart;
642 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
643 // We have an operand reference.
644 size_t DigitStart = Pos;
645 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
646 if (DigitEnd == std::string::npos)
647 DigitEnd = AsmString.size();
648 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
649 unsigned OperandIndex;
650 if (!OperandStr.getAsInteger(10, OperandIndex)) {
651 if (OperandIndex >= FirstIn)
652 OperandIndex += NumNewOuts;
653 OS << OperandIndex;
654 } else {
655 OS << OperandStr;
656 }
657 Pos = DigitEnd;
658 }
659 }
660 AsmString = std::move(OS.str());
661}
662
663/// Add output constraints for EAX:EDX because they are return registers.
664void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
665 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
666 std::vector<llvm::Type *> &ResultRegTypes,
667 std::vector<llvm::Type *> &ResultTruncRegTypes,
668 std::vector<LValue> &ResultRegDests, std::string &AsmString,
669 unsigned NumOutputs) const {
670 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
671
672 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
673 // larger.
674 if (!Constraints.empty())
675 Constraints += ',';
676 if (RetWidth <= 32) {
677 Constraints += "={eax}";
678 ResultRegTypes.push_back(CGF.Int32Ty);
679 } else {
680 // Use the 'A' constraint for EAX:EDX.
681 Constraints += "=A";
682 ResultRegTypes.push_back(CGF.Int64Ty);
683 }
684
685 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
686 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
687 ResultTruncRegTypes.push_back(CoerceTy);
688
689 // Coerce the integer by bitcasting the return slot pointer.
690 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
691 CoerceTy->getPointerTo()));
692 ResultRegDests.push_back(ReturnSlot);
693
694 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
695}
696
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000697/// shouldReturnTypeInRegister - Determine if the given type should be
698/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000699bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
700 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000701 uint64_t Size = Context.getTypeSize(Ty);
702
703 // Type must be register sized.
704 if (!isRegisterSize(Size))
705 return false;
706
707 if (Ty->isVectorType()) {
708 // 64- and 128- bit vectors inside structures are not returned in
709 // registers.
710 if (Size == 64 || Size == 128)
711 return false;
712
713 return true;
714 }
715
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000716 // If this is a builtin, pointer, enum, complex type, member pointer, or
717 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000718 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000719 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000720 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000721 return true;
722
723 // Arrays are treated like records.
724 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000725 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000726
727 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000728 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000729 if (!RT) return false;
730
Anders Carlsson40446e82010-01-27 03:25:19 +0000731 // FIXME: Traverse bases here too.
732
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000733 // Structure types are passed in register if all fields would be
734 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000735 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000736 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000737 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000738 continue;
739
740 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000741 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000742 return false;
743 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000744 return true;
745}
746
Reid Kleckner661f35b2014-01-18 01:12:41 +0000747ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
748 // If the return value is indirect, then the hidden argument is consuming one
749 // integer register.
750 if (State.FreeRegs) {
751 --State.FreeRegs;
752 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
753 }
754 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
755}
756
Reid Kleckner40ca9132014-05-13 22:05:45 +0000757ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000758 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000759 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000760
Chris Lattner458b2aa2010-07-29 02:16:43 +0000761 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000762 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000763 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000764 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000765
766 // 128-bit vectors are a special case; they are returned in
767 // registers and we need to make sure to pick a type the LLVM
768 // backend will like.
769 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000770 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000771 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000772
773 // Always return in register if it fits in a general purpose
774 // register, or if it is 64 bits and has a single element.
775 if ((Size == 8 || Size == 16 || Size == 32) ||
776 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000777 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000778 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000779
Reid Kleckner661f35b2014-01-18 01:12:41 +0000780 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000781 }
782
783 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000784 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000785
John McCalla1dee5302010-08-22 10:59:02 +0000786 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000787 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000788 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000789 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000790 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000791 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000792
David Chisnallde3a0692009-08-17 23:08:21 +0000793 // If specified, structs and unions are always indirect.
794 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000795 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000796
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000797 // Small structures which are register sized are generally returned
798 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000799 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000800 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000801
802 // As a special-case, if the struct is a "single-element" struct, and
803 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000804 // floating-point register. (MSVC does not apply this special case.)
805 // We apply a similar transformation for pointer types to improve the
806 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000807 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000808 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000809 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000810 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
811
812 // FIXME: We should be able to narrow this integer in cases with dead
813 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000814 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000815 }
816
Reid Kleckner661f35b2014-01-18 01:12:41 +0000817 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000818 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000819
Chris Lattner458b2aa2010-07-29 02:16:43 +0000820 // Treat an enum type as its underlying type.
821 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
822 RetTy = EnumTy->getDecl()->getIntegerType();
823
824 return (RetTy->isPromotableIntegerType() ?
825 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000826}
827
Eli Friedman7919bea2012-06-05 19:40:46 +0000828static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
829 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
830}
831
Daniel Dunbared23de32010-09-16 20:42:00 +0000832static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
833 const RecordType *RT = Ty->getAs<RecordType>();
834 if (!RT)
835 return 0;
836 const RecordDecl *RD = RT->getDecl();
837
838 // If this is a C++ record, check the bases first.
839 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000840 for (const auto &I : CXXRD->bases())
841 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000842 return false;
843
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000844 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000845 QualType FT = i->getType();
846
Eli Friedman7919bea2012-06-05 19:40:46 +0000847 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000848 return true;
849
850 if (isRecordWithSSEVectorType(Context, FT))
851 return true;
852 }
853
854 return false;
855}
856
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000857unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
858 unsigned Align) const {
859 // Otherwise, if the alignment is less than or equal to the minimum ABI
860 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000861 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000862 return 0; // Use default alignment.
863
864 // On non-Darwin, the stack type alignment is always 4.
865 if (!IsDarwinVectorABI) {
866 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000867 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000868 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000869
Daniel Dunbared23de32010-09-16 20:42:00 +0000870 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000871 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
872 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000873 return 16;
874
875 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000876}
877
Rafael Espindola703c47f2012-10-19 05:04:37 +0000878ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000879 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000880 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000881 if (State.FreeRegs) {
882 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000883 return ABIArgInfo::getIndirectInReg(0, false);
884 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000885 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000886 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000887
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000888 // Compute the byval alignment.
889 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
890 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
891 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000892 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000893
894 // If the stack alignment is less than the type alignment, realign the
895 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000896 bool Realign = TypeAlign > StackAlign;
897 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000898}
899
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000900X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
901 const Type *T = isSingleElementStruct(Ty, getContext());
902 if (!T)
903 T = Ty.getTypePtr();
904
905 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
906 BuiltinType::Kind K = BT->getKind();
907 if (K == BuiltinType::Float || K == BuiltinType::Double)
908 return Float;
909 }
910 return Integer;
911}
912
Reid Kleckner661f35b2014-01-18 01:12:41 +0000913bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
914 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000915 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000916 Class C = classify(Ty);
917 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000918 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000919
Rafael Espindola077dd592012-10-24 01:58:58 +0000920 unsigned Size = getContext().getTypeSize(Ty);
921 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000922
923 if (SizeInRegs == 0)
924 return false;
925
Reid Kleckner661f35b2014-01-18 01:12:41 +0000926 if (SizeInRegs > State.FreeRegs) {
927 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000928 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000929 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000930
Reid Kleckner661f35b2014-01-18 01:12:41 +0000931 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000932
Reid Kleckner661f35b2014-01-18 01:12:41 +0000933 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000934 if (Size > 32)
935 return false;
936
937 if (Ty->isIntegralOrEnumerationType())
938 return true;
939
940 if (Ty->isPointerType())
941 return true;
942
943 if (Ty->isReferenceType())
944 return true;
945
Reid Kleckner661f35b2014-01-18 01:12:41 +0000946 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000947 NeedsPadding = true;
948
Rafael Espindola077dd592012-10-24 01:58:58 +0000949 return false;
950 }
951
Rafael Espindola703c47f2012-10-19 05:04:37 +0000952 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000953}
954
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000955ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
956 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000957 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000958 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000959 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000960 // Check with the C++ ABI first.
961 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
962 if (RAA == CGCXXABI::RAA_Indirect) {
963 return getIndirectResult(Ty, false, State);
964 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
965 // The field index doesn't matter, we'll fix it up later.
966 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
967 }
968
969 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000970 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000971 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000972
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000973 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000974 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000975 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000976 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000977
Eli Friedman9f061a32011-11-18 00:28:11 +0000978 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000979 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980 return ABIArgInfo::getIgnore();
981
Rafael Espindolafad28de2012-10-24 01:59:00 +0000982 llvm::LLVMContext &LLVMContext = getVMContext();
983 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
984 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000985 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000986 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000987 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000988 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
989 return ABIArgInfo::getDirectInReg(Result);
990 }
Craig Topper8a13c412014-05-21 05:09:00 +0000991 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000992
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000993 // Expand small (<= 128-bit) record types when we know that the stack layout
994 // of those arguments will match the struct. This is important because the
995 // LLVM backend isn't smart enough to remove byval, which inhibits many
996 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000997 if (getContext().getTypeSize(Ty) <= 4*32 &&
998 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000999 return ABIArgInfo::getExpandWithPadding(
1000 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001001
Reid Kleckner661f35b2014-01-18 01:12:41 +00001002 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001003 }
1004
Chris Lattnerd774ae92010-08-26 20:05:13 +00001005 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001006 // On Darwin, some vectors are passed in memory, we handle this by passing
1007 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001008 if (IsDarwinVectorABI) {
1009 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001010 if ((Size == 8 || Size == 16 || Size == 32) ||
1011 (Size == 64 && VT->getNumElements() == 1))
1012 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1013 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001014 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001015
Chad Rosier651c1832013-03-25 21:00:27 +00001016 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1017 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001018
Chris Lattnerd774ae92010-08-26 20:05:13 +00001019 return ABIArgInfo::getDirect();
1020 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001021
1022
Chris Lattner458b2aa2010-07-29 02:16:43 +00001023 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1024 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001025
Rafael Espindolafad28de2012-10-24 01:59:00 +00001026 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001027 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001028
1029 if (Ty->isPromotableIntegerType()) {
1030 if (InReg)
1031 return ABIArgInfo::getExtendInReg();
1032 return ABIArgInfo::getExtend();
1033 }
1034 if (InReg)
1035 return ABIArgInfo::getDirectInReg();
1036 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001037}
1038
Rafael Espindolaa6472962012-07-24 00:01:07 +00001039void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001040 CCState State(FI.getCallingConvention());
1041 if (State.CC == llvm::CallingConv::X86_FastCall)
1042 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +00001043 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001044 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001045 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001046 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001047
Reid Kleckner677539d2014-07-10 01:58:55 +00001048 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001049 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001050 } else if (FI.getReturnInfo().isIndirect()) {
1051 // The C++ ABI is not aware of register usage, so we have to check if the
1052 // return value was sret and put it in a register ourselves if appropriate.
1053 if (State.FreeRegs) {
1054 --State.FreeRegs; // The sret parameter consumes a register.
1055 FI.getReturnInfo().setInReg(true);
1056 }
1057 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001058
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001059 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001060 for (auto &I : FI.arguments()) {
1061 I.info = classifyArgumentType(I.type, State);
1062 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001063 }
1064
1065 // If we needed to use inalloca for any argument, do a second pass and rewrite
1066 // all the memory arguments to use inalloca.
1067 if (UsedInAlloca)
1068 rewriteWithInAlloca(FI);
1069}
1070
1071void
1072X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1073 unsigned &StackOffset,
1074 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001075 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1076 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1077 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1078 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1079
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001080 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1081 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001082 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001083 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001084 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001085 unsigned NumBytes = StackOffset - OldOffset;
1086 assert(NumBytes);
1087 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1088 Ty = llvm::ArrayType::get(Ty, NumBytes);
1089 FrameFields.push_back(Ty);
1090 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001091}
1092
Reid Kleckner852361d2014-07-26 00:12:26 +00001093static bool isArgInAlloca(const ABIArgInfo &Info) {
1094 // Leave ignored and inreg arguments alone.
1095 switch (Info.getKind()) {
1096 case ABIArgInfo::InAlloca:
1097 return true;
1098 case ABIArgInfo::Indirect:
1099 assert(Info.getIndirectByVal());
1100 return true;
1101 case ABIArgInfo::Ignore:
1102 return false;
1103 case ABIArgInfo::Direct:
1104 case ABIArgInfo::Extend:
1105 case ABIArgInfo::Expand:
1106 if (Info.getInReg())
1107 return false;
1108 return true;
1109 }
1110 llvm_unreachable("invalid enum");
1111}
1112
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001113void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1114 assert(IsWin32StructABI && "inalloca only supported on win32");
1115
1116 // Build a packed struct type for all of the arguments in memory.
1117 SmallVector<llvm::Type *, 6> FrameFields;
1118
1119 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001120 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1121
1122 // Put 'this' into the struct before 'sret', if necessary.
1123 bool IsThisCall =
1124 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1125 ABIArgInfo &Ret = FI.getReturnInfo();
1126 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1127 isArgInAlloca(I->info)) {
1128 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1129 ++I;
1130 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001131
1132 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001133 if (Ret.isIndirect() && !Ret.getInReg()) {
1134 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1135 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001136 // On Windows, the hidden sret parameter is always returned in eax.
1137 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001138 }
1139
1140 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001141 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001142 ++I;
1143
1144 // Put arguments passed in memory into the struct.
1145 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001146 if (isArgInAlloca(I->info))
1147 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001148 }
1149
1150 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1151 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001152}
1153
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001154llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1155 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001156 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001157
1158 CGBuilderTy &Builder = CGF.Builder;
1159 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1160 "ap");
1161 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001162
1163 // Compute if the address needs to be aligned
1164 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1165 Align = getTypeStackAlignInBytes(Ty, Align);
1166 Align = std::max(Align, 4U);
1167 if (Align > 4) {
1168 // addr = (addr + align - 1) & -align;
1169 llvm::Value *Offset =
1170 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1171 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1172 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1173 CGF.Int32Ty);
1174 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1175 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1176 Addr->getType(),
1177 "ap.cur.aligned");
1178 }
1179
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001180 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001181 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001182 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1183
1184 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001185 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001186 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001187 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001188 "ap.next");
1189 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1190
1191 return AddrTyped;
1192}
1193
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001194bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1195 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1196 assert(Triple.getArch() == llvm::Triple::x86);
1197
1198 switch (Opts.getStructReturnConvention()) {
1199 case CodeGenOptions::SRCK_Default:
1200 break;
1201 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1202 return false;
1203 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1204 return true;
1205 }
1206
1207 if (Triple.isOSDarwin())
1208 return true;
1209
1210 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001211 case llvm::Triple::DragonFly:
1212 case llvm::Triple::FreeBSD:
1213 case llvm::Triple::OpenBSD:
1214 case llvm::Triple::Bitrig:
1215 return true;
1216 case llvm::Triple::Win32:
1217 switch (Triple.getEnvironment()) {
1218 case llvm::Triple::UnknownEnvironment:
1219 case llvm::Triple::Cygnus:
1220 case llvm::Triple::GNU:
1221 case llvm::Triple::MSVC:
1222 return true;
1223 default:
1224 return false;
1225 }
1226 default:
1227 return false;
1228 }
1229}
1230
Charles Davis4ea31ab2010-02-13 15:54:06 +00001231void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1232 llvm::GlobalValue *GV,
1233 CodeGen::CodeGenModule &CGM) const {
1234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1235 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1236 // Get the LLVM function.
1237 llvm::Function *Fn = cast<llvm::Function>(GV);
1238
1239 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001240 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001241 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001242 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1243 llvm::AttributeSet::get(CGM.getLLVMContext(),
1244 llvm::AttributeSet::FunctionIndex,
1245 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001246 }
1247 }
1248}
1249
John McCallbeec5a02010-03-06 00:35:14 +00001250bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1251 CodeGen::CodeGenFunction &CGF,
1252 llvm::Value *Address) const {
1253 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001254
Chris Lattnerece04092012-02-07 00:39:47 +00001255 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001256
John McCallbeec5a02010-03-06 00:35:14 +00001257 // 0-7 are the eight integer registers; the order is different
1258 // on Darwin (for EH), but the range is the same.
1259 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001260 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001261
John McCallc8e01702013-04-16 22:48:15 +00001262 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001263 // 12-16 are st(0..4). Not sure why we stop at 4.
1264 // These have size 16, which is sizeof(long double) on
1265 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001266 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001267 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001268
John McCallbeec5a02010-03-06 00:35:14 +00001269 } else {
1270 // 9 is %eflags, which doesn't get a size on Darwin for some
1271 // reason.
1272 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1273
1274 // 11-16 are st(0..5). Not sure why we stop at 5.
1275 // These have size 12, which is sizeof(long double) on
1276 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001277 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001278 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1279 }
John McCallbeec5a02010-03-06 00:35:14 +00001280
1281 return false;
1282}
1283
Chris Lattner0cf24192010-06-28 20:05:43 +00001284//===----------------------------------------------------------------------===//
1285// X86-64 ABI Implementation
1286//===----------------------------------------------------------------------===//
1287
1288
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001289namespace {
1290/// X86_64ABIInfo - The X86_64 ABI information.
1291class X86_64ABIInfo : public ABIInfo {
1292 enum Class {
1293 Integer = 0,
1294 SSE,
1295 SSEUp,
1296 X87,
1297 X87Up,
1298 ComplexX87,
1299 NoClass,
1300 Memory
1301 };
1302
1303 /// merge - Implement the X86_64 ABI merging algorithm.
1304 ///
1305 /// Merge an accumulating classification \arg Accum with a field
1306 /// classification \arg Field.
1307 ///
1308 /// \param Accum - The accumulating classification. This should
1309 /// always be either NoClass or the result of a previous merge
1310 /// call. In addition, this should never be Memory (the caller
1311 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001312 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001313
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001314 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1315 ///
1316 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1317 /// final MEMORY or SSE classes when necessary.
1318 ///
1319 /// \param AggregateSize - The size of the current aggregate in
1320 /// the classification process.
1321 ///
1322 /// \param Lo - The classification for the parts of the type
1323 /// residing in the low word of the containing object.
1324 ///
1325 /// \param Hi - The classification for the parts of the type
1326 /// residing in the higher words of the containing object.
1327 ///
1328 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1329
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001330 /// classify - Determine the x86_64 register classes in which the
1331 /// given type T should be passed.
1332 ///
1333 /// \param Lo - The classification for the parts of the type
1334 /// residing in the low word of the containing object.
1335 ///
1336 /// \param Hi - The classification for the parts of the type
1337 /// residing in the high word of the containing object.
1338 ///
1339 /// \param OffsetBase - The bit offset of this type in the
1340 /// containing object. Some parameters are classified different
1341 /// depending on whether they straddle an eightbyte boundary.
1342 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001343 /// \param isNamedArg - Whether the argument in question is a "named"
1344 /// argument, as used in AMD64-ABI 3.5.7.
1345 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001346 /// If a word is unused its result will be NoClass; if a type should
1347 /// be passed in Memory then at least the classification of \arg Lo
1348 /// will be Memory.
1349 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001350 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001351 ///
1352 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1353 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001354 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1355 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001356
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001357 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001358 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1359 unsigned IROffset, QualType SourceTy,
1360 unsigned SourceOffset) const;
1361 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1362 unsigned IROffset, QualType SourceTy,
1363 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001364
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001365 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001366 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001367 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001368
1369 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001370 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001371 ///
1372 /// \param freeIntRegs - The number of free integer registers remaining
1373 /// available.
1374 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001375
Chris Lattner458b2aa2010-07-29 02:16:43 +00001376 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001377
Bill Wendling5cd41c42010-10-18 03:41:31 +00001378 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001379 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001380 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001381 unsigned &neededSSE,
1382 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001383
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001384 bool IsIllegalVectorType(QualType Ty) const;
1385
John McCalle0fda732011-04-21 01:20:55 +00001386 /// The 0.98 ABI revision clarified a lot of ambiguities,
1387 /// unfortunately in ways that were not always consistent with
1388 /// certain previous compilers. In particular, platforms which
1389 /// required strict binary compatibility with older versions of GCC
1390 /// may need to exempt themselves.
1391 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001392 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001393 }
1394
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001395 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001396 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1397 // 64-bit hardware.
1398 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001399
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001401 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001402 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001403 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001404 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001405
John McCalla729c622012-02-17 03:33:10 +00001406 bool isPassedUsingAVXType(QualType type) const {
1407 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001408 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001409 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1410 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001411 if (info.isDirect()) {
1412 llvm::Type *ty = info.getCoerceToType();
1413 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1414 return (vectorTy->getBitWidth() > 128);
1415 }
1416 return false;
1417 }
1418
Craig Topper4f12f102014-03-12 06:41:41 +00001419 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001420
Craig Topper4f12f102014-03-12 06:41:41 +00001421 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1422 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001423};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001424
Chris Lattner04dc9572010-08-31 16:44:54 +00001425/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001426class WinX86_64ABIInfo : public ABIInfo {
1427
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001428 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001429
Chris Lattner04dc9572010-08-31 16:44:54 +00001430public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001431 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1432
Craig Topper4f12f102014-03-12 06:41:41 +00001433 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001434
Craig Topper4f12f102014-03-12 06:41:41 +00001435 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1436 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001437};
1438
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001439class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001440 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001441public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001442 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001443 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001444
John McCalla729c622012-02-17 03:33:10 +00001445 const X86_64ABIInfo &getABIInfo() const {
1446 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1447 }
1448
Craig Topper4f12f102014-03-12 06:41:41 +00001449 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001450 return 7;
1451 }
1452
1453 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001454 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001455 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001456
John McCall943fae92010-05-27 06:19:26 +00001457 // 0-15 are the 16 integer registers.
1458 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001459 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001460 return false;
1461 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001462
Jay Foad7c57be32011-07-11 09:56:20 +00001463 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001464 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001465 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001466 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1467 }
1468
John McCalla729c622012-02-17 03:33:10 +00001469 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001470 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001471 // The default CC on x86-64 sets %al to the number of SSA
1472 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001473 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001474 // that when AVX types are involved: the ABI explicitly states it is
1475 // undefined, and it doesn't work in practice because of how the ABI
1476 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001477 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001478 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001479 for (CallArgList::const_iterator
1480 it = args.begin(), ie = args.end(); it != ie; ++it) {
1481 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1482 HasAVXType = true;
1483 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001484 }
1485 }
John McCalla729c622012-02-17 03:33:10 +00001486
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001487 if (!HasAVXType)
1488 return true;
1489 }
John McCallcbc038a2011-09-21 08:08:30 +00001490
John McCalla729c622012-02-17 03:33:10 +00001491 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001492 }
1493
Craig Topper4f12f102014-03-12 06:41:41 +00001494 llvm::Constant *
1495 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001496 unsigned Sig = (0xeb << 0) | // jmp rel8
1497 (0x0a << 8) | // .+0x0c
1498 ('F' << 16) |
1499 ('T' << 24);
1500 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1501 }
1502
Alexander Musman09184fe2014-09-30 05:29:28 +00001503 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1504 return HasAVX ? 32 : 16;
1505 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001506};
1507
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001508static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1509 // If the argument does not end in .lib, automatically add the suffix. This
1510 // matches the behavior of MSVC.
1511 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001512 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001513 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001514 return ArgStr;
1515}
1516
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001517class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1518public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001519 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1520 bool d, bool p, bool w, unsigned RegParms)
1521 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001522
1523 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001524 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001525 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001526 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001527 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001528
1529 void getDetectMismatchOption(llvm::StringRef Name,
1530 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001531 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001532 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001533 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001534};
1535
Chris Lattner04dc9572010-08-31 16:44:54 +00001536class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001537 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001538public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001539 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1540 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001541
Craig Topper4f12f102014-03-12 06:41:41 +00001542 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001543 return 7;
1544 }
1545
1546 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001547 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001548 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001549
Chris Lattner04dc9572010-08-31 16:44:54 +00001550 // 0-15 are the 16 integer registers.
1551 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001552 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001553 return false;
1554 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001555
1556 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001557 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001558 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001559 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001560 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001561
1562 void getDetectMismatchOption(llvm::StringRef Name,
1563 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001564 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001565 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001566 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001567
1568 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1569 return HasAVX ? 32 : 16;
1570 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001571};
1572
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001573}
1574
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001575void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1576 Class &Hi) const {
1577 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1578 //
1579 // (a) If one of the classes is Memory, the whole argument is passed in
1580 // memory.
1581 //
1582 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1583 // memory.
1584 //
1585 // (c) If the size of the aggregate exceeds two eightbytes and the first
1586 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1587 // argument is passed in memory. NOTE: This is necessary to keep the
1588 // ABI working for processors that don't support the __m256 type.
1589 //
1590 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1591 //
1592 // Some of these are enforced by the merging logic. Others can arise
1593 // only with unions; for example:
1594 // union { _Complex double; unsigned; }
1595 //
1596 // Note that clauses (b) and (c) were added in 0.98.
1597 //
1598 if (Hi == Memory)
1599 Lo = Memory;
1600 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1601 Lo = Memory;
1602 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1603 Lo = Memory;
1604 if (Hi == SSEUp && Lo != SSE)
1605 Hi = SSE;
1606}
1607
Chris Lattnerd776fb12010-06-28 21:43:59 +00001608X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001609 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1610 // classified recursively so that always two fields are
1611 // considered. The resulting class is calculated according to
1612 // the classes of the fields in the eightbyte:
1613 //
1614 // (a) If both classes are equal, this is the resulting class.
1615 //
1616 // (b) If one of the classes is NO_CLASS, the resulting class is
1617 // the other class.
1618 //
1619 // (c) If one of the classes is MEMORY, the result is the MEMORY
1620 // class.
1621 //
1622 // (d) If one of the classes is INTEGER, the result is the
1623 // INTEGER.
1624 //
1625 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1626 // MEMORY is used as class.
1627 //
1628 // (f) Otherwise class SSE is used.
1629
1630 // Accum should never be memory (we should have returned) or
1631 // ComplexX87 (because this cannot be passed in a structure).
1632 assert((Accum != Memory && Accum != ComplexX87) &&
1633 "Invalid accumulated classification during merge.");
1634 if (Accum == Field || Field == NoClass)
1635 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001636 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001637 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001638 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001639 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001640 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001641 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001642 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1643 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001644 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001645 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001646}
1647
Chris Lattner5c740f12010-06-30 19:14:05 +00001648void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001649 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001650 // FIXME: This code can be simplified by introducing a simple value class for
1651 // Class pairs with appropriate constructor methods for the various
1652 // situations.
1653
1654 // FIXME: Some of the split computations are wrong; unaligned vectors
1655 // shouldn't be passed in registers for example, so there is no chance they
1656 // can straddle an eightbyte. Verify & simplify.
1657
1658 Lo = Hi = NoClass;
1659
1660 Class &Current = OffsetBase < 64 ? Lo : Hi;
1661 Current = Memory;
1662
John McCall9dd450b2009-09-21 23:43:11 +00001663 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001664 BuiltinType::Kind k = BT->getKind();
1665
1666 if (k == BuiltinType::Void) {
1667 Current = NoClass;
1668 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1669 Lo = Integer;
1670 Hi = Integer;
1671 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1672 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001673 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1674 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001675 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001676 Current = SSE;
1677 } else if (k == BuiltinType::LongDouble) {
1678 Lo = X87;
1679 Hi = X87Up;
1680 }
1681 // FIXME: _Decimal32 and _Decimal64 are SSE.
1682 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001683 return;
1684 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001685
Chris Lattnerd776fb12010-06-28 21:43:59 +00001686 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001687 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001688 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001689 return;
1690 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001691
Chris Lattnerd776fb12010-06-28 21:43:59 +00001692 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001693 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001694 return;
1695 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001696
Chris Lattnerd776fb12010-06-28 21:43:59 +00001697 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001698 if (Ty->isMemberFunctionPointerType()) {
1699 if (Has64BitPointers) {
1700 // If Has64BitPointers, this is an {i64, i64}, so classify both
1701 // Lo and Hi now.
1702 Lo = Hi = Integer;
1703 } else {
1704 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1705 // straddles an eightbyte boundary, Hi should be classified as well.
1706 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1707 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1708 if (EB_FuncPtr != EB_ThisAdj) {
1709 Lo = Hi = Integer;
1710 } else {
1711 Current = Integer;
1712 }
1713 }
1714 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001715 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001716 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001717 return;
1718 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001719
Chris Lattnerd776fb12010-06-28 21:43:59 +00001720 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001721 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001722 if (Size == 32) {
1723 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1724 // float> as integer.
1725 Current = Integer;
1726
1727 // If this type crosses an eightbyte boundary, it should be
1728 // split.
1729 uint64_t EB_Real = (OffsetBase) / 64;
1730 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1731 if (EB_Real != EB_Imag)
1732 Hi = Lo;
1733 } else if (Size == 64) {
1734 // gcc passes <1 x double> in memory. :(
1735 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1736 return;
1737
1738 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001739 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001740 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1741 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1742 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001743 Current = Integer;
1744 else
1745 Current = SSE;
1746
1747 // If this type crosses an eightbyte boundary, it should be
1748 // split.
1749 if (OffsetBase && OffsetBase != 64)
1750 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001751 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001752 // Arguments of 256-bits are split into four eightbyte chunks. The
1753 // least significant one belongs to class SSE and all the others to class
1754 // SSEUP. The original Lo and Hi design considers that types can't be
1755 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1756 // This design isn't correct for 256-bits, but since there're no cases
1757 // where the upper parts would need to be inspected, avoid adding
1758 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001759 //
1760 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1761 // registers if they are "named", i.e. not part of the "..." of a
1762 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001763 Lo = SSE;
1764 Hi = SSEUp;
1765 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001766 return;
1767 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001768
Chris Lattnerd776fb12010-06-28 21:43:59 +00001769 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001770 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001771
Chris Lattner2b037972010-07-29 02:01:43 +00001772 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001773 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001774 if (Size <= 64)
1775 Current = Integer;
1776 else if (Size <= 128)
1777 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001778 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001779 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001780 else if (ET == getContext().DoubleTy ||
1781 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001782 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001783 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001784 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001785 Current = ComplexX87;
1786
1787 // If this complex type crosses an eightbyte boundary then it
1788 // should be split.
1789 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001790 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001791 if (Hi == NoClass && EB_Real != EB_Imag)
1792 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001793
Chris Lattnerd776fb12010-06-28 21:43:59 +00001794 return;
1795 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001796
Chris Lattner2b037972010-07-29 02:01:43 +00001797 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001798 // Arrays are treated like structures.
1799
Chris Lattner2b037972010-07-29 02:01:43 +00001800 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001801
1802 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001803 // than four eightbytes, ..., it has class MEMORY.
1804 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001805 return;
1806
1807 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1808 // fields, it has class MEMORY.
1809 //
1810 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001811 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001812 return;
1813
1814 // Otherwise implement simplified merge. We could be smarter about
1815 // this, but it isn't worth it and would be harder to verify.
1816 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001817 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001818 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001819
1820 // The only case a 256-bit wide vector could be used is when the array
1821 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1822 // to work for sizes wider than 128, early check and fallback to memory.
1823 if (Size > 128 && EltSize != 256)
1824 return;
1825
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001826 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1827 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001828 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001829 Lo = merge(Lo, FieldLo);
1830 Hi = merge(Hi, FieldHi);
1831 if (Lo == Memory || Hi == Memory)
1832 break;
1833 }
1834
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001835 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001836 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001837 return;
1838 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001839
Chris Lattnerd776fb12010-06-28 21:43:59 +00001840 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001841 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001842
1843 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001844 // than four eightbytes, ..., it has class MEMORY.
1845 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001846 return;
1847
Anders Carlsson20759ad2009-09-16 15:53:40 +00001848 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1849 // copy constructor or a non-trivial destructor, it is passed by invisible
1850 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001851 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001852 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001853
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001854 const RecordDecl *RD = RT->getDecl();
1855
1856 // Assume variable sized types are passed in memory.
1857 if (RD->hasFlexibleArrayMember())
1858 return;
1859
Chris Lattner2b037972010-07-29 02:01:43 +00001860 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001861
1862 // Reset Lo class, this will be recomputed.
1863 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001864
1865 // If this is a C++ record, classify the bases first.
1866 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001867 for (const auto &I : CXXRD->bases()) {
1868 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001869 "Unexpected base class!");
1870 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001871 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001872
1873 // Classify this field.
1874 //
1875 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1876 // single eightbyte, each is classified separately. Each eightbyte gets
1877 // initialized to class NO_CLASS.
1878 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001879 uint64_t Offset =
1880 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001881 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001882 Lo = merge(Lo, FieldLo);
1883 Hi = merge(Hi, FieldHi);
1884 if (Lo == Memory || Hi == Memory)
1885 break;
1886 }
1887 }
1888
1889 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001890 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001891 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001892 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001893 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1894 bool BitField = i->isBitField();
1895
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001896 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1897 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001898 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001899 // The only case a 256-bit wide vector could be used is when the struct
1900 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1901 // to work for sizes wider than 128, early check and fallback to memory.
1902 //
1903 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1904 Lo = Memory;
1905 return;
1906 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001907 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001908 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001909 Lo = Memory;
1910 return;
1911 }
1912
1913 // Classify this field.
1914 //
1915 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1916 // exceeds a single eightbyte, each is classified
1917 // separately. Each eightbyte gets initialized to class
1918 // NO_CLASS.
1919 Class FieldLo, FieldHi;
1920
1921 // Bit-fields require special handling, they do not force the
1922 // structure to be passed in memory even if unaligned, and
1923 // therefore they can straddle an eightbyte.
1924 if (BitField) {
1925 // Ignore padding bit-fields.
1926 if (i->isUnnamedBitfield())
1927 continue;
1928
1929 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001930 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001931
1932 uint64_t EB_Lo = Offset / 64;
1933 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001934
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001935 if (EB_Lo) {
1936 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1937 FieldLo = NoClass;
1938 FieldHi = Integer;
1939 } else {
1940 FieldLo = Integer;
1941 FieldHi = EB_Hi ? Integer : NoClass;
1942 }
1943 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001944 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001945 Lo = merge(Lo, FieldLo);
1946 Hi = merge(Hi, FieldHi);
1947 if (Lo == Memory || Hi == Memory)
1948 break;
1949 }
1950
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001951 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001952 }
1953}
1954
Chris Lattner22a931e2010-06-29 06:01:59 +00001955ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001956 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1957 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001958 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001959 // Treat an enum type as its underlying type.
1960 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1961 Ty = EnumTy->getDecl()->getIntegerType();
1962
1963 return (Ty->isPromotableIntegerType() ?
1964 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1965 }
1966
1967 return ABIArgInfo::getIndirect(0);
1968}
1969
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001970bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1971 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1972 uint64_t Size = getContext().getTypeSize(VecTy);
1973 unsigned LargestVector = HasAVX ? 256 : 128;
1974 if (Size <= 64 || Size > LargestVector)
1975 return true;
1976 }
1977
1978 return false;
1979}
1980
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001981ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1982 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001983 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1984 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001985 //
1986 // This assumption is optimistic, as there could be free registers available
1987 // when we need to pass this argument in memory, and LLVM could try to pass
1988 // the argument in the free register. This does not seem to happen currently,
1989 // but this code would be much safer if we could mark the argument with
1990 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001991 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001992 // Treat an enum type as its underlying type.
1993 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1994 Ty = EnumTy->getDecl()->getIntegerType();
1995
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001996 return (Ty->isPromotableIntegerType() ?
1997 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001998 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001999
Mark Lacey3825e832013-10-06 01:33:34 +00002000 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002001 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002002
Chris Lattner44c2b902011-05-22 23:21:23 +00002003 // Compute the byval alignment. We specify the alignment of the byval in all
2004 // cases so that the mid-level optimizer knows the alignment of the byval.
2005 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002006
2007 // Attempt to avoid passing indirect results using byval when possible. This
2008 // is important for good codegen.
2009 //
2010 // We do this by coercing the value into a scalar type which the backend can
2011 // handle naturally (i.e., without using byval).
2012 //
2013 // For simplicity, we currently only do this when we have exhausted all of the
2014 // free integer registers. Doing this when there are free integer registers
2015 // would require more care, as we would have to ensure that the coerced value
2016 // did not claim the unused register. That would require either reording the
2017 // arguments to the function (so that any subsequent inreg values came first),
2018 // or only doing this optimization when there were no following arguments that
2019 // might be inreg.
2020 //
2021 // We currently expect it to be rare (particularly in well written code) for
2022 // arguments to be passed on the stack when there are still free integer
2023 // registers available (this would typically imply large structs being passed
2024 // by value), so this seems like a fair tradeoff for now.
2025 //
2026 // We can revisit this if the backend grows support for 'onstack' parameter
2027 // attributes. See PR12193.
2028 if (freeIntRegs == 0) {
2029 uint64_t Size = getContext().getTypeSize(Ty);
2030
2031 // If this type fits in an eightbyte, coerce it into the matching integral
2032 // type, which will end up on the stack (with alignment 8).
2033 if (Align == 8 && Size <= 64)
2034 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2035 Size));
2036 }
2037
Chris Lattner44c2b902011-05-22 23:21:23 +00002038 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002039}
2040
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002041/// GetByteVectorType - The ABI specifies that a value should be passed in an
2042/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00002043/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002044llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002045 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002046
Chris Lattner9fa15c32010-07-29 05:02:29 +00002047 // Wrapper structs that just contain vectors are passed just like vectors,
2048 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002049 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00002050 while (STy && STy->getNumElements() == 1) {
2051 IRType = STy->getElementType(0);
2052 STy = dyn_cast<llvm::StructType>(IRType);
2053 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002054
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00002055 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002056 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2057 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002058 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00002059 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00002060 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2061 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2062 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2063 EltTy->isIntegerTy(128)))
2064 return VT;
2065 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002066
Chris Lattner4200fe42010-07-29 04:56:46 +00002067 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2068}
2069
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002070/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2071/// is known to either be off the end of the specified type or being in
2072/// alignment padding. The user type specified is known to be at most 128 bits
2073/// in size, and have passed through X86_64ABIInfo::classify with a successful
2074/// classification that put one of the two halves in the INTEGER class.
2075///
2076/// It is conservatively correct to return false.
2077static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2078 unsigned EndBit, ASTContext &Context) {
2079 // If the bytes being queried are off the end of the type, there is no user
2080 // data hiding here. This handles analysis of builtins, vectors and other
2081 // types that don't contain interesting padding.
2082 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2083 if (TySize <= StartBit)
2084 return true;
2085
Chris Lattner98076a22010-07-29 07:43:55 +00002086 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2087 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2088 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2089
2090 // Check each element to see if the element overlaps with the queried range.
2091 for (unsigned i = 0; i != NumElts; ++i) {
2092 // If the element is after the span we care about, then we're done..
2093 unsigned EltOffset = i*EltSize;
2094 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002095
Chris Lattner98076a22010-07-29 07:43:55 +00002096 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2097 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2098 EndBit-EltOffset, Context))
2099 return false;
2100 }
2101 // If it overlaps no elements, then it is safe to process as padding.
2102 return true;
2103 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002104
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002105 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2106 const RecordDecl *RD = RT->getDecl();
2107 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002108
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002109 // If this is a C++ record, check the bases first.
2110 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002111 for (const auto &I : CXXRD->bases()) {
2112 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002113 "Unexpected base class!");
2114 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002115 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002116
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002117 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002118 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002119 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002120
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002121 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002122 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002123 EndBit-BaseOffset, Context))
2124 return false;
2125 }
2126 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002127
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002128 // Verify that no field has data that overlaps the region of interest. Yes
2129 // this could be sped up a lot by being smarter about queried fields,
2130 // however we're only looking at structs up to 16 bytes, so we don't care
2131 // much.
2132 unsigned idx = 0;
2133 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2134 i != e; ++i, ++idx) {
2135 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002136
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002137 // If we found a field after the region we care about, then we're done.
2138 if (FieldOffset >= EndBit) break;
2139
2140 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2141 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2142 Context))
2143 return false;
2144 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002145
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002146 // If nothing in this record overlapped the area of interest, then we're
2147 // clean.
2148 return true;
2149 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002150
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002151 return false;
2152}
2153
Chris Lattnere556a712010-07-29 18:39:32 +00002154/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2155/// float member at the specified offset. For example, {int,{float}} has a
2156/// float at offset 4. It is conservatively correct for this routine to return
2157/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002158static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002159 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002160 // Base case if we find a float.
2161 if (IROffset == 0 && IRType->isFloatTy())
2162 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002163
Chris Lattnere556a712010-07-29 18:39:32 +00002164 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002165 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002166 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2167 unsigned Elt = SL->getElementContainingOffset(IROffset);
2168 IROffset -= SL->getElementOffset(Elt);
2169 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2170 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002171
Chris Lattnere556a712010-07-29 18:39:32 +00002172 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002173 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2174 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002175 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2176 IROffset -= IROffset/EltSize*EltSize;
2177 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2178 }
2179
2180 return false;
2181}
2182
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002183
2184/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2185/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002186llvm::Type *X86_64ABIInfo::
2187GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002188 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002189 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002190 // pass as float if the last 4 bytes is just padding. This happens for
2191 // structs that contain 3 floats.
2192 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2193 SourceOffset*8+64, getContext()))
2194 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002195
Chris Lattnere556a712010-07-29 18:39:32 +00002196 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2197 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2198 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002199 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2200 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002201 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002202
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002203 return llvm::Type::getDoubleTy(getVMContext());
2204}
2205
2206
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002207/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2208/// an 8-byte GPR. This means that we either have a scalar or we are talking
2209/// about the high or low part of an up-to-16-byte struct. This routine picks
2210/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002211/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2212/// etc).
2213///
2214/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2215/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2216/// the 8-byte value references. PrefType may be null.
2217///
Alp Toker9907f082014-07-09 14:06:35 +00002218/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002219/// an offset into this that we're processing (which is always either 0 or 8).
2220///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002221llvm::Type *X86_64ABIInfo::
2222GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002223 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002224 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2225 // returning an 8-byte unit starting with it. See if we can safely use it.
2226 if (IROffset == 0) {
2227 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002228 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2229 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002230 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002231
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002232 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2233 // goodness in the source type is just tail padding. This is allowed to
2234 // kick in for struct {double,int} on the int, but not on
2235 // struct{double,int,int} because we wouldn't return the second int. We
2236 // have to do this analysis on the source type because we can't depend on
2237 // unions being lowered a specific way etc.
2238 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002239 IRType->isIntegerTy(32) ||
2240 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2241 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2242 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002243
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002244 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2245 SourceOffset*8+64, getContext()))
2246 return IRType;
2247 }
2248 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002249
Chris Lattner2192fe52011-07-18 04:24:23 +00002250 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002251 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002252 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002253 if (IROffset < SL->getSizeInBytes()) {
2254 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2255 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002256
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002257 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2258 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002259 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002260 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002261
Chris Lattner2192fe52011-07-18 04:24:23 +00002262 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002263 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002264 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002265 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002266 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2267 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002268 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002269
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002270 // Okay, we don't have any better idea of what to pass, so we pass this in an
2271 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002272 unsigned TySizeInBytes =
2273 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002274
Chris Lattner3f763422010-07-29 17:34:39 +00002275 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002276
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002277 // It is always safe to classify this as an integer type up to i64 that
2278 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002279 return llvm::IntegerType::get(getVMContext(),
2280 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002281}
2282
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002283
2284/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2285/// be used as elements of a two register pair to pass or return, return a
2286/// first class aggregate to represent them. For example, if the low part of
2287/// a by-value argument should be passed as i32* and the high part as float,
2288/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002289static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002290GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002291 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002292 // In order to correctly satisfy the ABI, we need to the high part to start
2293 // at offset 8. If the high and low parts we inferred are both 4-byte types
2294 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2295 // the second element at offset 8. Check for this:
2296 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2297 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002298 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002299 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002300
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002301 // To handle this, we have to increase the size of the low part so that the
2302 // second element will start at an 8 byte offset. We can't increase the size
2303 // of the second element because it might make us access off the end of the
2304 // struct.
2305 if (HiStart != 8) {
2306 // There are only two sorts of types the ABI generation code can produce for
2307 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2308 // Promote these to a larger type.
2309 if (Lo->isFloatTy())
2310 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2311 else {
2312 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2313 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2314 }
2315 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002316
Chris Lattnera5f58b02011-07-09 17:41:47 +00002317 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002318
2319
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002320 // Verify that the second element is at an 8-byte offset.
2321 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2322 "Invalid x86-64 argument pair!");
2323 return Result;
2324}
2325
Chris Lattner31faff52010-07-28 23:06:14 +00002326ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002327classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002328 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2329 // classification algorithm.
2330 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002331 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002332
2333 // Check some invariants.
2334 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002335 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2336
Craig Topper8a13c412014-05-21 05:09:00 +00002337 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002338 switch (Lo) {
2339 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002340 if (Hi == NoClass)
2341 return ABIArgInfo::getIgnore();
2342 // If the low part is just padding, it takes no register, leave ResType
2343 // null.
2344 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2345 "Unknown missing lo part");
2346 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002347
2348 case SSEUp:
2349 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002350 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002351
2352 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2353 // hidden argument.
2354 case Memory:
2355 return getIndirectReturnResult(RetTy);
2356
2357 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2358 // available register of the sequence %rax, %rdx is used.
2359 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002360 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002361
Chris Lattner1f3a0632010-07-29 21:42:50 +00002362 // If we have a sign or zero extended integer, make sure to return Extend
2363 // so that the parameter gets the right LLVM IR attributes.
2364 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2365 // Treat an enum type as its underlying type.
2366 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2367 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002368
Chris Lattner1f3a0632010-07-29 21:42:50 +00002369 if (RetTy->isIntegralOrEnumerationType() &&
2370 RetTy->isPromotableIntegerType())
2371 return ABIArgInfo::getExtend();
2372 }
Chris Lattner31faff52010-07-28 23:06:14 +00002373 break;
2374
2375 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2376 // available SSE register of the sequence %xmm0, %xmm1 is used.
2377 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002378 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002379 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002380
2381 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2382 // returned on the X87 stack in %st0 as 80-bit x87 number.
2383 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002384 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002385 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002386
2387 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2388 // part of the value is returned in %st0 and the imaginary part in
2389 // %st1.
2390 case ComplexX87:
2391 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002392 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002393 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002394 NULL);
2395 break;
2396 }
2397
Craig Topper8a13c412014-05-21 05:09:00 +00002398 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002399 switch (Hi) {
2400 // Memory was handled previously and X87 should
2401 // never occur as a hi class.
2402 case Memory:
2403 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002404 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002405
2406 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002407 case NoClass:
2408 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002409
Chris Lattner52b3c132010-09-01 00:20:33 +00002410 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002411 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002412 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2413 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002414 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002415 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002416 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002417 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2418 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002419 break;
2420
2421 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002422 // is passed in the next available eightbyte chunk if the last used
2423 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002424 //
Chris Lattner57540c52011-04-15 05:22:18 +00002425 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002426 case SSEUp:
2427 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002428 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002429 break;
2430
2431 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2432 // returned together with the previous X87 value in %st0.
2433 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002434 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002435 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002436 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002437 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002438 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002439 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002440 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2441 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002442 }
Chris Lattner31faff52010-07-28 23:06:14 +00002443 break;
2444 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002445
Chris Lattner52b3c132010-09-01 00:20:33 +00002446 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002447 // known to pass in the high eightbyte of the result. We do this by forming a
2448 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002449 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002450 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002451
Chris Lattner1f3a0632010-07-29 21:42:50 +00002452 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002453}
2454
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002455ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002456 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2457 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002458 const
2459{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002460 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002461 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002462
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002463 // Check some invariants.
2464 // FIXME: Enforce these by construction.
2465 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002466 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2467
2468 neededInt = 0;
2469 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002470 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002471 switch (Lo) {
2472 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002473 if (Hi == NoClass)
2474 return ABIArgInfo::getIgnore();
2475 // If the low part is just padding, it takes no register, leave ResType
2476 // null.
2477 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2478 "Unknown missing lo part");
2479 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002480
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002481 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2482 // on the stack.
2483 case Memory:
2484
2485 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2486 // COMPLEX_X87, it is passed in memory.
2487 case X87:
2488 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002489 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002490 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002491 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002492
2493 case SSEUp:
2494 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002495 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002496
2497 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2498 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2499 // and %r9 is used.
2500 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002501 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002502
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002503 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002504 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002505
2506 // If we have a sign or zero extended integer, make sure to return Extend
2507 // so that the parameter gets the right LLVM IR attributes.
2508 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2509 // Treat an enum type as its underlying type.
2510 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2511 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002512
Chris Lattner1f3a0632010-07-29 21:42:50 +00002513 if (Ty->isIntegralOrEnumerationType() &&
2514 Ty->isPromotableIntegerType())
2515 return ABIArgInfo::getExtend();
2516 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002517
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518 break;
2519
2520 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2521 // available SSE register is used, the registers are taken in the
2522 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002523 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002524 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002525 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002526 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 break;
2528 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002529 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002530
Craig Topper8a13c412014-05-21 05:09:00 +00002531 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532 switch (Hi) {
2533 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002534 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002535 // which is passed in memory.
2536 case Memory:
2537 case X87:
2538 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002539 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002540
2541 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002542
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002543 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002544 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002545 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002546 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002547
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002548 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2549 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002550 break;
2551
2552 // X87Up generally doesn't occur here (long double is passed in
2553 // memory), except in situations involving unions.
2554 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002555 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002556 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002557
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002558 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2559 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002560
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002561 ++neededSSE;
2562 break;
2563
2564 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2565 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002566 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002567 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002568 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002569 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002570 break;
2571 }
2572
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002573 // If a high part was specified, merge it together with the low part. It is
2574 // known to pass in the high eightbyte of the result. We do this by forming a
2575 // first class struct aggregate with the high and low part: {low, high}
2576 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002577 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002578
Chris Lattner1f3a0632010-07-29 21:42:50 +00002579 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002580}
2581
Chris Lattner22326a12010-07-29 02:31:05 +00002582void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002583
Reid Kleckner40ca9132014-05-13 22:05:45 +00002584 if (!getCXXABI().classifyReturnType(FI))
2585 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002586
2587 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002588 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002589
2590 // If the return value is indirect, then the hidden argument is consuming one
2591 // integer register.
2592 if (FI.getReturnInfo().isIndirect())
2593 --freeIntRegs;
2594
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002595 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002596 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2597 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002598 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002599 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002600 it != ie; ++it, ++ArgNo) {
2601 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002602
Bill Wendling9987c0e2010-10-18 23:51:38 +00002603 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002604 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002605 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002606
2607 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2608 // eightbyte of an argument, the whole argument is passed on the
2609 // stack. If registers have already been assigned for some
2610 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002611 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002612 freeIntRegs -= neededInt;
2613 freeSSERegs -= neededSSE;
2614 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002615 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 }
2617 }
2618}
2619
2620static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2621 QualType Ty,
2622 CodeGenFunction &CGF) {
2623 llvm::Value *overflow_arg_area_p =
2624 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2625 llvm::Value *overflow_arg_area =
2626 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2627
2628 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2629 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002630 // It isn't stated explicitly in the standard, but in practice we use
2631 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002632 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2633 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002634 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002635 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002636 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002637 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2638 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002639 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002640 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002641 overflow_arg_area =
2642 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2643 overflow_arg_area->getType(),
2644 "overflow_arg_area.align");
2645 }
2646
2647 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002648 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 llvm::Value *Res =
2650 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002651 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002652
2653 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2654 // l->overflow_arg_area + sizeof(type).
2655 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2656 // an 8 byte boundary.
2657
2658 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002659 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002660 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2662 "overflow_arg_area.next");
2663 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2664
2665 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2666 return Res;
2667}
2668
2669llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2670 CodeGenFunction &CGF) const {
2671 // Assume that va_list type is correct; should be pointer to LLVM type:
2672 // struct {
2673 // i32 gp_offset;
2674 // i32 fp_offset;
2675 // i8* overflow_arg_area;
2676 // i8* reg_save_area;
2677 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002678 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002679
Chris Lattner9723d6c2010-03-11 18:19:55 +00002680 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002681 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2682 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002683
2684 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2685 // in the registers. If not go to step 7.
2686 if (!neededInt && !neededSSE)
2687 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2688
2689 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2690 // general purpose registers needed to pass type and num_fp to hold
2691 // the number of floating point registers needed.
2692
2693 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2694 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2695 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2696 //
2697 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2698 // register save space).
2699
Craig Topper8a13c412014-05-21 05:09:00 +00002700 llvm::Value *InRegs = nullptr;
2701 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2702 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002703 if (neededInt) {
2704 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2705 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002706 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2707 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002708 }
2709
2710 if (neededSSE) {
2711 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2712 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2713 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002714 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2715 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002716 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2717 }
2718
2719 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2720 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2721 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2722 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2723
2724 // Emit code to load the value if it was passed in registers.
2725
2726 CGF.EmitBlock(InRegBlock);
2727
2728 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2729 // an offset of l->gp_offset and/or l->fp_offset. This may require
2730 // copying to a temporary location in case the parameter is passed
2731 // in different register classes or requires an alignment greater
2732 // than 8 for general purpose registers and 16 for XMM registers.
2733 //
2734 // FIXME: This really results in shameful code when we end up needing to
2735 // collect arguments from different places; often what should result in a
2736 // simple assembling of a structure from scattered addresses has many more
2737 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002738 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002739 llvm::Value *RegAddr =
2740 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2741 "reg_save_area");
2742 if (neededInt && neededSSE) {
2743 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002744 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002745 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002746 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2747 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002748 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002749 llvm::Type *TyLo = ST->getElementType(0);
2750 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002751 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002752 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002753 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2754 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002755 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2756 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002757 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2758 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002759 llvm::Value *V =
2760 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2761 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2762 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2763 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2764
Owen Anderson170229f2009-07-14 23:10:40 +00002765 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002766 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002767 } else if (neededInt) {
2768 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2769 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002770 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002771
2772 // Copy to a temporary if necessary to ensure the appropriate alignment.
2773 std::pair<CharUnits, CharUnits> SizeAlign =
2774 CGF.getContext().getTypeInfoInChars(Ty);
2775 uint64_t TySize = SizeAlign.first.getQuantity();
2776 unsigned TyAlign = SizeAlign.second.getQuantity();
2777 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002778 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2779 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2780 RegAddr = Tmp;
2781 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002782 } else if (neededSSE == 1) {
2783 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2784 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2785 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002786 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002787 assert(neededSSE == 2 && "Invalid number of needed registers!");
2788 // SSE registers are spaced 16 bytes apart in the register save
2789 // area, we need to collect the two eightbytes together.
2790 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002791 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002792 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002793 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002794 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002795 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2796 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2797 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002798 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2799 DblPtrTy));
2800 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2801 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2802 DblPtrTy));
2803 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2804 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2805 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002806 }
2807
2808 // AMD64-ABI 3.5.7p5: Step 5. Set:
2809 // l->gp_offset = l->gp_offset + num_gp * 8
2810 // l->fp_offset = l->fp_offset + num_fp * 16.
2811 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002812 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002813 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2814 gp_offset_p);
2815 }
2816 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002817 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2819 fp_offset_p);
2820 }
2821 CGF.EmitBranch(ContBlock);
2822
2823 // Emit code to load the value if it was passed in memory.
2824
2825 CGF.EmitBlock(InMemBlock);
2826 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2827
2828 // Return the appropriate result.
2829
2830 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002831 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002832 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002833 ResAddr->addIncoming(RegAddr, InRegBlock);
2834 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002835 return ResAddr;
2836}
2837
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002838ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002839
2840 if (Ty->isVoidType())
2841 return ABIArgInfo::getIgnore();
2842
2843 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2844 Ty = EnumTy->getDecl()->getIntegerType();
2845
2846 uint64_t Size = getContext().getTypeSize(Ty);
2847
Reid Kleckner9005f412014-05-02 00:51:20 +00002848 const RecordType *RT = Ty->getAs<RecordType>();
2849 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002850 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002851 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002852 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2853 }
2854
2855 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002856 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2857
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002858 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00002859 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002860 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2861 Size));
Reid Kleckner9005f412014-05-02 00:51:20 +00002862 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002863
Reid Klecknerec87fec2014-05-02 01:17:12 +00002864 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002865 // If the member pointer is represented by an LLVM int or ptr, pass it
2866 // directly.
2867 llvm::Type *LLTy = CGT.ConvertType(Ty);
2868 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2869 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002870 }
2871
2872 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002873 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2874 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner9005f412014-05-02 00:51:20 +00002875 if (Size > 64 || !llvm::isPowerOf2_64(Size))
2876 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002877
Reid Kleckner9005f412014-05-02 00:51:20 +00002878 // Otherwise, coerce it to a small integer.
2879 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002880 }
2881
Julien Lerouge10dcff82014-08-27 00:36:55 +00002882 // Bool type is always extended to the ABI, other builtin types are not
2883 // extended.
2884 const BuiltinType *BT = Ty->getAs<BuiltinType>();
2885 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00002886 return ABIArgInfo::getExtend();
2887
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002888 return ABIArgInfo::getDirect();
2889}
2890
2891void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002892 if (!getCXXABI().classifyReturnType(FI))
2893 FI.getReturnInfo() = classify(FI.getReturnType(), true);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002894
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002895 for (auto &I : FI.arguments())
2896 I.info = classify(I.type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002897}
2898
Chris Lattner04dc9572010-08-31 16:44:54 +00002899llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2900 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002901 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002902
Chris Lattner04dc9572010-08-31 16:44:54 +00002903 CGBuilderTy &Builder = CGF.Builder;
2904 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2905 "ap");
2906 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2907 llvm::Type *PTy =
2908 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2909 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2910
2911 uint64_t Offset =
2912 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2913 llvm::Value *NextAddr =
2914 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2915 "ap.next");
2916 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2917
2918 return AddrTyped;
2919}
Chris Lattner0cf24192010-06-28 20:05:43 +00002920
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002921namespace {
2922
Derek Schuffa2020962012-10-16 22:30:41 +00002923class NaClX86_64ABIInfo : public ABIInfo {
2924 public:
2925 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2926 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002927 void computeInfo(CGFunctionInfo &FI) const override;
2928 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2929 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00002930 private:
2931 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2932 X86_64ABIInfo NInfo; // Used for everything else.
2933};
2934
2935class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00002936 bool HasAVX;
Derek Schuffa2020962012-10-16 22:30:41 +00002937 public:
Alexander Musman09184fe2014-09-30 05:29:28 +00002938 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2939 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {
2940 }
2941 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
2942 return HasAVX ? 32 : 16;
2943 }
Derek Schuffa2020962012-10-16 22:30:41 +00002944};
2945
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002946}
2947
Derek Schuffa2020962012-10-16 22:30:41 +00002948void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2949 if (FI.getASTCallingConvention() == CC_PnaclCall)
2950 PInfo.computeInfo(FI);
2951 else
2952 NInfo.computeInfo(FI);
2953}
2954
2955llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2956 CodeGenFunction &CGF) const {
2957 // Always use the native convention; calling pnacl-style varargs functions
2958 // is unuspported.
2959 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2960}
2961
2962
John McCallea8d8bb2010-03-11 00:10:12 +00002963// PowerPC-32
2964
2965namespace {
2966class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2967public:
Chris Lattner2b037972010-07-29 02:01:43 +00002968 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002969
Craig Topper4f12f102014-03-12 06:41:41 +00002970 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00002971 // This is recovered from gcc output.
2972 return 1; // r1 is the dedicated stack pointer
2973 }
2974
2975 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002976 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00002977
2978 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
2979 return 16; // Natural alignment for Altivec vectors.
2980 }
John McCallea8d8bb2010-03-11 00:10:12 +00002981};
2982
2983}
2984
2985bool
2986PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2987 llvm::Value *Address) const {
2988 // This is calculated from the LLVM and GCC tables and verified
2989 // against gcc output. AFAIK all ABIs use the same encoding.
2990
2991 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002992
Chris Lattnerece04092012-02-07 00:39:47 +00002993 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002994 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2995 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2996 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2997
2998 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002999 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003000
3001 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003002 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003003
3004 // 64-76 are various 4-byte special-purpose registers:
3005 // 64: mq
3006 // 65: lr
3007 // 66: ctr
3008 // 67: ap
3009 // 68-75 cr0-7
3010 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003011 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003012
3013 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003014 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003015
3016 // 109: vrsave
3017 // 110: vscr
3018 // 111: spe_acc
3019 // 112: spefscr
3020 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003021 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003022
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003023 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003024}
3025
Roman Divackyd966e722012-05-09 18:22:46 +00003026// PowerPC-64
3027
3028namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003029/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3030class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003031public:
3032 enum ABIKind {
3033 ELFv1 = 0,
3034 ELFv2
3035 };
3036
3037private:
3038 static const unsigned GPRBits = 64;
3039 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003040
3041public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003042 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3043 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003044
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003045 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003046 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003047 bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3048 uint64_t &Members) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003049
3050 ABIArgInfo classifyReturnType(QualType RetTy) const;
3051 ABIArgInfo classifyArgumentType(QualType Ty) const;
3052
Bill Schmidt84d37792012-10-12 19:26:17 +00003053 // TODO: We can add more logic to computeInfo to improve performance.
3054 // Example: For aggregate arguments that fit in a register, we could
3055 // use getDirectInReg (as is done below for structs containing a single
3056 // floating-point value) to avoid pushing them to memory on function
3057 // entry. This would require changing the logic in PPCISelLowering
3058 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003059 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003060 if (!getCXXABI().classifyReturnType(FI))
3061 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003062 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003063 // We rely on the default argument classification for the most part.
3064 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003065 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003066 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003067 if (T) {
3068 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003069 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3070 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003071 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003072 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003073 continue;
3074 }
3075 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003076 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003077 }
3078 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003079
Craig Topper4f12f102014-03-12 06:41:41 +00003080 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3081 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003082};
3083
3084class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3085public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003086 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3087 PPC64_SVR4_ABIInfo::ABIKind Kind)
3088 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003089
Craig Topper4f12f102014-03-12 06:41:41 +00003090 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003091 // This is recovered from gcc output.
3092 return 1; // r1 is the dedicated stack pointer
3093 }
3094
3095 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003096 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003097
3098 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3099 return 16; // Natural alignment for Altivec and VSX vectors.
3100 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003101};
3102
Roman Divackyd966e722012-05-09 18:22:46 +00003103class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3104public:
3105 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3106
Craig Topper4f12f102014-03-12 06:41:41 +00003107 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003108 // This is recovered from gcc output.
3109 return 1; // r1 is the dedicated stack pointer
3110 }
3111
3112 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003113 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003114
3115 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3116 return 16; // Natural alignment for Altivec vectors.
3117 }
Roman Divackyd966e722012-05-09 18:22:46 +00003118};
3119
3120}
3121
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003122// Return true if the ABI requires Ty to be passed sign- or zero-
3123// extended to 64 bits.
3124bool
3125PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3126 // Treat an enum type as its underlying type.
3127 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3128 Ty = EnumTy->getDecl()->getIntegerType();
3129
3130 // Promotable integer types are required to be promoted by the ABI.
3131 if (Ty->isPromotableIntegerType())
3132 return true;
3133
3134 // In addition to the usual promotable integer types, we also need to
3135 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3136 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3137 switch (BT->getKind()) {
3138 case BuiltinType::Int:
3139 case BuiltinType::UInt:
3140 return true;
3141 default:
3142 break;
3143 }
3144
3145 return false;
3146}
3147
Ulrich Weigand581badc2014-07-10 17:20:07 +00003148/// isAlignedParamType - Determine whether a type requires 16-byte
3149/// alignment in the parameter area.
3150bool
3151PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3152 // Complex types are passed just like their elements.
3153 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3154 Ty = CTy->getElementType();
3155
3156 // Only vector types of size 16 bytes need alignment (larger types are
3157 // passed via reference, smaller types are not aligned).
3158 if (Ty->isVectorType())
3159 return getContext().getTypeSize(Ty) == 128;
3160
3161 // For single-element float/vector structs, we consider the whole type
3162 // to have the same alignment requirements as its single element.
3163 const Type *AlignAsType = nullptr;
3164 const Type *EltType = isSingleElementStruct(Ty, getContext());
3165 if (EltType) {
3166 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3167 if ((EltType->isVectorType() &&
3168 getContext().getTypeSize(EltType) == 128) ||
3169 (BT && BT->isFloatingPoint()))
3170 AlignAsType = EltType;
3171 }
3172
Ulrich Weigandb7122372014-07-21 00:48:09 +00003173 // Likewise for ELFv2 homogeneous aggregates.
3174 const Type *Base = nullptr;
3175 uint64_t Members = 0;
3176 if (!AlignAsType && Kind == ELFv2 &&
3177 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3178 AlignAsType = Base;
3179
Ulrich Weigand581badc2014-07-10 17:20:07 +00003180 // With special case aggregates, only vector base types need alignment.
3181 if (AlignAsType)
3182 return AlignAsType->isVectorType();
3183
3184 // Otherwise, we only need alignment for any aggregate type that
3185 // has an alignment requirement of >= 16 bytes.
3186 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3187 return true;
3188
3189 return false;
3190}
3191
Ulrich Weigandb7122372014-07-21 00:48:09 +00003192/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3193/// aggregate. Base is set to the base element type, and Members is set
3194/// to the number of base elements.
3195bool
3196PPC64_SVR4_ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3197 uint64_t &Members) const {
3198 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3199 uint64_t NElements = AT->getSize().getZExtValue();
3200 if (NElements == 0)
3201 return false;
3202 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3203 return false;
3204 Members *= NElements;
3205 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3206 const RecordDecl *RD = RT->getDecl();
3207 if (RD->hasFlexibleArrayMember())
3208 return false;
3209
3210 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003211
3212 // If this is a C++ record, check the bases first.
3213 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3214 for (const auto &I : CXXRD->bases()) {
3215 // Ignore empty records.
3216 if (isEmptyRecord(getContext(), I.getType(), true))
3217 continue;
3218
3219 uint64_t FldMembers;
3220 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3221 return false;
3222
3223 Members += FldMembers;
3224 }
3225 }
3226
Ulrich Weigandb7122372014-07-21 00:48:09 +00003227 for (const auto *FD : RD->fields()) {
3228 // Ignore (non-zero arrays of) empty records.
3229 QualType FT = FD->getType();
3230 while (const ConstantArrayType *AT =
3231 getContext().getAsConstantArrayType(FT)) {
3232 if (AT->getSize().getZExtValue() == 0)
3233 return false;
3234 FT = AT->getElementType();
3235 }
3236 if (isEmptyRecord(getContext(), FT, true))
3237 continue;
3238
3239 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3240 if (getContext().getLangOpts().CPlusPlus &&
3241 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3242 continue;
3243
3244 uint64_t FldMembers;
3245 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3246 return false;
3247
3248 Members = (RD->isUnion() ?
3249 std::max(Members, FldMembers) : Members + FldMembers);
3250 }
3251
3252 if (!Base)
3253 return false;
3254
3255 // Ensure there is no padding.
3256 if (getContext().getTypeSize(Base) * Members !=
3257 getContext().getTypeSize(Ty))
3258 return false;
3259 } else {
3260 Members = 1;
3261 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3262 Members = 2;
3263 Ty = CT->getElementType();
3264 }
3265
3266 // Homogeneous aggregates for ELFv2 must have base types of float,
3267 // double, long double, or 128-bit vectors.
3268 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3269 if (BT->getKind() != BuiltinType::Float &&
3270 BT->getKind() != BuiltinType::Double &&
3271 BT->getKind() != BuiltinType::LongDouble)
3272 return false;
3273 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3274 if (getContext().getTypeSize(VT) != 128)
3275 return false;
3276 } else {
3277 return false;
3278 }
3279
3280 // The base type must be the same for all members. Types that
3281 // agree in both total size and mode (float vs. vector) are
3282 // treated as being equivalent here.
3283 const Type *TyPtr = Ty.getTypePtr();
3284 if (!Base)
3285 Base = TyPtr;
3286
3287 if (Base->isVectorType() != TyPtr->isVectorType() ||
3288 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3289 return false;
3290 }
3291
3292 // Vector types require one register, floating point types require one
3293 // or two registers depending on their size.
3294 uint32_t NumRegs = Base->isVectorType() ? 1 :
3295 (getContext().getTypeSize(Base) + 63) / 64;
3296
3297 // Homogeneous Aggregates may occupy at most 8 registers.
3298 return (Members > 0 && Members * NumRegs <= 8);
3299}
3300
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003301ABIArgInfo
3302PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00003303 if (Ty->isAnyComplexType())
3304 return ABIArgInfo::getDirect();
3305
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003306 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3307 // or via reference (larger than 16 bytes).
3308 if (Ty->isVectorType()) {
3309 uint64_t Size = getContext().getTypeSize(Ty);
3310 if (Size > 128)
3311 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3312 else if (Size < 128) {
3313 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3314 return ABIArgInfo::getDirect(CoerceTy);
3315 }
3316 }
3317
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003318 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003319 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003320 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003321
Ulrich Weigand581badc2014-07-10 17:20:07 +00003322 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3323 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003324
3325 // ELFv2 homogeneous aggregates are passed as array types.
3326 const Type *Base = nullptr;
3327 uint64_t Members = 0;
3328 if (Kind == ELFv2 &&
3329 isHomogeneousAggregate(Ty, Base, Members)) {
3330 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3331 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3332 return ABIArgInfo::getDirect(CoerceTy);
3333 }
3334
Ulrich Weigand601957f2014-07-21 00:56:36 +00003335 // If an aggregate may end up fully in registers, we do not
3336 // use the ByVal method, but pass the aggregate as array.
3337 // This is usually beneficial since we avoid forcing the
3338 // back-end to store the argument to memory.
3339 uint64_t Bits = getContext().getTypeSize(Ty);
3340 if (Bits > 0 && Bits <= 8 * GPRBits) {
3341 llvm::Type *CoerceTy;
3342
3343 // Types up to 8 bytes are passed as integer type (which will be
3344 // properly aligned in the argument save area doubleword).
3345 if (Bits <= GPRBits)
3346 CoerceTy = llvm::IntegerType::get(getVMContext(),
3347 llvm::RoundUpToAlignment(Bits, 8));
3348 // Larger types are passed as arrays, with the base type selected
3349 // according to the required alignment in the save area.
3350 else {
3351 uint64_t RegBits = ABIAlign * 8;
3352 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3353 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3354 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3355 }
3356
3357 return ABIArgInfo::getDirect(CoerceTy);
3358 }
3359
Ulrich Weigandb7122372014-07-21 00:48:09 +00003360 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003361 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3362 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003363 }
3364
3365 return (isPromotableTypeForABI(Ty) ?
3366 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3367}
3368
3369ABIArgInfo
3370PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3371 if (RetTy->isVoidType())
3372 return ABIArgInfo::getIgnore();
3373
Bill Schmidta3d121c2012-12-17 04:20:17 +00003374 if (RetTy->isAnyComplexType())
3375 return ABIArgInfo::getDirect();
3376
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003377 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3378 // or via reference (larger than 16 bytes).
3379 if (RetTy->isVectorType()) {
3380 uint64_t Size = getContext().getTypeSize(RetTy);
3381 if (Size > 128)
3382 return ABIArgInfo::getIndirect(0);
3383 else if (Size < 128) {
3384 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3385 return ABIArgInfo::getDirect(CoerceTy);
3386 }
3387 }
3388
Ulrich Weigandb7122372014-07-21 00:48:09 +00003389 if (isAggregateTypeForABI(RetTy)) {
3390 // ELFv2 homogeneous aggregates are returned as array types.
3391 const Type *Base = nullptr;
3392 uint64_t Members = 0;
3393 if (Kind == ELFv2 &&
3394 isHomogeneousAggregate(RetTy, Base, Members)) {
3395 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3396 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3397 return ABIArgInfo::getDirect(CoerceTy);
3398 }
3399
3400 // ELFv2 small aggregates are returned in up to two registers.
3401 uint64_t Bits = getContext().getTypeSize(RetTy);
3402 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3403 if (Bits == 0)
3404 return ABIArgInfo::getIgnore();
3405
3406 llvm::Type *CoerceTy;
3407 if (Bits > GPRBits) {
3408 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3409 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3410 } else
3411 CoerceTy = llvm::IntegerType::get(getVMContext(),
3412 llvm::RoundUpToAlignment(Bits, 8));
3413 return ABIArgInfo::getDirect(CoerceTy);
3414 }
3415
3416 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003417 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003418 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003419
3420 return (isPromotableTypeForABI(RetTy) ?
3421 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3422}
3423
Bill Schmidt25cb3492012-10-03 19:18:57 +00003424// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3425llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3426 QualType Ty,
3427 CodeGenFunction &CGF) const {
3428 llvm::Type *BP = CGF.Int8PtrTy;
3429 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3430
3431 CGBuilderTy &Builder = CGF.Builder;
3432 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3433 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3434
Ulrich Weigand581badc2014-07-10 17:20:07 +00003435 // Handle types that require 16-byte alignment in the parameter save area.
3436 if (isAlignedParamType(Ty)) {
3437 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3438 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3439 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3440 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3441 }
3442
Bill Schmidt924c4782013-01-14 17:45:36 +00003443 // Update the va_list pointer. The pointer should be bumped by the
3444 // size of the object. We can trust getTypeSize() except for a complex
3445 // type whose base type is smaller than a doubleword. For these, the
3446 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003447 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003448 QualType BaseTy;
3449 unsigned CplxBaseSize = 0;
3450
3451 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3452 BaseTy = CTy->getElementType();
3453 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3454 if (CplxBaseSize < 8)
3455 SizeInBytes = 16;
3456 }
3457
Bill Schmidt25cb3492012-10-03 19:18:57 +00003458 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3459 llvm::Value *NextAddr =
3460 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3461 "ap.next");
3462 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3463
Bill Schmidt924c4782013-01-14 17:45:36 +00003464 // If we have a complex type and the base type is smaller than 8 bytes,
3465 // the ABI calls for the real and imaginary parts to be right-adjusted
3466 // in separate doublewords. However, Clang expects us to produce a
3467 // pointer to a structure with the two parts packed tightly. So generate
3468 // loads of the real and imaginary parts relative to the va_list pointer,
3469 // and store them to a temporary structure.
3470 if (CplxBaseSize && CplxBaseSize < 8) {
3471 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3472 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003473 if (CGF.CGM.getDataLayout().isBigEndian()) {
3474 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3475 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3476 } else {
3477 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3478 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003479 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3480 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3481 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3482 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3483 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3484 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3485 "vacplx");
3486 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3487 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3488 Builder.CreateStore(Real, RealPtr, false);
3489 Builder.CreateStore(Imag, ImagPtr, false);
3490 return Ptr;
3491 }
3492
Bill Schmidt25cb3492012-10-03 19:18:57 +00003493 // If the argument is smaller than 8 bytes, it is right-adjusted in
3494 // its doubleword slot. Adjust the pointer to pick it up from the
3495 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003496 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003497 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3498 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3499 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3500 }
3501
3502 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3503 return Builder.CreateBitCast(Addr, PTy);
3504}
3505
3506static bool
3507PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3508 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003509 // This is calculated from the LLVM and GCC tables and verified
3510 // against gcc output. AFAIK all ABIs use the same encoding.
3511
3512 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3513
3514 llvm::IntegerType *i8 = CGF.Int8Ty;
3515 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3516 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3517 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3518
3519 // 0-31: r0-31, the 8-byte general-purpose registers
3520 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3521
3522 // 32-63: fp0-31, the 8-byte floating-point registers
3523 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3524
3525 // 64-76 are various 4-byte special-purpose registers:
3526 // 64: mq
3527 // 65: lr
3528 // 66: ctr
3529 // 67: ap
3530 // 68-75 cr0-7
3531 // 76: xer
3532 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3533
3534 // 77-108: v0-31, the 16-byte vector registers
3535 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3536
3537 // 109: vrsave
3538 // 110: vscr
3539 // 111: spe_acc
3540 // 112: spefscr
3541 // 113: sfp
3542 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3543
3544 return false;
3545}
John McCallea8d8bb2010-03-11 00:10:12 +00003546
Bill Schmidt25cb3492012-10-03 19:18:57 +00003547bool
3548PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3549 CodeGen::CodeGenFunction &CGF,
3550 llvm::Value *Address) const {
3551
3552 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3553}
3554
3555bool
3556PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3557 llvm::Value *Address) const {
3558
3559 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3560}
3561
Chris Lattner0cf24192010-06-28 20:05:43 +00003562//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003563// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003564//===----------------------------------------------------------------------===//
3565
3566namespace {
3567
Tim Northover573cbee2014-05-24 12:52:07 +00003568class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003569public:
3570 enum ABIKind {
3571 AAPCS = 0,
3572 DarwinPCS
3573 };
3574
3575private:
3576 ABIKind Kind;
3577
3578public:
Tim Northover573cbee2014-05-24 12:52:07 +00003579 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003580
3581private:
3582 ABIKind getABIKind() const { return Kind; }
3583 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3584
3585 ABIArgInfo classifyReturnType(QualType RetTy) const;
3586 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3587 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003588 bool &IsSmallAggr, bool IsNamedArg) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00003589 bool isIllegalVectorType(QualType Ty) const;
3590
3591 virtual void computeInfo(CGFunctionInfo &FI) const {
3592 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3593 // number of SIMD and Floating-point registers allocated so far.
3594 // If the argument is an HFA or an HVA and there are sufficient unallocated
3595 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3596 // and Floating-point Registers (with one register per member of the HFA or
3597 // HVA). Otherwise, the NSRN is set to 8.
3598 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003599
Tim Northovera2ee4332014-03-29 15:09:45 +00003600 // To correctly handle small aggregates, we need to keep track of the number
3601 // of GPRs allocated so far. If the small aggregate can't all fit into
3602 // registers, it will be on stack. We don't allow the aggregate to be
3603 // partially in registers.
3604 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003605
3606 // Find the number of named arguments. Variadic arguments get special
3607 // treatment with the Darwin ABI.
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003608 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Bob Wilson373af732014-04-21 01:23:39 +00003609
Reid Kleckner40ca9132014-05-13 22:05:45 +00003610 if (!getCXXABI().classifyReturnType(FI))
3611 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003612 unsigned ArgNo = 0;
Tim Northovera2ee4332014-03-29 15:09:45 +00003613 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003614 it != ie; ++it, ++ArgNo) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003615 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3616 bool IsHA = false, IsSmallAggr = false;
3617 const unsigned NumVFPs = 8;
3618 const unsigned NumGPRs = 8;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003619 bool IsNamedArg = ArgNo < NumRequiredArgs;
Tim Northovera2ee4332014-03-29 15:09:45 +00003620 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003621 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003622
3623 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3624 // as sequences of floats since they'll get "holes" inserted as
3625 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003626 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3627 getContext().getTypeAlign(it->type) < 64) {
3628 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3629 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003630
Tim Northover07f16242014-04-18 10:47:44 +00003631 llvm::Type *CoerceTy = llvm::ArrayType::get(
3632 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3633 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003634 }
3635
Tim Northovera2ee4332014-03-29 15:09:45 +00003636 // If we do not have enough VFP registers for the HA, any VFP registers
3637 // that are unallocated are marked as unavailable. To achieve this, we add
3638 // padding of (NumVFPs - PreAllocation) floats.
3639 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3640 llvm::Type *PaddingTy = llvm::ArrayType::get(
3641 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003642 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003643 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003644
Tim Northovera2ee4332014-03-29 15:09:45 +00003645 // If we do not have enough GPRs for the small aggregate, any GPR regs
3646 // that are unallocated are marked as unavailable.
3647 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3648 llvm::Type *PaddingTy = llvm::ArrayType::get(
3649 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3650 it->info =
3651 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3652 }
3653 }
3654 }
3655
3656 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3657 CodeGenFunction &CGF) const;
3658
3659 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3660 CodeGenFunction &CGF) const;
3661
3662 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3663 CodeGenFunction &CGF) const {
3664 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3665 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3666 }
3667};
3668
Tim Northover573cbee2014-05-24 12:52:07 +00003669class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003670public:
Tim Northover573cbee2014-05-24 12:52:07 +00003671 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3672 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003673
3674 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3675 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3676 }
3677
3678 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3679
3680 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3681};
3682}
3683
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003684static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
Tim Northovera2ee4332014-03-29 15:09:45 +00003685 ASTContext &Context,
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003686 bool isAArch64,
Craig Topper8a13c412014-05-21 05:09:00 +00003687 uint64_t *HAMembers = nullptr);
Tim Northovera2ee4332014-03-29 15:09:45 +00003688
Tim Northover573cbee2014-05-24 12:52:07 +00003689ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3690 unsigned &AllocatedVFP,
3691 bool &IsHA,
3692 unsigned &AllocatedGPR,
3693 bool &IsSmallAggr,
3694 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003695 // Handle illegal vector types here.
3696 if (isIllegalVectorType(Ty)) {
3697 uint64_t Size = getContext().getTypeSize(Ty);
3698 if (Size <= 32) {
3699 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3700 AllocatedGPR++;
3701 return ABIArgInfo::getDirect(ResType);
3702 }
3703 if (Size == 64) {
3704 llvm::Type *ResType =
3705 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3706 AllocatedVFP++;
3707 return ABIArgInfo::getDirect(ResType);
3708 }
3709 if (Size == 128) {
3710 llvm::Type *ResType =
3711 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3712 AllocatedVFP++;
3713 return ABIArgInfo::getDirect(ResType);
3714 }
3715 AllocatedGPR++;
3716 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3717 }
3718 if (Ty->isVectorType())
3719 // Size of a legal vector should be either 64 or 128.
3720 AllocatedVFP++;
3721 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3722 if (BT->getKind() == BuiltinType::Half ||
3723 BT->getKind() == BuiltinType::Float ||
3724 BT->getKind() == BuiltinType::Double ||
3725 BT->getKind() == BuiltinType::LongDouble)
3726 AllocatedVFP++;
3727 }
3728
3729 if (!isAggregateTypeForABI(Ty)) {
3730 // Treat an enum type as its underlying type.
3731 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3732 Ty = EnumTy->getDecl()->getIntegerType();
3733
3734 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003735 unsigned Alignment = getContext().getTypeAlign(Ty);
3736 if (!isDarwinPCS() && Alignment > 64)
3737 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3738
Tim Northovera2ee4332014-03-29 15:09:45 +00003739 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3740 AllocatedGPR += RegsNeeded;
3741 }
3742 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3743 ? ABIArgInfo::getExtend()
3744 : ABIArgInfo::getDirect());
3745 }
3746
3747 // Structures with either a non-trivial destructor or a non-trivial
3748 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003749 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003750 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003751 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3752 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003753 }
3754
3755 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3756 // elsewhere for GNU compatibility.
3757 if (isEmptyRecord(getContext(), Ty, true)) {
3758 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3759 return ABIArgInfo::getIgnore();
3760
3761 ++AllocatedGPR;
3762 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3763 }
3764
3765 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003766 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003767 uint64_t Members = 0;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003768 if (isARMHomogeneousAggregate(Ty, Base, getContext(), true, &Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003769 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003770 if (!IsNamedArg && isDarwinPCS()) {
3771 // With the Darwin ABI, variadic arguments are always passed on the stack
3772 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3773 uint64_t Size = getContext().getTypeSize(Ty);
3774 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3775 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3776 }
3777 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003778 return ABIArgInfo::getExpand();
3779 }
3780
3781 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3782 uint64_t Size = getContext().getTypeSize(Ty);
3783 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003784 unsigned Alignment = getContext().getTypeAlign(Ty);
3785 if (!isDarwinPCS() && Alignment > 64)
3786 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3787
Tim Northovera2ee4332014-03-29 15:09:45 +00003788 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3789 AllocatedGPR += Size / 64;
3790 IsSmallAggr = true;
3791 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3792 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003793 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003794 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3795 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3796 }
3797 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3798 }
3799
3800 AllocatedGPR++;
3801 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3802}
3803
Tim Northover573cbee2014-05-24 12:52:07 +00003804ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003805 if (RetTy->isVoidType())
3806 return ABIArgInfo::getIgnore();
3807
3808 // Large vector types should be returned via memory.
3809 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3810 return ABIArgInfo::getIndirect(0);
3811
3812 if (!isAggregateTypeForABI(RetTy)) {
3813 // Treat an enum type as its underlying type.
3814 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3815 RetTy = EnumTy->getDecl()->getIntegerType();
3816
Tim Northover4dab6982014-04-18 13:46:08 +00003817 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3818 ? ABIArgInfo::getExtend()
3819 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003820 }
3821
Tim Northovera2ee4332014-03-29 15:09:45 +00003822 if (isEmptyRecord(getContext(), RetTy, true))
3823 return ABIArgInfo::getIgnore();
3824
Craig Topper8a13c412014-05-21 05:09:00 +00003825 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003826 if (isARMHomogeneousAggregate(RetTy, Base, getContext(), true))
Tim Northovera2ee4332014-03-29 15:09:45 +00003827 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3828 return ABIArgInfo::getDirect();
3829
3830 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3831 uint64_t Size = getContext().getTypeSize(RetTy);
3832 if (Size <= 128) {
3833 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3834 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3835 }
3836
3837 return ABIArgInfo::getIndirect(0);
3838}
3839
Tim Northover573cbee2014-05-24 12:52:07 +00003840/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3841bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003842 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3843 // Check whether VT is legal.
3844 unsigned NumElements = VT->getNumElements();
3845 uint64_t Size = getContext().getTypeSize(VT);
3846 // NumElements should be power of 2 between 1 and 16.
3847 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3848 return true;
3849 return Size != 64 && (Size != 128 || NumElements == 1);
3850 }
3851 return false;
3852}
3853
3854static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3855 int AllocatedGPR, int AllocatedVFP,
3856 bool IsIndirect, CodeGenFunction &CGF) {
3857 // The AArch64 va_list type and handling is specified in the Procedure Call
3858 // Standard, section B.4:
3859 //
3860 // struct {
3861 // void *__stack;
3862 // void *__gr_top;
3863 // void *__vr_top;
3864 // int __gr_offs;
3865 // int __vr_offs;
3866 // };
3867
3868 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3869 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3870 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3871 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3872 auto &Ctx = CGF.getContext();
3873
Craig Topper8a13c412014-05-21 05:09:00 +00003874 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003875 int reg_top_index;
3876 int RegSize;
3877 if (AllocatedGPR) {
3878 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3879 // 3 is the field number of __gr_offs
3880 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3881 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3882 reg_top_index = 1; // field number for __gr_top
3883 RegSize = 8 * AllocatedGPR;
3884 } else {
3885 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3886 // 4 is the field number of __vr_offs.
3887 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3888 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3889 reg_top_index = 2; // field number for __vr_top
3890 RegSize = 16 * AllocatedVFP;
3891 }
3892
3893 //=======================================
3894 // Find out where argument was passed
3895 //=======================================
3896
3897 // If reg_offs >= 0 we're already using the stack for this type of
3898 // argument. We don't want to keep updating reg_offs (in case it overflows,
3899 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3900 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00003901 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003902 UsingStack = CGF.Builder.CreateICmpSGE(
3903 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3904
3905 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3906
3907 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00003908 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00003909 CGF.EmitBlock(MaybeRegBlock);
3910
3911 // Integer arguments may need to correct register alignment (for example a
3912 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3913 // align __gr_offs to calculate the potential address.
3914 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3915 int Align = Ctx.getTypeAlign(Ty) / 8;
3916
3917 reg_offs = CGF.Builder.CreateAdd(
3918 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3919 "align_regoffs");
3920 reg_offs = CGF.Builder.CreateAnd(
3921 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3922 "aligned_regoffs");
3923 }
3924
3925 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00003926 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003927 NewOffset = CGF.Builder.CreateAdd(
3928 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3929 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3930
3931 // Now we're in a position to decide whether this argument really was in
3932 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00003933 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003934 InRegs = CGF.Builder.CreateICmpSLE(
3935 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3936
3937 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3938
3939 //=======================================
3940 // Argument was in registers
3941 //=======================================
3942
3943 // Now we emit the code for if the argument was originally passed in
3944 // registers. First start the appropriate block:
3945 CGF.EmitBlock(InRegBlock);
3946
Craig Topper8a13c412014-05-21 05:09:00 +00003947 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003948 reg_top_p =
3949 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3950 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3951 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00003952 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003953 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3954
3955 if (IsIndirect) {
3956 // If it's been passed indirectly (actually a struct), whatever we find from
3957 // stored registers or on the stack will actually be a struct **.
3958 MemTy = llvm::PointerType::getUnqual(MemTy);
3959 }
3960
Craig Topper8a13c412014-05-21 05:09:00 +00003961 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003962 uint64_t NumMembers;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003963 bool IsHFA = isARMHomogeneousAggregate(Ty, Base, Ctx, true, &NumMembers);
James Molloy467be602014-05-07 14:45:55 +00003964 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003965 // Homogeneous aggregates passed in registers will have their elements split
3966 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3967 // qN+1, ...). We reload and store into a temporary local variable
3968 // contiguously.
3969 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3970 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3971 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3972 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3973 int Offset = 0;
3974
3975 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3976 Offset = 16 - Ctx.getTypeSize(Base) / 8;
3977 for (unsigned i = 0; i < NumMembers; ++i) {
3978 llvm::Value *BaseOffset =
3979 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3980 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3981 LoadAddr = CGF.Builder.CreateBitCast(
3982 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3983 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3984
3985 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3986 CGF.Builder.CreateStore(Elem, StoreAddr);
3987 }
3988
3989 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3990 } else {
3991 // Otherwise the object is contiguous in memory
3992 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00003993 if (CGF.CGM.getDataLayout().isBigEndian() &&
3994 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00003995 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3996 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3997 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3998
3999 BaseAddr = CGF.Builder.CreateAdd(
4000 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4001
4002 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4003 }
4004
4005 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4006 }
4007
4008 CGF.EmitBranch(ContBlock);
4009
4010 //=======================================
4011 // Argument was on the stack
4012 //=======================================
4013 CGF.EmitBlock(OnStackBlock);
4014
Craig Topper8a13c412014-05-21 05:09:00 +00004015 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004016 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4017 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4018
4019 // Again, stack arguments may need realigmnent. In this case both integer and
4020 // floating-point ones might be affected.
4021 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4022 int Align = Ctx.getTypeAlign(Ty) / 8;
4023
4024 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4025
4026 OnStackAddr = CGF.Builder.CreateAdd(
4027 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4028 "align_stack");
4029 OnStackAddr = CGF.Builder.CreateAnd(
4030 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4031 "align_stack");
4032
4033 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4034 }
4035
4036 uint64_t StackSize;
4037 if (IsIndirect)
4038 StackSize = 8;
4039 else
4040 StackSize = Ctx.getTypeSize(Ty) / 8;
4041
4042 // All stack slots are 8 bytes
4043 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4044
4045 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4046 llvm::Value *NewStack =
4047 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4048
4049 // Write the new value of __stack for the next call to va_arg
4050 CGF.Builder.CreateStore(NewStack, stack_p);
4051
4052 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4053 Ctx.getTypeSize(Ty) < 64) {
4054 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4055 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4056
4057 OnStackAddr = CGF.Builder.CreateAdd(
4058 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4059
4060 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4061 }
4062
4063 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4064
4065 CGF.EmitBranch(ContBlock);
4066
4067 //=======================================
4068 // Tidy up
4069 //=======================================
4070 CGF.EmitBlock(ContBlock);
4071
4072 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4073 ResAddr->addIncoming(RegAddr, InRegBlock);
4074 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4075
4076 if (IsIndirect)
4077 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4078
4079 return ResAddr;
4080}
4081
Tim Northover573cbee2014-05-24 12:52:07 +00004082llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004083 CodeGenFunction &CGF) const {
4084
4085 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4086 bool IsHA = false, IsSmallAggr = false;
Bob Wilson373af732014-04-21 01:23:39 +00004087 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4088 IsSmallAggr, false /*IsNamedArg*/);
Tim Northovera2ee4332014-03-29 15:09:45 +00004089
4090 return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
4091 AI.isIndirect(), CGF);
4092}
4093
Tim Northover573cbee2014-05-24 12:52:07 +00004094llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004095 CodeGenFunction &CGF) const {
4096 // We do not support va_arg for aggregates or illegal vector types.
4097 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4098 // other cases.
4099 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004100 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004101
4102 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4103 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4104
Craig Topper8a13c412014-05-21 05:09:00 +00004105 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004106 bool isHA = isARMHomogeneousAggregate(Ty, Base, getContext(), true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004107
4108 bool isIndirect = false;
4109 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4110 // be passed indirectly.
4111 if (Size > 16 && !isHA) {
4112 isIndirect = true;
4113 Size = 8;
4114 Align = 8;
4115 }
4116
4117 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4118 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4119
4120 CGBuilderTy &Builder = CGF.Builder;
4121 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4122 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4123
4124 if (isEmptyRecord(getContext(), Ty, true)) {
4125 // These are ignored for parameter passing purposes.
4126 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4127 return Builder.CreateBitCast(Addr, PTy);
4128 }
4129
4130 const uint64_t MinABIAlign = 8;
4131 if (Align > MinABIAlign) {
4132 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4133 Addr = Builder.CreateGEP(Addr, Offset);
4134 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4135 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4136 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4137 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4138 }
4139
4140 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4141 llvm::Value *NextAddr = Builder.CreateGEP(
4142 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4143 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4144
4145 if (isIndirect)
4146 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4147 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4148 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4149
4150 return AddrTyped;
4151}
4152
4153//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004154// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004155//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004156
4157namespace {
4158
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004159class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004160public:
4161 enum ABIKind {
4162 APCS = 0,
4163 AAPCS = 1,
4164 AAPCS_VFP
4165 };
4166
4167private:
4168 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004169 mutable int VFPRegs[16];
4170 const unsigned NumVFPs;
4171 const unsigned NumGPRs;
4172 mutable unsigned AllocatedGPRs;
4173 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004174
4175public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004176 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4177 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00004178 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004179 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004180 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004181
John McCall3480ef22011-08-30 01:42:09 +00004182 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004183 switch (getTarget().getTriple().getEnvironment()) {
4184 case llvm::Triple::Android:
4185 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004186 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004187 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004188 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004189 return true;
4190 default:
4191 return false;
4192 }
John McCall3480ef22011-08-30 01:42:09 +00004193 }
4194
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004195 bool isEABIHF() const {
4196 switch (getTarget().getTriple().getEnvironment()) {
4197 case llvm::Triple::EABIHF:
4198 case llvm::Triple::GNUEABIHF:
4199 return true;
4200 default:
4201 return false;
4202 }
4203 }
4204
Daniel Dunbar020daa92009-09-12 01:00:39 +00004205 ABIKind getABIKind() const { return Kind; }
4206
Tim Northovera484bc02013-10-01 14:34:25 +00004207private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004208 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004209 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004210 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004211 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004212
Craig Topper4f12f102014-03-12 06:41:41 +00004213 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004214
Craig Topper4f12f102014-03-12 06:41:41 +00004215 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4216 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004217
4218 llvm::CallingConv::ID getLLVMDefaultCC() const;
4219 llvm::CallingConv::ID getABIDefaultCC() const;
4220 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004221
4222 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4223 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4224 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004225};
4226
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004227class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4228public:
Chris Lattner2b037972010-07-29 02:01:43 +00004229 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4230 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004231
John McCall3480ef22011-08-30 01:42:09 +00004232 const ARMABIInfo &getABIInfo() const {
4233 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4234 }
4235
Craig Topper4f12f102014-03-12 06:41:41 +00004236 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004237 return 13;
4238 }
Roman Divackyc1617352011-05-18 19:36:54 +00004239
Craig Topper4f12f102014-03-12 06:41:41 +00004240 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004241 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4242 }
4243
Roman Divackyc1617352011-05-18 19:36:54 +00004244 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004245 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004246 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004247
4248 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004249 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004250 return false;
4251 }
John McCall3480ef22011-08-30 01:42:09 +00004252
Craig Topper4f12f102014-03-12 06:41:41 +00004253 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004254 if (getABIInfo().isEABI()) return 88;
4255 return TargetCodeGenInfo::getSizeOfUnwindException();
4256 }
Tim Northovera484bc02013-10-01 14:34:25 +00004257
4258 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004259 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004260 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4261 if (!FD)
4262 return;
4263
4264 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4265 if (!Attr)
4266 return;
4267
4268 const char *Kind;
4269 switch (Attr->getInterrupt()) {
4270 case ARMInterruptAttr::Generic: Kind = ""; break;
4271 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4272 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4273 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4274 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4275 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4276 }
4277
4278 llvm::Function *Fn = cast<llvm::Function>(GV);
4279
4280 Fn->addFnAttr("interrupt", Kind);
4281
4282 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4283 return;
4284
4285 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4286 // however this is not necessarily true on taking any interrupt. Instruct
4287 // the backend to perform a realignment as part of the function prologue.
4288 llvm::AttrBuilder B;
4289 B.addStackAlignmentAttr(8);
4290 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4291 llvm::AttributeSet::get(CGM.getLLVMContext(),
4292 llvm::AttributeSet::FunctionIndex,
4293 B));
4294 }
4295
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004296};
4297
Daniel Dunbard59655c2009-09-12 00:59:49 +00004298}
4299
Chris Lattner22326a12010-07-29 02:31:05 +00004300void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004301 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004302 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004303 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4304 // VFP registers of the appropriate type unallocated then the argument is
4305 // allocated to the lowest-numbered sequence of such registers.
4306 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4307 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004308 resetAllocatedRegs();
4309
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004310 const bool isAAPCS_VFP =
4311 getABIKind() == ARMABIInfo::AAPCS_VFP && !FI.isVariadic();
4312
Reid Kleckner40ca9132014-05-13 22:05:45 +00004313 if (getCXXABI().classifyReturnType(FI)) {
4314 if (FI.getReturnInfo().isIndirect())
4315 markAllocatedGPRs(1, 1);
4316 } else {
4317 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4318 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004319 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004320 unsigned PreAllocationVFPs = AllocatedVFPs;
4321 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004322 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004323 // 6.1.2.3 There is one VFP co-processor register class using registers
4324 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004325 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004326
4327 // If we have allocated some arguments onto the stack (due to running
4328 // out of VFP registers), we cannot split an argument between GPRs and
4329 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004330 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004331 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4332 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004333 // We do not have to do this if the argument is being passed ByVal, as the
4334 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004335 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004336 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4337 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4338 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004339 llvm::Type *PaddingTy = llvm::ArrayType::get(
4340 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004341 if (I.info.canHaveCoerceToType()) {
4342 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004343 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004344 } else {
4345 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004346 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004347 }
Manman Ren2a523d82012-10-30 23:21:41 +00004348 }
4349 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004350
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004351 // Always honor user-specified calling convention.
4352 if (FI.getCallingConvention() != llvm::CallingConv::C)
4353 return;
4354
John McCall882987f2013-02-28 19:01:20 +00004355 llvm::CallingConv::ID cc = getRuntimeCC();
4356 if (cc != llvm::CallingConv::C)
4357 FI.setEffectiveCallingConvention(cc);
4358}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004359
John McCall882987f2013-02-28 19:01:20 +00004360/// Return the default calling convention that LLVM will use.
4361llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4362 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004363 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004364 return llvm::CallingConv::ARM_AAPCS_VFP;
4365 else if (isEABI())
4366 return llvm::CallingConv::ARM_AAPCS;
4367 else
4368 return llvm::CallingConv::ARM_APCS;
4369}
4370
4371/// Return the calling convention that our ABI would like us to use
4372/// as the C calling convention.
4373llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004374 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004375 case APCS: return llvm::CallingConv::ARM_APCS;
4376 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4377 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004378 }
John McCall882987f2013-02-28 19:01:20 +00004379 llvm_unreachable("bad ABI kind");
4380}
4381
4382void ARMABIInfo::setRuntimeCC() {
4383 assert(getRuntimeCC() == llvm::CallingConv::C);
4384
4385 // Don't muddy up the IR with a ton of explicit annotations if
4386 // they'd just match what LLVM will infer from the triple.
4387 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4388 if (abiCC != getLLVMDefaultCC())
4389 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004390}
4391
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004392/// isARMHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
Bob Wilsone826a2a2011-08-03 05:58:22 +00004393/// aggregate. If HAMembers is non-null, the number of base elements
4394/// contained in the type is returned through it; this is used for the
4395/// recursive calls that check aggregate component types.
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004396static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
4397 ASTContext &Context, bool isAArch64,
4398 uint64_t *HAMembers) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004399 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00004400 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004401 if (!isARMHomogeneousAggregate(AT->getElementType(), Base, Context, isAArch64, &Members))
Bob Wilsone826a2a2011-08-03 05:58:22 +00004402 return false;
4403 Members *= AT->getSize().getZExtValue();
4404 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4405 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004406 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00004407 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004408
Bob Wilsone826a2a2011-08-03 05:58:22 +00004409 Members = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004410 for (const auto *FD : RD->fields()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00004411 uint64_t FldMembers;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004412 if (!isARMHomogeneousAggregate(FD->getType(), Base, Context, isAArch64, &FldMembers))
Bob Wilsone826a2a2011-08-03 05:58:22 +00004413 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004414
4415 Members = (RD->isUnion() ?
4416 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004417 }
4418 } else {
4419 Members = 1;
4420 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4421 Members = 2;
4422 Ty = CT->getElementType();
4423 }
4424
4425 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004426 // double, or 64-bit or 128-bit vectors. "long double" has the same machine
4427 // type as double, so it is also allowed as a base type.
4428 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4429 // point type or a short-vector type. This is the same as the 32-bit ABI,
4430 // but with the difference that any floating-point type is allowed,
4431 // including __fp16.
Bob Wilsone826a2a2011-08-03 05:58:22 +00004432 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004433 if (isAArch64) {
4434 if (!BT->isFloatingPoint())
4435 return false;
4436 } else {
4437 if (BT->getKind() != BuiltinType::Float &&
4438 BT->getKind() != BuiltinType::Double &&
4439 BT->getKind() != BuiltinType::LongDouble)
4440 return false;
4441 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004442 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4443 unsigned VecSize = Context.getTypeSize(VT);
4444 if (VecSize != 64 && VecSize != 128)
4445 return false;
4446 } else {
4447 return false;
4448 }
4449
4450 // The base type must be the same for all members. Vector types of the
4451 // same total size are treated as being equivalent here.
4452 const Type *TyPtr = Ty.getTypePtr();
4453 if (!Base)
4454 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00004455
4456 if (Base != TyPtr) {
4457 // Homogeneous aggregates are defined as containing members with the
4458 // same machine type. There are two cases in which two members have
4459 // different TypePtrs but the same machine type:
4460
4461 // 1) Vectors of the same length, regardless of the type and number
4462 // of their members.
4463 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
4464 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4465
4466 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
4467 // machine type. This is not the case for the 64-bit AAPCS.
4468 const bool SameSizeDoubles =
4469 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
4470 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4471 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4472 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4473 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4474
4475 if (!SameLengthVectors && !SameSizeDoubles)
4476 return false;
4477 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004478 }
4479
4480 // Homogeneous Aggregates can have at most 4 members of the base type.
4481 if (HAMembers)
4482 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004483
4484 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004485}
4486
Manman Renb505d332012-10-31 19:02:26 +00004487/// markAllocatedVFPs - update VFPRegs according to the alignment and
4488/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004489void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4490 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004491 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004492 if (AllocatedVFPs >= 16) {
4493 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4494 // the stack.
4495 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004496 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004497 }
Manman Renb505d332012-10-31 19:02:26 +00004498 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4499 // VFP registers of the appropriate type unallocated then the argument is
4500 // allocated to the lowest-numbered sequence of such registers.
4501 for (unsigned I = 0; I < 16; I += Alignment) {
4502 bool FoundSlot = true;
4503 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4504 if (J >= 16 || VFPRegs[J]) {
4505 FoundSlot = false;
4506 break;
4507 }
4508 if (FoundSlot) {
4509 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4510 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004511 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004512 return;
4513 }
4514 }
4515 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4516 // unallocated are marked as unavailable.
4517 for (unsigned I = 0; I < 16; I++)
4518 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004519 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004520}
4521
Oliver Stannard405bded2014-02-11 09:25:50 +00004522/// Update AllocatedGPRs to record the number of general purpose registers
4523/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4524/// this represents arguments being stored on the stack.
4525void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004526 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004527 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4528
4529 if (Alignment == 2 && AllocatedGPRs & 0x1)
4530 AllocatedGPRs += 1;
4531
4532 AllocatedGPRs += NumRequired;
4533}
4534
4535void ARMABIInfo::resetAllocatedRegs(void) const {
4536 AllocatedGPRs = 0;
4537 AllocatedVFPs = 0;
4538 for (unsigned i = 0; i < NumVFPs; ++i)
4539 VFPRegs[i] = 0;
4540}
4541
James Molloy6f244b62014-05-09 16:21:39 +00004542ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004543 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004544 // We update number of allocated VFPs according to
4545 // 6.1.2.1 The following argument types are VFP CPRCs:
4546 // A single-precision floating-point type (including promoted
4547 // half-precision types); A double-precision floating-point type;
4548 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4549 // with a Base Type of a single- or double-precision floating-point type,
4550 // 64-bit containerized vectors or 128-bit containerized vectors with one
4551 // to four Elements.
4552
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004553 const bool isAAPCS_VFP =
4554 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4555
Manman Renfef9e312012-10-16 19:18:39 +00004556 // Handle illegal vector types here.
4557 if (isIllegalVectorType(Ty)) {
4558 uint64_t Size = getContext().getTypeSize(Ty);
4559 if (Size <= 32) {
4560 llvm::Type *ResType =
4561 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004562 markAllocatedGPRs(1, 1);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004563 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004564 }
4565 if (Size == 64) {
4566 llvm::Type *ResType = llvm::VectorType::get(
4567 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004568 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4569 markAllocatedGPRs(2, 2);
4570 } else {
4571 markAllocatedVFPs(2, 2);
4572 IsCPRC = true;
4573 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004574 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004575 }
4576 if (Size == 128) {
4577 llvm::Type *ResType = llvm::VectorType::get(
4578 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004579 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4580 markAllocatedGPRs(2, 4);
4581 } else {
4582 markAllocatedVFPs(4, 4);
4583 IsCPRC = true;
4584 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004585 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004586 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004587 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004588 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4589 }
Manman Renb505d332012-10-31 19:02:26 +00004590 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004591 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4592 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4593 uint64_t Size = getContext().getTypeSize(VT);
4594 // Size of a legal vector should be power of 2 and above 64.
4595 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4596 IsCPRC = true;
4597 }
Manman Ren2a523d82012-10-30 23:21:41 +00004598 }
Manman Renb505d332012-10-31 19:02:26 +00004599 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004600 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4601 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4602 if (BT->getKind() == BuiltinType::Half ||
4603 BT->getKind() == BuiltinType::Float) {
4604 markAllocatedVFPs(1, 1);
4605 IsCPRC = true;
4606 }
4607 if (BT->getKind() == BuiltinType::Double ||
4608 BT->getKind() == BuiltinType::LongDouble) {
4609 markAllocatedVFPs(2, 2);
4610 IsCPRC = true;
4611 }
4612 }
Manman Ren2a523d82012-10-30 23:21:41 +00004613 }
Manman Renfef9e312012-10-16 19:18:39 +00004614
John McCalla1dee5302010-08-22 10:59:02 +00004615 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004616 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004617 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004618 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004619 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004620
Oliver Stannard405bded2014-02-11 09:25:50 +00004621 unsigned Size = getContext().getTypeSize(Ty);
4622 if (!IsCPRC)
4623 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004624 return (Ty->isPromotableIntegerType()
4625 ? ABIArgInfo::getExtend()
4626 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004627 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004628
Oliver Stannard405bded2014-02-11 09:25:50 +00004629 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4630 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004631 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004632 }
Tim Northover1060eae2013-06-21 22:49:34 +00004633
Daniel Dunbar09d33622009-09-14 21:54:03 +00004634 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004635 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004636 return ABIArgInfo::getIgnore();
4637
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004638 if (isAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004639 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4640 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004641 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004642 uint64_t Members = 0;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004643 if (isARMHomogeneousAggregate(Ty, Base, getContext(), false, &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004644 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004645 // Base can be a floating-point or a vector.
4646 if (Base->isVectorType()) {
4647 // ElementSize is in number of floats.
4648 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004649 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004650 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004651 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004652 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004653 else {
4654 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4655 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004656 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004657 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004658 IsCPRC = true;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004659 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004660 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004661 }
4662
Manman Ren6c30e132012-08-13 21:23:55 +00004663 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004664 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4665 // most 8-byte. We realign the indirect argument if type alignment is bigger
4666 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004667 uint64_t ABIAlign = 4;
4668 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4669 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4670 getABIKind() == ARMABIInfo::AAPCS)
4671 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004672 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004673 // Update Allocated GPRs. Since this is only used when the size of the
4674 // argument is greater than 64 bytes, this will always use up any available
4675 // registers (of which there are 4). We also don't care about getting the
4676 // alignment right, because general-purpose registers cannot be back-filled.
4677 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004678 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004679 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004680 }
4681
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004682 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004683 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004684 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004685 // FIXME: Try to match the types of the arguments more accurately where
4686 // we can.
4687 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004688 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4689 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004690 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004691 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004692 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4693 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004694 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004695 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004696
Chris Lattnera5f58b02011-07-09 17:41:47 +00004697 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004698 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004699 return ABIArgInfo::getDirect(STy, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004700}
4701
Chris Lattner458b2aa2010-07-29 02:16:43 +00004702static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004703 llvm::LLVMContext &VMContext) {
4704 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4705 // is called integer-like if its size is less than or equal to one word, and
4706 // the offset of each of its addressable sub-fields is zero.
4707
4708 uint64_t Size = Context.getTypeSize(Ty);
4709
4710 // Check that the type fits in a word.
4711 if (Size > 32)
4712 return false;
4713
4714 // FIXME: Handle vector types!
4715 if (Ty->isVectorType())
4716 return false;
4717
Daniel Dunbard53bac72009-09-14 02:20:34 +00004718 // Float types are never treated as "integer like".
4719 if (Ty->isRealFloatingType())
4720 return false;
4721
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004722 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004723 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004724 return true;
4725
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004726 // Small complex integer types are "integer like".
4727 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4728 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004729
4730 // Single element and zero sized arrays should be allowed, by the definition
4731 // above, but they are not.
4732
4733 // Otherwise, it must be a record type.
4734 const RecordType *RT = Ty->getAs<RecordType>();
4735 if (!RT) return false;
4736
4737 // Ignore records with flexible arrays.
4738 const RecordDecl *RD = RT->getDecl();
4739 if (RD->hasFlexibleArrayMember())
4740 return false;
4741
4742 // Check that all sub-fields are at offset 0, and are themselves "integer
4743 // like".
4744 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4745
4746 bool HadField = false;
4747 unsigned idx = 0;
4748 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4749 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004750 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004751
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004752 // Bit-fields are not addressable, we only need to verify they are "integer
4753 // like". We still have to disallow a subsequent non-bitfield, for example:
4754 // struct { int : 0; int x }
4755 // is non-integer like according to gcc.
4756 if (FD->isBitField()) {
4757 if (!RD->isUnion())
4758 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004759
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004760 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4761 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004762
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004763 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004764 }
4765
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004766 // Check if this field is at offset 0.
4767 if (Layout.getFieldOffset(idx) != 0)
4768 return false;
4769
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004770 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4771 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004772
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004773 // Only allow at most one field in a structure. This doesn't match the
4774 // wording above, but follows gcc in situations with a field following an
4775 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004776 if (!RD->isUnion()) {
4777 if (HadField)
4778 return false;
4779
4780 HadField = true;
4781 }
4782 }
4783
4784 return true;
4785}
4786
Oliver Stannard405bded2014-02-11 09:25:50 +00004787ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4788 bool isVariadic) const {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004789 const bool isAAPCS_VFP =
4790 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4791
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004792 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004793 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004794
Daniel Dunbar19964db2010-09-23 01:54:32 +00004795 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004796 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4797 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004798 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004799 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004800
John McCalla1dee5302010-08-22 10:59:02 +00004801 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004802 // Treat an enum type as its underlying type.
4803 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4804 RetTy = EnumTy->getDecl()->getIntegerType();
4805
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004806 return (RetTy->isPromotableIntegerType()
4807 ? ABIArgInfo::getExtend()
4808 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004809 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004810
4811 // Are we following APCS?
4812 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004813 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004814 return ABIArgInfo::getIgnore();
4815
Daniel Dunbareedf1512010-02-01 23:31:19 +00004816 // Complex types are all returned as packed integers.
4817 //
4818 // FIXME: Consider using 2 x vector types if the back end handles them
4819 // correctly.
4820 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004821 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4822 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004823
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004824 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004825 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004826 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004827 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004828 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004829 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004830 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004831 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4832 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004833 }
4834
4835 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004836 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004837 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004838 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004839
4840 // Otherwise this is an AAPCS variant.
4841
Chris Lattner458b2aa2010-07-29 02:16:43 +00004842 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004843 return ABIArgInfo::getIgnore();
4844
Bob Wilson1d9269a2011-11-02 04:51:36 +00004845 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004846 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Craig Topper8a13c412014-05-21 05:09:00 +00004847 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004848 if (isARMHomogeneousAggregate(RetTy, Base, getContext(), false)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004849 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004850 // Homogeneous Aggregates are returned directly.
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004851 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004852 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004853 }
4854
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004855 // Aggregates <= 4 bytes are returned in r0; other aggregates
4856 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004857 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004858 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004859 if (getDataLayout().isBigEndian())
4860 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004861 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4862 nullptr, !isAAPCS_VFP);
Christian Pirkerc3d32172014-07-03 09:28:12 +00004863
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004864 // Return in the smallest viable integer type.
4865 if (Size <= 8)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004866 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()), 0,
4867 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004868 if (Size <= 16)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004869 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()), 0,
4870 nullptr, !isAAPCS_VFP);
4871 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4872 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004873 }
4874
Oliver Stannard405bded2014-02-11 09:25:50 +00004875 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004876 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004877}
4878
Manman Renfef9e312012-10-16 19:18:39 +00004879/// isIllegalVector - check whether Ty is an illegal vector type.
4880bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4881 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4882 // Check whether VT is legal.
4883 unsigned NumElements = VT->getNumElements();
4884 uint64_t Size = getContext().getTypeSize(VT);
4885 // NumElements should be power of 2.
4886 if ((NumElements & (NumElements - 1)) != 0)
4887 return true;
4888 // Size should be greater than 32 bits.
4889 return Size <= 32;
4890 }
4891 return false;
4892}
4893
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004894llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004895 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004896 llvm::Type *BP = CGF.Int8PtrTy;
4897 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004898
4899 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004900 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004901 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004902
Tim Northover1711cc92013-06-21 23:05:33 +00004903 if (isEmptyRecord(getContext(), Ty, true)) {
4904 // These are ignored for parameter passing purposes.
4905 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4906 return Builder.CreateBitCast(Addr, PTy);
4907 }
4908
Manman Rencca54d02012-10-16 19:01:37 +00004909 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004910 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004911 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004912
4913 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4914 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004915 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4916 getABIKind() == ARMABIInfo::AAPCS)
4917 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4918 else
4919 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004920 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4921 if (isIllegalVectorType(Ty) && Size > 16) {
4922 IsIndirect = true;
4923 Size = 4;
4924 TyAlign = 4;
4925 }
Manman Rencca54d02012-10-16 19:01:37 +00004926
4927 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004928 if (TyAlign > 4) {
4929 assert((TyAlign & (TyAlign - 1)) == 0 &&
4930 "Alignment is not power of 2!");
4931 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4932 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4933 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004934 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004935 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004936
4937 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004938 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004939 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004940 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004941 "ap.next");
4942 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4943
Manman Renfef9e312012-10-16 19:18:39 +00004944 if (IsIndirect)
4945 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004946 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004947 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4948 // may not be correctly aligned for the vector type. We create an aligned
4949 // temporary space and copy the content over from ap.cur to the temporary
4950 // space. This is necessary if the natural alignment of the type is greater
4951 // than the ABI alignment.
4952 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4953 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4954 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4955 "var.align");
4956 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4957 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4958 Builder.CreateMemCpy(Dst, Src,
4959 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4960 TyAlign, false);
4961 Addr = AlignedTemp; //The content is in aligned location.
4962 }
4963 llvm::Type *PTy =
4964 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4965 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4966
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004967 return AddrTyped;
4968}
4969
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004970namespace {
4971
Derek Schuffa2020962012-10-16 22:30:41 +00004972class NaClARMABIInfo : public ABIInfo {
4973 public:
4974 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4975 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004976 void computeInfo(CGFunctionInfo &FI) const override;
4977 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4978 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00004979 private:
4980 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4981 ARMABIInfo NInfo; // Used for everything else.
4982};
4983
4984class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4985 public:
4986 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4987 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4988};
4989
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004990}
4991
Derek Schuffa2020962012-10-16 22:30:41 +00004992void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4993 if (FI.getASTCallingConvention() == CC_PnaclCall)
4994 PInfo.computeInfo(FI);
4995 else
4996 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4997}
4998
4999llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5000 CodeGenFunction &CGF) const {
5001 // Always use the native convention; calling pnacl-style varargs functions
5002 // is unsupported.
5003 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
5004}
5005
Chris Lattner0cf24192010-06-28 20:05:43 +00005006//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005007// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005008//===----------------------------------------------------------------------===//
5009
5010namespace {
5011
Justin Holewinski83e96682012-05-24 17:43:12 +00005012class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005013public:
Justin Holewinski36837432013-03-30 14:38:24 +00005014 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005015
5016 ABIArgInfo classifyReturnType(QualType RetTy) const;
5017 ABIArgInfo classifyArgumentType(QualType Ty) const;
5018
Craig Topper4f12f102014-03-12 06:41:41 +00005019 void computeInfo(CGFunctionInfo &FI) const override;
5020 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5021 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005022};
5023
Justin Holewinski83e96682012-05-24 17:43:12 +00005024class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005025public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005026 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5027 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005028
5029 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5030 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005031private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005032 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5033 // resulting MDNode to the nvvm.annotations MDNode.
5034 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005035};
5036
Justin Holewinski83e96682012-05-24 17:43:12 +00005037ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005038 if (RetTy->isVoidType())
5039 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005040
5041 // note: this is different from default ABI
5042 if (!RetTy->isScalarType())
5043 return ABIArgInfo::getDirect();
5044
5045 // Treat an enum type as its underlying type.
5046 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5047 RetTy = EnumTy->getDecl()->getIntegerType();
5048
5049 return (RetTy->isPromotableIntegerType() ?
5050 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005051}
5052
Justin Holewinski83e96682012-05-24 17:43:12 +00005053ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005054 // Treat an enum type as its underlying type.
5055 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5056 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005057
Eli Bendersky95338a02014-10-29 13:43:21 +00005058 // Return aggregates type as indirect by value
5059 if (isAggregateTypeForABI(Ty))
5060 return ABIArgInfo::getIndirect(0, /* byval */ true);
5061
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005062 return (Ty->isPromotableIntegerType() ?
5063 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005064}
5065
Justin Holewinski83e96682012-05-24 17:43:12 +00005066void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005067 if (!getCXXABI().classifyReturnType(FI))
5068 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005069 for (auto &I : FI.arguments())
5070 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005071
5072 // Always honor user-specified calling convention.
5073 if (FI.getCallingConvention() != llvm::CallingConv::C)
5074 return;
5075
John McCall882987f2013-02-28 19:01:20 +00005076 FI.setEffectiveCallingConvention(getRuntimeCC());
5077}
5078
Justin Holewinski83e96682012-05-24 17:43:12 +00005079llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5080 CodeGenFunction &CFG) const {
5081 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005082}
5083
Justin Holewinski83e96682012-05-24 17:43:12 +00005084void NVPTXTargetCodeGenInfo::
5085SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5086 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005087 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5088 if (!FD) return;
5089
5090 llvm::Function *F = cast<llvm::Function>(GV);
5091
5092 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005093 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005094 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005095 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005096 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005097 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005098 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5099 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005100 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005101 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005102 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005103 }
Justin Holewinski38031972011-10-05 17:58:44 +00005104
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005105 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005106 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005107 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005108 // __global__ functions cannot be called from the device, we do not
5109 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005110 if (FD->hasAttr<CUDAGlobalAttr>()) {
5111 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5112 addNVVMMetadata(F, "kernel", 1);
5113 }
5114 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5115 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5116 addNVVMMetadata(F, "maxntidx",
5117 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5118 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5119 // zero value from getMinBlocks either means it was not specified in
5120 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5121 // don't have to add a PTX directive.
5122 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5123 if (MinCTASM > 0) {
5124 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5125 addNVVMMetadata(F, "minctasm", MinCTASM);
5126 }
5127 }
Justin Holewinski38031972011-10-05 17:58:44 +00005128 }
5129}
5130
Eli Benderskye06a2c42014-04-15 16:57:05 +00005131void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5132 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005133 llvm::Module *M = F->getParent();
5134 llvm::LLVMContext &Ctx = M->getContext();
5135
5136 // Get "nvvm.annotations" metadata node
5137 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5138
Eli Benderskye1627b42014-04-15 17:19:26 +00005139 llvm::Value *MDVals[] = {
5140 F, llvm::MDString::get(Ctx, Name),
5141 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00005142 // Append metadata to nvvm.annotations
5143 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5144}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005145}
5146
5147//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005148// SystemZ ABI Implementation
5149//===----------------------------------------------------------------------===//
5150
5151namespace {
5152
5153class SystemZABIInfo : public ABIInfo {
5154public:
5155 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5156
5157 bool isPromotableIntegerType(QualType Ty) const;
5158 bool isCompoundType(QualType Ty) const;
5159 bool isFPArgumentType(QualType Ty) const;
5160
5161 ABIArgInfo classifyReturnType(QualType RetTy) const;
5162 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5163
Craig Topper4f12f102014-03-12 06:41:41 +00005164 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005165 if (!getCXXABI().classifyReturnType(FI))
5166 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005167 for (auto &I : FI.arguments())
5168 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005169 }
5170
Craig Topper4f12f102014-03-12 06:41:41 +00005171 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5172 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005173};
5174
5175class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5176public:
5177 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5178 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5179};
5180
5181}
5182
5183bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5184 // Treat an enum type as its underlying type.
5185 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5186 Ty = EnumTy->getDecl()->getIntegerType();
5187
5188 // Promotable integer types are required to be promoted by the ABI.
5189 if (Ty->isPromotableIntegerType())
5190 return true;
5191
5192 // 32-bit values must also be promoted.
5193 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5194 switch (BT->getKind()) {
5195 case BuiltinType::Int:
5196 case BuiltinType::UInt:
5197 return true;
5198 default:
5199 return false;
5200 }
5201 return false;
5202}
5203
5204bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5205 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5206}
5207
5208bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5209 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5210 switch (BT->getKind()) {
5211 case BuiltinType::Float:
5212 case BuiltinType::Double:
5213 return true;
5214 default:
5215 return false;
5216 }
5217
5218 if (const RecordType *RT = Ty->getAsStructureType()) {
5219 const RecordDecl *RD = RT->getDecl();
5220 bool Found = false;
5221
5222 // If this is a C++ record, check the bases first.
5223 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005224 for (const auto &I : CXXRD->bases()) {
5225 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005226
5227 // Empty bases don't affect things either way.
5228 if (isEmptyRecord(getContext(), Base, true))
5229 continue;
5230
5231 if (Found)
5232 return false;
5233 Found = isFPArgumentType(Base);
5234 if (!Found)
5235 return false;
5236 }
5237
5238 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005239 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005240 // Empty bitfields don't affect things either way.
5241 // Unlike isSingleElementStruct(), empty structure and array fields
5242 // do count. So do anonymous bitfields that aren't zero-sized.
5243 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5244 return true;
5245
5246 // Unlike isSingleElementStruct(), arrays do not count.
5247 // Nested isFPArgumentType structures still do though.
5248 if (Found)
5249 return false;
5250 Found = isFPArgumentType(FD->getType());
5251 if (!Found)
5252 return false;
5253 }
5254
5255 // Unlike isSingleElementStruct(), trailing padding is allowed.
5256 // An 8-byte aligned struct s { float f; } is passed as a double.
5257 return Found;
5258 }
5259
5260 return false;
5261}
5262
5263llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5264 CodeGenFunction &CGF) const {
5265 // Assume that va_list type is correct; should be pointer to LLVM type:
5266 // struct {
5267 // i64 __gpr;
5268 // i64 __fpr;
5269 // i8 *__overflow_arg_area;
5270 // i8 *__reg_save_area;
5271 // };
5272
5273 // Every argument occupies 8 bytes and is passed by preference in either
5274 // GPRs or FPRs.
5275 Ty = CGF.getContext().getCanonicalType(Ty);
5276 ABIArgInfo AI = classifyArgumentType(Ty);
5277 bool InFPRs = isFPArgumentType(Ty);
5278
5279 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5280 bool IsIndirect = AI.isIndirect();
5281 unsigned UnpaddedBitSize;
5282 if (IsIndirect) {
5283 APTy = llvm::PointerType::getUnqual(APTy);
5284 UnpaddedBitSize = 64;
5285 } else
5286 UnpaddedBitSize = getContext().getTypeSize(Ty);
5287 unsigned PaddedBitSize = 64;
5288 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5289
5290 unsigned PaddedSize = PaddedBitSize / 8;
5291 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5292
5293 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5294 if (InFPRs) {
5295 MaxRegs = 4; // Maximum of 4 FPR arguments
5296 RegCountField = 1; // __fpr
5297 RegSaveIndex = 16; // save offset for f0
5298 RegPadding = 0; // floats are passed in the high bits of an FPR
5299 } else {
5300 MaxRegs = 5; // Maximum of 5 GPR arguments
5301 RegCountField = 0; // __gpr
5302 RegSaveIndex = 2; // save offset for r2
5303 RegPadding = Padding; // values are passed in the low bits of a GPR
5304 }
5305
5306 llvm::Value *RegCountPtr =
5307 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5308 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5309 llvm::Type *IndexTy = RegCount->getType();
5310 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5311 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005312 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005313
5314 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5315 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5316 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5317 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5318
5319 // Emit code to load the value if it was passed in registers.
5320 CGF.EmitBlock(InRegBlock);
5321
5322 // Work out the address of an argument register.
5323 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5324 llvm::Value *ScaledRegCount =
5325 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5326 llvm::Value *RegBase =
5327 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5328 llvm::Value *RegOffset =
5329 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5330 llvm::Value *RegSaveAreaPtr =
5331 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5332 llvm::Value *RegSaveArea =
5333 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5334 llvm::Value *RawRegAddr =
5335 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5336 llvm::Value *RegAddr =
5337 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5338
5339 // Update the register count
5340 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5341 llvm::Value *NewRegCount =
5342 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5343 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5344 CGF.EmitBranch(ContBlock);
5345
5346 // Emit code to load the value if it was passed in memory.
5347 CGF.EmitBlock(InMemBlock);
5348
5349 // Work out the address of a stack argument.
5350 llvm::Value *OverflowArgAreaPtr =
5351 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5352 llvm::Value *OverflowArgArea =
5353 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5354 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5355 llvm::Value *RawMemAddr =
5356 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5357 llvm::Value *MemAddr =
5358 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5359
5360 // Update overflow_arg_area_ptr pointer
5361 llvm::Value *NewOverflowArgArea =
5362 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5363 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5364 CGF.EmitBranch(ContBlock);
5365
5366 // Return the appropriate result.
5367 CGF.EmitBlock(ContBlock);
5368 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5369 ResAddr->addIncoming(RegAddr, InRegBlock);
5370 ResAddr->addIncoming(MemAddr, InMemBlock);
5371
5372 if (IsIndirect)
5373 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5374
5375 return ResAddr;
5376}
5377
Ulrich Weigand47445072013-05-06 16:26:41 +00005378ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5379 if (RetTy->isVoidType())
5380 return ABIArgInfo::getIgnore();
5381 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5382 return ABIArgInfo::getIndirect(0);
5383 return (isPromotableIntegerType(RetTy) ?
5384 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5385}
5386
5387ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5388 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005389 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005390 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5391
5392 // Integers and enums are extended to full register width.
5393 if (isPromotableIntegerType(Ty))
5394 return ABIArgInfo::getExtend();
5395
5396 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5397 uint64_t Size = getContext().getTypeSize(Ty);
5398 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005399 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005400
5401 // Handle small structures.
5402 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5403 // Structures with flexible arrays have variable length, so really
5404 // fail the size test above.
5405 const RecordDecl *RD = RT->getDecl();
5406 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005407 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005408
5409 // The structure is passed as an unextended integer, a float, or a double.
5410 llvm::Type *PassTy;
5411 if (isFPArgumentType(Ty)) {
5412 assert(Size == 32 || Size == 64);
5413 if (Size == 32)
5414 PassTy = llvm::Type::getFloatTy(getVMContext());
5415 else
5416 PassTy = llvm::Type::getDoubleTy(getVMContext());
5417 } else
5418 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5419 return ABIArgInfo::getDirect(PassTy);
5420 }
5421
5422 // Non-structure compounds are passed indirectly.
5423 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005424 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005425
Craig Topper8a13c412014-05-21 05:09:00 +00005426 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005427}
5428
5429//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005430// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005431//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005432
5433namespace {
5434
5435class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5436public:
Chris Lattner2b037972010-07-29 02:01:43 +00005437 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5438 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005439 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005440 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005441};
5442
5443}
5444
5445void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5446 llvm::GlobalValue *GV,
5447 CodeGen::CodeGenModule &M) const {
5448 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5449 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5450 // Handle 'interrupt' attribute:
5451 llvm::Function *F = cast<llvm::Function>(GV);
5452
5453 // Step 1: Set ISR calling convention.
5454 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5455
5456 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005457 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005458
5459 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005460 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005461 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5462 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005463 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005464 }
5465}
5466
Chris Lattner0cf24192010-06-28 20:05:43 +00005467//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005468// MIPS ABI Implementation. This works for both little-endian and
5469// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005470//===----------------------------------------------------------------------===//
5471
John McCall943fae92010-05-27 06:19:26 +00005472namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005473class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005474 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005475 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5476 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005477 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005478 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005479 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005480 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005481public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005482 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005483 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005484 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005485
5486 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005487 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005488 void computeInfo(CGFunctionInfo &FI) const override;
5489 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5490 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005491};
5492
John McCall943fae92010-05-27 06:19:26 +00005493class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005494 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005495public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005496 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5497 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005498 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005499
Craig Topper4f12f102014-03-12 06:41:41 +00005500 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005501 return 29;
5502 }
5503
Reed Kotler373feca2013-01-16 17:10:28 +00005504 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005505 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005506 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5507 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005508 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005509 if (FD->hasAttr<Mips16Attr>()) {
5510 Fn->addFnAttr("mips16");
5511 }
5512 else if (FD->hasAttr<NoMips16Attr>()) {
5513 Fn->addFnAttr("nomips16");
5514 }
Reed Kotler373feca2013-01-16 17:10:28 +00005515 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005516
John McCall943fae92010-05-27 06:19:26 +00005517 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005518 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005519
Craig Topper4f12f102014-03-12 06:41:41 +00005520 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005521 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005522 }
John McCall943fae92010-05-27 06:19:26 +00005523};
5524}
5525
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005526void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005527 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005528 llvm::IntegerType *IntTy =
5529 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005530
5531 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5532 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5533 ArgList.push_back(IntTy);
5534
5535 // If necessary, add one more integer type to ArgList.
5536 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5537
5538 if (R)
5539 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005540}
5541
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005542// In N32/64, an aligned double precision floating point field is passed in
5543// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005544llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005545 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5546
5547 if (IsO32) {
5548 CoerceToIntArgs(TySize, ArgList);
5549 return llvm::StructType::get(getVMContext(), ArgList);
5550 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005551
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005552 if (Ty->isComplexType())
5553 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005554
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005555 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005556
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005557 // Unions/vectors are passed in integer registers.
5558 if (!RT || !RT->isStructureOrClassType()) {
5559 CoerceToIntArgs(TySize, ArgList);
5560 return llvm::StructType::get(getVMContext(), ArgList);
5561 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005562
5563 const RecordDecl *RD = RT->getDecl();
5564 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005565 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005566
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005567 uint64_t LastOffset = 0;
5568 unsigned idx = 0;
5569 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5570
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005571 // Iterate over fields in the struct/class and check if there are any aligned
5572 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005573 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5574 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005575 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005576 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5577
5578 if (!BT || BT->getKind() != BuiltinType::Double)
5579 continue;
5580
5581 uint64_t Offset = Layout.getFieldOffset(idx);
5582 if (Offset % 64) // Ignore doubles that are not aligned.
5583 continue;
5584
5585 // Add ((Offset - LastOffset) / 64) args of type i64.
5586 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5587 ArgList.push_back(I64);
5588
5589 // Add double type.
5590 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5591 LastOffset = Offset + 64;
5592 }
5593
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005594 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5595 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005596
5597 return llvm::StructType::get(getVMContext(), ArgList);
5598}
5599
Akira Hatanakaddd66342013-10-29 18:41:15 +00005600llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5601 uint64_t Offset) const {
5602 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005603 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005604
Akira Hatanakaddd66342013-10-29 18:41:15 +00005605 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005606}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005607
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005608ABIArgInfo
5609MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005610 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005611 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005612 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005613
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005614 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5615 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005616 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5617 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005618
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005619 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005620 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005621 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005622 return ABIArgInfo::getIgnore();
5623
Mark Lacey3825e832013-10-06 01:33:34 +00005624 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005625 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005626 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005627 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005628
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005629 // If we have reached here, aggregates are passed directly by coercing to
5630 // another structure type. Padding is inserted if the offset of the
5631 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005632 ABIArgInfo ArgInfo =
5633 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5634 getPaddingType(OrigOffset, CurrOffset));
5635 ArgInfo.setInReg(true);
5636 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005637 }
5638
5639 // Treat an enum type as its underlying type.
5640 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5641 Ty = EnumTy->getDecl()->getIntegerType();
5642
Daniel Sanders5b445b32014-10-24 14:42:42 +00005643 // All integral types are promoted to the GPR width.
5644 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005645 return ABIArgInfo::getExtend();
5646
Akira Hatanakaddd66342013-10-29 18:41:15 +00005647 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005648 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005649}
5650
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005651llvm::Type*
5652MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005653 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005654 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005655
Akira Hatanakab6f74432012-02-09 18:49:26 +00005656 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005657 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005658 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5659 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005660
Akira Hatanakab6f74432012-02-09 18:49:26 +00005661 // N32/64 returns struct/classes in floating point registers if the
5662 // following conditions are met:
5663 // 1. The size of the struct/class is no larger than 128-bit.
5664 // 2. The struct/class has one or two fields all of which are floating
5665 // point types.
5666 // 3. The offset of the first field is zero (this follows what gcc does).
5667 //
5668 // Any other composite results are returned in integer registers.
5669 //
5670 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5671 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5672 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005673 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005674
Akira Hatanakab6f74432012-02-09 18:49:26 +00005675 if (!BT || !BT->isFloatingPoint())
5676 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005677
David Blaikie2d7c57e2012-04-30 02:36:29 +00005678 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005679 }
5680
5681 if (b == e)
5682 return llvm::StructType::get(getVMContext(), RTList,
5683 RD->hasAttr<PackedAttr>());
5684
5685 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005686 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005687 }
5688
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005689 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005690 return llvm::StructType::get(getVMContext(), RTList);
5691}
5692
Akira Hatanakab579fe52011-06-02 00:09:17 +00005693ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005694 uint64_t Size = getContext().getTypeSize(RetTy);
5695
Daniel Sandersed39f582014-09-04 13:28:14 +00005696 if (RetTy->isVoidType())
5697 return ABIArgInfo::getIgnore();
5698
5699 // O32 doesn't treat zero-sized structs differently from other structs.
5700 // However, N32/N64 ignores zero sized return values.
5701 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005702 return ABIArgInfo::getIgnore();
5703
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005704 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005705 if (Size <= 128) {
5706 if (RetTy->isAnyComplexType())
5707 return ABIArgInfo::getDirect();
5708
Daniel Sanderse5018b62014-09-04 15:05:39 +00005709 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005710 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005711 if (!IsO32 ||
5712 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5713 ABIArgInfo ArgInfo =
5714 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5715 ArgInfo.setInReg(true);
5716 return ArgInfo;
5717 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005718 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005719
5720 return ABIArgInfo::getIndirect(0);
5721 }
5722
5723 // Treat an enum type as its underlying type.
5724 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5725 RetTy = EnumTy->getDecl()->getIntegerType();
5726
5727 return (RetTy->isPromotableIntegerType() ?
5728 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5729}
5730
5731void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005732 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005733 if (!getCXXABI().classifyReturnType(FI))
5734 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005735
5736 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005737 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005738
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005739 for (auto &I : FI.arguments())
5740 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005741}
5742
5743llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5744 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005745 llvm::Type *BP = CGF.Int8PtrTy;
5746 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5747
5748 CGBuilderTy &Builder = CGF.Builder;
5749 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5750 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005751 int64_t TypeAlign =
5752 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005753 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5754 llvm::Value *AddrTyped;
5755 unsigned PtrWidth = getTarget().getPointerWidth(0);
5756 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5757
5758 if (TypeAlign > MinABIStackAlignInBytes) {
5759 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5760 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5761 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5762 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5763 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5764 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5765 }
5766 else
5767 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5768
5769 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5770 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5771 uint64_t Offset =
5772 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5773 llvm::Value *NextAddr =
5774 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5775 "ap.next");
5776 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5777
5778 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005779}
5780
John McCall943fae92010-05-27 06:19:26 +00005781bool
5782MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5783 llvm::Value *Address) const {
5784 // This information comes from gcc's implementation, which seems to
5785 // as canonical as it gets.
5786
John McCall943fae92010-05-27 06:19:26 +00005787 // Everything on MIPS is 4 bytes. Double-precision FP registers
5788 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005789 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005790
5791 // 0-31 are the general purpose registers, $0 - $31.
5792 // 32-63 are the floating-point registers, $f0 - $f31.
5793 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5794 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005795 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005796
5797 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5798 // They are one bit wide and ignored here.
5799
5800 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5801 // (coprocessor 1 is the FP unit)
5802 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5803 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5804 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005805 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005806 return false;
5807}
5808
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005809//===----------------------------------------------------------------------===//
5810// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5811// Currently subclassed only to implement custom OpenCL C function attribute
5812// handling.
5813//===----------------------------------------------------------------------===//
5814
5815namespace {
5816
5817class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5818public:
5819 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5820 : DefaultTargetCodeGenInfo(CGT) {}
5821
Craig Topper4f12f102014-03-12 06:41:41 +00005822 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5823 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005824};
5825
5826void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5827 llvm::GlobalValue *GV,
5828 CodeGen::CodeGenModule &M) const {
5829 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5830 if (!FD) return;
5831
5832 llvm::Function *F = cast<llvm::Function>(GV);
5833
David Blaikiebbafb8a2012-03-11 07:00:24 +00005834 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005835 if (FD->hasAttr<OpenCLKernelAttr>()) {
5836 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005837 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005838 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5839 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005840 // Convert the reqd_work_group_size() attributes to metadata.
5841 llvm::LLVMContext &Context = F->getContext();
5842 llvm::NamedMDNode *OpenCLMetadata =
5843 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5844
5845 SmallVector<llvm::Value*, 5> Operands;
5846 Operands.push_back(F);
5847
Chris Lattnerece04092012-02-07 00:39:47 +00005848 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005849 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005850 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005851 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005852 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005853 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005854
5855 // Add a boolean constant operand for "required" (true) or "hint" (false)
5856 // for implementing the work_group_size_hint attr later. Currently
5857 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005858 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005859 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5860 }
5861 }
5862 }
5863}
5864
5865}
John McCall943fae92010-05-27 06:19:26 +00005866
Tony Linthicum76329bf2011-12-12 21:14:55 +00005867//===----------------------------------------------------------------------===//
5868// Hexagon ABI Implementation
5869//===----------------------------------------------------------------------===//
5870
5871namespace {
5872
5873class HexagonABIInfo : public ABIInfo {
5874
5875
5876public:
5877 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5878
5879private:
5880
5881 ABIArgInfo classifyReturnType(QualType RetTy) const;
5882 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5883
Craig Topper4f12f102014-03-12 06:41:41 +00005884 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005885
Craig Topper4f12f102014-03-12 06:41:41 +00005886 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5887 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005888};
5889
5890class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5891public:
5892 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5893 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5894
Craig Topper4f12f102014-03-12 06:41:41 +00005895 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005896 return 29;
5897 }
5898};
5899
5900}
5901
5902void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005903 if (!getCXXABI().classifyReturnType(FI))
5904 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005905 for (auto &I : FI.arguments())
5906 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005907}
5908
5909ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5910 if (!isAggregateTypeForABI(Ty)) {
5911 // Treat an enum type as its underlying type.
5912 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5913 Ty = EnumTy->getDecl()->getIntegerType();
5914
5915 return (Ty->isPromotableIntegerType() ?
5916 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5917 }
5918
5919 // Ignore empty records.
5920 if (isEmptyRecord(getContext(), Ty, true))
5921 return ABIArgInfo::getIgnore();
5922
Mark Lacey3825e832013-10-06 01:33:34 +00005923 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005924 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005925
5926 uint64_t Size = getContext().getTypeSize(Ty);
5927 if (Size > 64)
5928 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5929 // Pass in the smallest viable integer type.
5930 else if (Size > 32)
5931 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5932 else if (Size > 16)
5933 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5934 else if (Size > 8)
5935 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5936 else
5937 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5938}
5939
5940ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5941 if (RetTy->isVoidType())
5942 return ABIArgInfo::getIgnore();
5943
5944 // Large vector types should be returned via memory.
5945 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5946 return ABIArgInfo::getIndirect(0);
5947
5948 if (!isAggregateTypeForABI(RetTy)) {
5949 // Treat an enum type as its underlying type.
5950 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5951 RetTy = EnumTy->getDecl()->getIntegerType();
5952
5953 return (RetTy->isPromotableIntegerType() ?
5954 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5955 }
5956
Tony Linthicum76329bf2011-12-12 21:14:55 +00005957 if (isEmptyRecord(getContext(), RetTy, true))
5958 return ABIArgInfo::getIgnore();
5959
5960 // Aggregates <= 8 bytes are returned in r0; other aggregates
5961 // are returned indirectly.
5962 uint64_t Size = getContext().getTypeSize(RetTy);
5963 if (Size <= 64) {
5964 // Return in the smallest viable integer type.
5965 if (Size <= 8)
5966 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5967 if (Size <= 16)
5968 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5969 if (Size <= 32)
5970 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5971 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5972 }
5973
5974 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5975}
5976
5977llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005978 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005979 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005980 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005981
5982 CGBuilderTy &Builder = CGF.Builder;
5983 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5984 "ap");
5985 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5986 llvm::Type *PTy =
5987 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5988 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5989
5990 uint64_t Offset =
5991 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5992 llvm::Value *NextAddr =
5993 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5994 "ap.next");
5995 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5996
5997 return AddrTyped;
5998}
5999
6000
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006001//===----------------------------------------------------------------------===//
6002// SPARC v9 ABI Implementation.
6003// Based on the SPARC Compliance Definition version 2.4.1.
6004//
6005// Function arguments a mapped to a nominal "parameter array" and promoted to
6006// registers depending on their type. Each argument occupies 8 or 16 bytes in
6007// the array, structs larger than 16 bytes are passed indirectly.
6008//
6009// One case requires special care:
6010//
6011// struct mixed {
6012// int i;
6013// float f;
6014// };
6015//
6016// When a struct mixed is passed by value, it only occupies 8 bytes in the
6017// parameter array, but the int is passed in an integer register, and the float
6018// is passed in a floating point register. This is represented as two arguments
6019// with the LLVM IR inreg attribute:
6020//
6021// declare void f(i32 inreg %i, float inreg %f)
6022//
6023// The code generator will only allocate 4 bytes from the parameter array for
6024// the inreg arguments. All other arguments are allocated a multiple of 8
6025// bytes.
6026//
6027namespace {
6028class SparcV9ABIInfo : public ABIInfo {
6029public:
6030 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6031
6032private:
6033 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006034 void computeInfo(CGFunctionInfo &FI) const override;
6035 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6036 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006037
6038 // Coercion type builder for structs passed in registers. The coercion type
6039 // serves two purposes:
6040 //
6041 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6042 // in registers.
6043 // 2. Expose aligned floating point elements as first-level elements, so the
6044 // code generator knows to pass them in floating point registers.
6045 //
6046 // We also compute the InReg flag which indicates that the struct contains
6047 // aligned 32-bit floats.
6048 //
6049 struct CoerceBuilder {
6050 llvm::LLVMContext &Context;
6051 const llvm::DataLayout &DL;
6052 SmallVector<llvm::Type*, 8> Elems;
6053 uint64_t Size;
6054 bool InReg;
6055
6056 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6057 : Context(c), DL(dl), Size(0), InReg(false) {}
6058
6059 // Pad Elems with integers until Size is ToSize.
6060 void pad(uint64_t ToSize) {
6061 assert(ToSize >= Size && "Cannot remove elements");
6062 if (ToSize == Size)
6063 return;
6064
6065 // Finish the current 64-bit word.
6066 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6067 if (Aligned > Size && Aligned <= ToSize) {
6068 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6069 Size = Aligned;
6070 }
6071
6072 // Add whole 64-bit words.
6073 while (Size + 64 <= ToSize) {
6074 Elems.push_back(llvm::Type::getInt64Ty(Context));
6075 Size += 64;
6076 }
6077
6078 // Final in-word padding.
6079 if (Size < ToSize) {
6080 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6081 Size = ToSize;
6082 }
6083 }
6084
6085 // Add a floating point element at Offset.
6086 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6087 // Unaligned floats are treated as integers.
6088 if (Offset % Bits)
6089 return;
6090 // The InReg flag is only required if there are any floats < 64 bits.
6091 if (Bits < 64)
6092 InReg = true;
6093 pad(Offset);
6094 Elems.push_back(Ty);
6095 Size = Offset + Bits;
6096 }
6097
6098 // Add a struct type to the coercion type, starting at Offset (in bits).
6099 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6100 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6101 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6102 llvm::Type *ElemTy = StrTy->getElementType(i);
6103 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6104 switch (ElemTy->getTypeID()) {
6105 case llvm::Type::StructTyID:
6106 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6107 break;
6108 case llvm::Type::FloatTyID:
6109 addFloat(ElemOffset, ElemTy, 32);
6110 break;
6111 case llvm::Type::DoubleTyID:
6112 addFloat(ElemOffset, ElemTy, 64);
6113 break;
6114 case llvm::Type::FP128TyID:
6115 addFloat(ElemOffset, ElemTy, 128);
6116 break;
6117 case llvm::Type::PointerTyID:
6118 if (ElemOffset % 64 == 0) {
6119 pad(ElemOffset);
6120 Elems.push_back(ElemTy);
6121 Size += 64;
6122 }
6123 break;
6124 default:
6125 break;
6126 }
6127 }
6128 }
6129
6130 // Check if Ty is a usable substitute for the coercion type.
6131 bool isUsableType(llvm::StructType *Ty) const {
6132 if (Ty->getNumElements() != Elems.size())
6133 return false;
6134 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6135 if (Elems[i] != Ty->getElementType(i))
6136 return false;
6137 return true;
6138 }
6139
6140 // Get the coercion type as a literal struct type.
6141 llvm::Type *getType() const {
6142 if (Elems.size() == 1)
6143 return Elems.front();
6144 else
6145 return llvm::StructType::get(Context, Elems);
6146 }
6147 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006148};
6149} // end anonymous namespace
6150
6151ABIArgInfo
6152SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6153 if (Ty->isVoidType())
6154 return ABIArgInfo::getIgnore();
6155
6156 uint64_t Size = getContext().getTypeSize(Ty);
6157
6158 // Anything too big to fit in registers is passed with an explicit indirect
6159 // pointer / sret pointer.
6160 if (Size > SizeLimit)
6161 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6162
6163 // Treat an enum type as its underlying type.
6164 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6165 Ty = EnumTy->getDecl()->getIntegerType();
6166
6167 // Integer types smaller than a register are extended.
6168 if (Size < 64 && Ty->isIntegerType())
6169 return ABIArgInfo::getExtend();
6170
6171 // Other non-aggregates go in registers.
6172 if (!isAggregateTypeForABI(Ty))
6173 return ABIArgInfo::getDirect();
6174
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006175 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6176 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6177 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6178 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6179
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006180 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006181 // Build a coercion type from the LLVM struct type.
6182 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6183 if (!StrTy)
6184 return ABIArgInfo::getDirect();
6185
6186 CoerceBuilder CB(getVMContext(), getDataLayout());
6187 CB.addStruct(0, StrTy);
6188 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6189
6190 // Try to use the original type for coercion.
6191 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6192
6193 if (CB.InReg)
6194 return ABIArgInfo::getDirectInReg(CoerceTy);
6195 else
6196 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006197}
6198
6199llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6200 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006201 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6202 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6203 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6204 AI.setCoerceToType(ArgTy);
6205
6206 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6207 CGBuilderTy &Builder = CGF.Builder;
6208 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6209 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6210 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6211 llvm::Value *ArgAddr;
6212 unsigned Stride;
6213
6214 switch (AI.getKind()) {
6215 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006216 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006217 llvm_unreachable("Unsupported ABI kind for va_arg");
6218
6219 case ABIArgInfo::Extend:
6220 Stride = 8;
6221 ArgAddr = Builder
6222 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6223 "extend");
6224 break;
6225
6226 case ABIArgInfo::Direct:
6227 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6228 ArgAddr = Addr;
6229 break;
6230
6231 case ABIArgInfo::Indirect:
6232 Stride = 8;
6233 ArgAddr = Builder.CreateBitCast(Addr,
6234 llvm::PointerType::getUnqual(ArgPtrTy),
6235 "indirect");
6236 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6237 break;
6238
6239 case ABIArgInfo::Ignore:
6240 return llvm::UndefValue::get(ArgPtrTy);
6241 }
6242
6243 // Update VAList.
6244 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6245 Builder.CreateStore(Addr, VAListAddrAsBPP);
6246
6247 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006248}
6249
6250void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6251 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006252 for (auto &I : FI.arguments())
6253 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006254}
6255
6256namespace {
6257class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6258public:
6259 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6260 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006261
Craig Topper4f12f102014-03-12 06:41:41 +00006262 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006263 return 14;
6264 }
6265
6266 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006267 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006268};
6269} // end anonymous namespace
6270
Roman Divackyf02c9942014-02-24 18:46:27 +00006271bool
6272SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6273 llvm::Value *Address) const {
6274 // This is calculated from the LLVM and GCC tables and verified
6275 // against gcc output. AFAIK all ABIs use the same encoding.
6276
6277 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6278
6279 llvm::IntegerType *i8 = CGF.Int8Ty;
6280 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6281 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6282
6283 // 0-31: the 8-byte general-purpose registers
6284 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6285
6286 // 32-63: f0-31, the 4-byte floating-point registers
6287 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6288
6289 // Y = 64
6290 // PSR = 65
6291 // WIM = 66
6292 // TBR = 67
6293 // PC = 68
6294 // NPC = 69
6295 // FSR = 70
6296 // CSR = 71
6297 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6298
6299 // 72-87: d0-15, the 8-byte floating-point registers
6300 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6301
6302 return false;
6303}
6304
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006305
Robert Lytton0e076492013-08-13 09:43:10 +00006306//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006307// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006308//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006309
Robert Lytton0e076492013-08-13 09:43:10 +00006310namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006311
6312/// A SmallStringEnc instance is used to build up the TypeString by passing
6313/// it by reference between functions that append to it.
6314typedef llvm::SmallString<128> SmallStringEnc;
6315
6316/// TypeStringCache caches the meta encodings of Types.
6317///
6318/// The reason for caching TypeStrings is two fold:
6319/// 1. To cache a type's encoding for later uses;
6320/// 2. As a means to break recursive member type inclusion.
6321///
6322/// A cache Entry can have a Status of:
6323/// NonRecursive: The type encoding is not recursive;
6324/// Recursive: The type encoding is recursive;
6325/// Incomplete: An incomplete TypeString;
6326/// IncompleteUsed: An incomplete TypeString that has been used in a
6327/// Recursive type encoding.
6328///
6329/// A NonRecursive entry will have all of its sub-members expanded as fully
6330/// as possible. Whilst it may contain types which are recursive, the type
6331/// itself is not recursive and thus its encoding may be safely used whenever
6332/// the type is encountered.
6333///
6334/// A Recursive entry will have all of its sub-members expanded as fully as
6335/// possible. The type itself is recursive and it may contain other types which
6336/// are recursive. The Recursive encoding must not be used during the expansion
6337/// of a recursive type's recursive branch. For simplicity the code uses
6338/// IncompleteCount to reject all usage of Recursive encodings for member types.
6339///
6340/// An Incomplete entry is always a RecordType and only encodes its
6341/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6342/// are placed into the cache during type expansion as a means to identify and
6343/// handle recursive inclusion of types as sub-members. If there is recursion
6344/// the entry becomes IncompleteUsed.
6345///
6346/// During the expansion of a RecordType's members:
6347///
6348/// If the cache contains a NonRecursive encoding for the member type, the
6349/// cached encoding is used;
6350///
6351/// If the cache contains a Recursive encoding for the member type, the
6352/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6353///
6354/// If the member is a RecordType, an Incomplete encoding is placed into the
6355/// cache to break potential recursive inclusion of itself as a sub-member;
6356///
6357/// Once a member RecordType has been expanded, its temporary incomplete
6358/// entry is removed from the cache. If a Recursive encoding was swapped out
6359/// it is swapped back in;
6360///
6361/// If an incomplete entry is used to expand a sub-member, the incomplete
6362/// entry is marked as IncompleteUsed. The cache keeps count of how many
6363/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6364///
6365/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6366/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6367/// Else the member is part of a recursive type and thus the recursion has
6368/// been exited too soon for the encoding to be correct for the member.
6369///
6370class TypeStringCache {
6371 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6372 struct Entry {
6373 std::string Str; // The encoded TypeString for the type.
6374 enum Status State; // Information about the encoding in 'Str'.
6375 std::string Swapped; // A temporary place holder for a Recursive encoding
6376 // during the expansion of RecordType's members.
6377 };
6378 std::map<const IdentifierInfo *, struct Entry> Map;
6379 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6380 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6381public:
Robert Lyttond263f142014-05-06 09:38:54 +00006382 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006383 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6384 bool removeIncomplete(const IdentifierInfo *ID);
6385 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6386 bool IsRecursive);
6387 StringRef lookupStr(const IdentifierInfo *ID);
6388};
6389
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006390/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006391/// FieldEncoding is a helper for this ordering process.
6392class FieldEncoding {
6393 bool HasName;
6394 std::string Enc;
6395public:
6396 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6397 StringRef str() {return Enc.c_str();};
6398 bool operator<(const FieldEncoding &rhs) const {
6399 if (HasName != rhs.HasName) return HasName;
6400 return Enc < rhs.Enc;
6401 }
6402};
6403
Robert Lytton7d1db152013-08-19 09:46:39 +00006404class XCoreABIInfo : public DefaultABIInfo {
6405public:
6406 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006407 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6408 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006409};
6410
Robert Lyttond21e2d72014-03-03 13:45:29 +00006411class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006412 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006413public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006414 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006415 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006416 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6417 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006418};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006419
Robert Lytton2d196952013-10-11 10:29:34 +00006420} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006421
Robert Lytton7d1db152013-08-19 09:46:39 +00006422llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6423 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006424 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006425
Robert Lytton2d196952013-10-11 10:29:34 +00006426 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006427 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6428 CGF.Int8PtrPtrTy);
6429 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006430
Robert Lytton2d196952013-10-11 10:29:34 +00006431 // Handle the argument.
6432 ABIArgInfo AI = classifyArgumentType(Ty);
6433 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6434 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6435 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006436 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006437 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006438 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006439 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006440 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006441 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006442 llvm_unreachable("Unsupported ABI kind for va_arg");
6443 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006444 Val = llvm::UndefValue::get(ArgPtrTy);
6445 ArgSize = 0;
6446 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006447 case ABIArgInfo::Extend:
6448 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006449 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6450 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6451 if (ArgSize < 4)
6452 ArgSize = 4;
6453 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006454 case ABIArgInfo::Indirect:
6455 llvm::Value *ArgAddr;
6456 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6457 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006458 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6459 ArgSize = 4;
6460 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006461 }
Robert Lytton2d196952013-10-11 10:29:34 +00006462
6463 // Increment the VAList.
6464 if (ArgSize) {
6465 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6466 Builder.CreateStore(APN, VAListAddrAsBPP);
6467 }
6468 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006469}
Robert Lytton0e076492013-08-13 09:43:10 +00006470
Robert Lytton844aeeb2014-05-02 09:33:20 +00006471/// During the expansion of a RecordType, an incomplete TypeString is placed
6472/// into the cache as a means to identify and break recursion.
6473/// If there is a Recursive encoding in the cache, it is swapped out and will
6474/// be reinserted by removeIncomplete().
6475/// All other types of encoding should have been used rather than arriving here.
6476void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6477 std::string StubEnc) {
6478 if (!ID)
6479 return;
6480 Entry &E = Map[ID];
6481 assert( (E.Str.empty() || E.State == Recursive) &&
6482 "Incorrectly use of addIncomplete");
6483 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6484 E.Swapped.swap(E.Str); // swap out the Recursive
6485 E.Str.swap(StubEnc);
6486 E.State = Incomplete;
6487 ++IncompleteCount;
6488}
6489
6490/// Once the RecordType has been expanded, the temporary incomplete TypeString
6491/// must be removed from the cache.
6492/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6493/// Returns true if the RecordType was defined recursively.
6494bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6495 if (!ID)
6496 return false;
6497 auto I = Map.find(ID);
6498 assert(I != Map.end() && "Entry not present");
6499 Entry &E = I->second;
6500 assert( (E.State == Incomplete ||
6501 E.State == IncompleteUsed) &&
6502 "Entry must be an incomplete type");
6503 bool IsRecursive = false;
6504 if (E.State == IncompleteUsed) {
6505 // We made use of our Incomplete encoding, thus we are recursive.
6506 IsRecursive = true;
6507 --IncompleteUsedCount;
6508 }
6509 if (E.Swapped.empty())
6510 Map.erase(I);
6511 else {
6512 // Swap the Recursive back.
6513 E.Swapped.swap(E.Str);
6514 E.Swapped.clear();
6515 E.State = Recursive;
6516 }
6517 --IncompleteCount;
6518 return IsRecursive;
6519}
6520
6521/// Add the encoded TypeString to the cache only if it is NonRecursive or
6522/// Recursive (viz: all sub-members were expanded as fully as possible).
6523void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6524 bool IsRecursive) {
6525 if (!ID || IncompleteUsedCount)
6526 return; // No key or it is is an incomplete sub-type so don't add.
6527 Entry &E = Map[ID];
6528 if (IsRecursive && !E.Str.empty()) {
6529 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6530 "This is not the same Recursive entry");
6531 // The parent container was not recursive after all, so we could have used
6532 // this Recursive sub-member entry after all, but we assumed the worse when
6533 // we started viz: IncompleteCount!=0.
6534 return;
6535 }
6536 assert(E.Str.empty() && "Entry already present");
6537 E.Str = Str.str();
6538 E.State = IsRecursive? Recursive : NonRecursive;
6539}
6540
6541/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6542/// are recursively expanding a type (IncompleteCount != 0) and the cached
6543/// encoding is Recursive, return an empty StringRef.
6544StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6545 if (!ID)
6546 return StringRef(); // We have no key.
6547 auto I = Map.find(ID);
6548 if (I == Map.end())
6549 return StringRef(); // We have no encoding.
6550 Entry &E = I->second;
6551 if (E.State == Recursive && IncompleteCount)
6552 return StringRef(); // We don't use Recursive encodings for member types.
6553
6554 if (E.State == Incomplete) {
6555 // The incomplete type is being used to break out of recursion.
6556 E.State = IncompleteUsed;
6557 ++IncompleteUsedCount;
6558 }
6559 return E.Str.c_str();
6560}
6561
6562/// The XCore ABI includes a type information section that communicates symbol
6563/// type information to the linker. The linker uses this information to verify
6564/// safety/correctness of things such as array bound and pointers et al.
6565/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6566/// This type information (TypeString) is emitted into meta data for all global
6567/// symbols: definitions, declarations, functions & variables.
6568///
6569/// The TypeString carries type, qualifier, name, size & value details.
6570/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6571/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6572/// The output is tested by test/CodeGen/xcore-stringtype.c.
6573///
6574static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6575 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6576
6577/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6578void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6579 CodeGen::CodeGenModule &CGM) const {
6580 SmallStringEnc Enc;
6581 if (getTypeString(Enc, D, CGM, TSC)) {
6582 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6583 llvm::SmallVector<llvm::Value *, 2> MDVals;
6584 MDVals.push_back(GV);
6585 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6586 llvm::NamedMDNode *MD =
6587 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6588 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6589 }
6590}
6591
6592static bool appendType(SmallStringEnc &Enc, QualType QType,
6593 const CodeGen::CodeGenModule &CGM,
6594 TypeStringCache &TSC);
6595
6596/// Helper function for appendRecordType().
6597/// Builds a SmallVector containing the encoded field types in declaration order.
6598static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6599 const RecordDecl *RD,
6600 const CodeGen::CodeGenModule &CGM,
6601 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006602 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006603 SmallStringEnc Enc;
6604 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006605 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006606 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006607 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006608 Enc += "b(";
6609 llvm::raw_svector_ostream OS(Enc);
6610 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006611 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006612 OS.flush();
6613 Enc += ':';
6614 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006615 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006616 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006617 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006618 Enc += ')';
6619 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006620 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006621 }
6622 return true;
6623}
6624
6625/// Appends structure and union types to Enc and adds encoding to cache.
6626/// Recursively calls appendType (via extractFieldType) for each field.
6627/// Union types have their fields ordered according to the ABI.
6628static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6629 const CodeGen::CodeGenModule &CGM,
6630 TypeStringCache &TSC, const IdentifierInfo *ID) {
6631 // Append the cached TypeString if we have one.
6632 StringRef TypeString = TSC.lookupStr(ID);
6633 if (!TypeString.empty()) {
6634 Enc += TypeString;
6635 return true;
6636 }
6637
6638 // Start to emit an incomplete TypeString.
6639 size_t Start = Enc.size();
6640 Enc += (RT->isUnionType()? 'u' : 's');
6641 Enc += '(';
6642 if (ID)
6643 Enc += ID->getName();
6644 Enc += "){";
6645
6646 // We collect all encoded fields and order as necessary.
6647 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006648 const RecordDecl *RD = RT->getDecl()->getDefinition();
6649 if (RD && !RD->field_empty()) {
6650 // An incomplete TypeString stub is placed in the cache for this RecordType
6651 // so that recursive calls to this RecordType will use it whilst building a
6652 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006653 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006654 std::string StubEnc(Enc.substr(Start).str());
6655 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6656 TSC.addIncomplete(ID, std::move(StubEnc));
6657 if (!extractFieldType(FE, RD, CGM, TSC)) {
6658 (void) TSC.removeIncomplete(ID);
6659 return false;
6660 }
6661 IsRecursive = TSC.removeIncomplete(ID);
6662 // The ABI requires unions to be sorted but not structures.
6663 // See FieldEncoding::operator< for sort algorithm.
6664 if (RT->isUnionType())
6665 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006666 // We can now complete the TypeString.
6667 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006668 for (unsigned I = 0; I != E; ++I) {
6669 if (I)
6670 Enc += ',';
6671 Enc += FE[I].str();
6672 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006673 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006674 Enc += '}';
6675 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6676 return true;
6677}
6678
6679/// Appends enum types to Enc and adds the encoding to the cache.
6680static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6681 TypeStringCache &TSC,
6682 const IdentifierInfo *ID) {
6683 // Append the cached TypeString if we have one.
6684 StringRef TypeString = TSC.lookupStr(ID);
6685 if (!TypeString.empty()) {
6686 Enc += TypeString;
6687 return true;
6688 }
6689
6690 size_t Start = Enc.size();
6691 Enc += "e(";
6692 if (ID)
6693 Enc += ID->getName();
6694 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006695
6696 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006697 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006698 SmallVector<FieldEncoding, 16> FE;
6699 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6700 ++I) {
6701 SmallStringEnc EnumEnc;
6702 EnumEnc += "m(";
6703 EnumEnc += I->getName();
6704 EnumEnc += "){";
6705 I->getInitVal().toString(EnumEnc);
6706 EnumEnc += '}';
6707 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6708 }
6709 std::sort(FE.begin(), FE.end());
6710 unsigned E = FE.size();
6711 for (unsigned I = 0; I != E; ++I) {
6712 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006713 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006714 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006715 }
6716 }
6717 Enc += '}';
6718 TSC.addIfComplete(ID, Enc.substr(Start), false);
6719 return true;
6720}
6721
6722/// Appends type's qualifier to Enc.
6723/// This is done prior to appending the type's encoding.
6724static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6725 // Qualifiers are emitted in alphabetical order.
6726 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6727 int Lookup = 0;
6728 if (QT.isConstQualified())
6729 Lookup += 1<<0;
6730 if (QT.isRestrictQualified())
6731 Lookup += 1<<1;
6732 if (QT.isVolatileQualified())
6733 Lookup += 1<<2;
6734 Enc += Table[Lookup];
6735}
6736
6737/// Appends built-in types to Enc.
6738static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6739 const char *EncType;
6740 switch (BT->getKind()) {
6741 case BuiltinType::Void:
6742 EncType = "0";
6743 break;
6744 case BuiltinType::Bool:
6745 EncType = "b";
6746 break;
6747 case BuiltinType::Char_U:
6748 EncType = "uc";
6749 break;
6750 case BuiltinType::UChar:
6751 EncType = "uc";
6752 break;
6753 case BuiltinType::SChar:
6754 EncType = "sc";
6755 break;
6756 case BuiltinType::UShort:
6757 EncType = "us";
6758 break;
6759 case BuiltinType::Short:
6760 EncType = "ss";
6761 break;
6762 case BuiltinType::UInt:
6763 EncType = "ui";
6764 break;
6765 case BuiltinType::Int:
6766 EncType = "si";
6767 break;
6768 case BuiltinType::ULong:
6769 EncType = "ul";
6770 break;
6771 case BuiltinType::Long:
6772 EncType = "sl";
6773 break;
6774 case BuiltinType::ULongLong:
6775 EncType = "ull";
6776 break;
6777 case BuiltinType::LongLong:
6778 EncType = "sll";
6779 break;
6780 case BuiltinType::Float:
6781 EncType = "ft";
6782 break;
6783 case BuiltinType::Double:
6784 EncType = "d";
6785 break;
6786 case BuiltinType::LongDouble:
6787 EncType = "ld";
6788 break;
6789 default:
6790 return false;
6791 }
6792 Enc += EncType;
6793 return true;
6794}
6795
6796/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6797static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6798 const CodeGen::CodeGenModule &CGM,
6799 TypeStringCache &TSC) {
6800 Enc += "p(";
6801 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6802 return false;
6803 Enc += ')';
6804 return true;
6805}
6806
6807/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006808static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6809 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006810 const CodeGen::CodeGenModule &CGM,
6811 TypeStringCache &TSC, StringRef NoSizeEnc) {
6812 if (AT->getSizeModifier() != ArrayType::Normal)
6813 return false;
6814 Enc += "a(";
6815 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6816 CAT->getSize().toStringUnsigned(Enc);
6817 else
6818 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6819 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006820 // The Qualifiers should be attached to the type rather than the array.
6821 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006822 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6823 return false;
6824 Enc += ')';
6825 return true;
6826}
6827
6828/// Appends a function encoding to Enc, calling appendType for the return type
6829/// and the arguments.
6830static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6831 const CodeGen::CodeGenModule &CGM,
6832 TypeStringCache &TSC) {
6833 Enc += "f{";
6834 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6835 return false;
6836 Enc += "}(";
6837 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6838 // N.B. we are only interested in the adjusted param types.
6839 auto I = FPT->param_type_begin();
6840 auto E = FPT->param_type_end();
6841 if (I != E) {
6842 do {
6843 if (!appendType(Enc, *I, CGM, TSC))
6844 return false;
6845 ++I;
6846 if (I != E)
6847 Enc += ',';
6848 } while (I != E);
6849 if (FPT->isVariadic())
6850 Enc += ",va";
6851 } else {
6852 if (FPT->isVariadic())
6853 Enc += "va";
6854 else
6855 Enc += '0';
6856 }
6857 }
6858 Enc += ')';
6859 return true;
6860}
6861
6862/// Handles the type's qualifier before dispatching a call to handle specific
6863/// type encodings.
6864static bool appendType(SmallStringEnc &Enc, QualType QType,
6865 const CodeGen::CodeGenModule &CGM,
6866 TypeStringCache &TSC) {
6867
6868 QualType QT = QType.getCanonicalType();
6869
Robert Lytton6adb20f2014-06-05 09:06:21 +00006870 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6871 // The Qualifiers should be attached to the type rather than the array.
6872 // Thus we don't call appendQualifier() here.
6873 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6874
Robert Lytton844aeeb2014-05-02 09:33:20 +00006875 appendQualifier(Enc, QT);
6876
6877 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6878 return appendBuiltinType(Enc, BT);
6879
Robert Lytton844aeeb2014-05-02 09:33:20 +00006880 if (const PointerType *PT = QT->getAs<PointerType>())
6881 return appendPointerType(Enc, PT, CGM, TSC);
6882
6883 if (const EnumType *ET = QT->getAs<EnumType>())
6884 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6885
6886 if (const RecordType *RT = QT->getAsStructureType())
6887 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6888
6889 if (const RecordType *RT = QT->getAsUnionType())
6890 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6891
6892 if (const FunctionType *FT = QT->getAs<FunctionType>())
6893 return appendFunctionType(Enc, FT, CGM, TSC);
6894
6895 return false;
6896}
6897
6898static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6899 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6900 if (!D)
6901 return false;
6902
6903 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6904 if (FD->getLanguageLinkage() != CLanguageLinkage)
6905 return false;
6906 return appendType(Enc, FD->getType(), CGM, TSC);
6907 }
6908
6909 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6910 if (VD->getLanguageLinkage() != CLanguageLinkage)
6911 return false;
6912 QualType QT = VD->getType().getCanonicalType();
6913 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6914 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006915 // The Qualifiers should be attached to the type rather than the array.
6916 // Thus we don't call appendQualifier() here.
6917 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00006918 }
6919 return appendType(Enc, QT, CGM, TSC);
6920 }
6921 return false;
6922}
6923
6924
Robert Lytton0e076492013-08-13 09:43:10 +00006925//===----------------------------------------------------------------------===//
6926// Driver code
6927//===----------------------------------------------------------------------===//
6928
Rafael Espindola9f834732014-09-19 01:54:22 +00006929const llvm::Triple &CodeGenModule::getTriple() const {
6930 return getTarget().getTriple();
6931}
6932
6933bool CodeGenModule::supportsCOMDAT() const {
6934 return !getTriple().isOSBinFormatMachO();
6935}
6936
Chris Lattner2b037972010-07-29 02:01:43 +00006937const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006938 if (TheTargetCodeGenInfo)
6939 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006940
John McCallc8e01702013-04-16 22:48:15 +00006941 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00006942 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00006943 default:
Chris Lattner2b037972010-07-29 02:01:43 +00006944 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00006945
Derek Schuff09338a22012-09-06 17:37:28 +00006946 case llvm::Triple::le32:
6947 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00006948 case llvm::Triple::mips:
6949 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006950 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6951
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00006952 case llvm::Triple::mips64:
6953 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006954 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6955
Tim Northover25e8a672014-05-24 12:51:25 +00006956 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00006957 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00006958 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006959 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00006960 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00006961
Tim Northover573cbee2014-05-24 12:52:07 +00006962 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00006963 }
6964
Daniel Dunbard59655c2009-09-12 00:59:49 +00006965 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006966 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00006967 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006968 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006969 {
6970 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006971 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006972 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00006973 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00006974 (CodeGenOpts.FloatABI != "soft" &&
6975 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006976 Kind = ARMABIInfo::AAPCS_VFP;
6977
Derek Schuffa2020962012-10-16 22:30:41 +00006978 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00006979 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00006980 return *(TheTargetCodeGenInfo =
6981 new NaClARMTargetCodeGenInfo(Types, Kind));
6982 default:
6983 return *(TheTargetCodeGenInfo =
6984 new ARMTargetCodeGenInfo(Types, Kind));
6985 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006986 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00006987
John McCallea8d8bb2010-03-11 00:10:12 +00006988 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00006989 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00006990 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00006991 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00006992 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006993 if (getTarget().getABI() == "elfv2")
6994 Kind = PPC64_SVR4_ABIInfo::ELFv2;
6995
Ulrich Weigandb7122372014-07-21 00:48:09 +00006996 return *(TheTargetCodeGenInfo =
6997 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6998 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00006999 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007000 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007001 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007002 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007003 if (getTarget().getABI() == "elfv1")
7004 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7005
Ulrich Weigandb7122372014-07-21 00:48:09 +00007006 return *(TheTargetCodeGenInfo =
7007 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7008 }
John McCallea8d8bb2010-03-11 00:10:12 +00007009
Peter Collingbournec947aae2012-05-20 23:28:41 +00007010 case llvm::Triple::nvptx:
7011 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007012 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007013
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007014 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007015 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007016
Ulrich Weigand47445072013-05-06 16:26:41 +00007017 case llvm::Triple::systemz:
7018 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7019
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007020 case llvm::Triple::tce:
7021 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7022
Eli Friedman33465822011-07-08 23:31:17 +00007023 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007024 bool IsDarwinVectorABI = Triple.isOSDarwin();
7025 bool IsSmallStructInRegABI =
7026 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00007027 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007028
John McCall1fe2a8c2013-06-18 02:46:29 +00007029 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007030 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007031 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007032 IsDarwinVectorABI, IsSmallStructInRegABI,
7033 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007034 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007035 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007036 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007037 new X86_32TargetCodeGenInfo(Types,
7038 IsDarwinVectorABI, IsSmallStructInRegABI,
7039 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007040 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007041 }
Eli Friedman33465822011-07-08 23:31:17 +00007042 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007043
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007044 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007045 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007046
Chris Lattner04dc9572010-08-31 16:44:54 +00007047 switch (Triple.getOS()) {
7048 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007049 return *(TheTargetCodeGenInfo =
7050 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Eli Benderskyd7c92032012-12-04 18:38:10 +00007051 case llvm::Triple::NaCl:
Alexander Musman09184fe2014-09-30 05:29:28 +00007052 return *(TheTargetCodeGenInfo =
7053 new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007054 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007055 return *(TheTargetCodeGenInfo =
7056 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007057 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007058 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007059 case llvm::Triple::hexagon:
7060 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007061 case llvm::Triple::sparcv9:
7062 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007063 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007064 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007065 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007066}