blob: ed9e83fda3b15739f684cc9103207f307d78de38 [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
Reid Klecknere9f6a712014-10-31 17:10:41 +000088bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
89 return false;
90}
91
92bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
93 uint64_t Members) const {
94 return false;
95}
96
Anton Korobeynikov244360d2009-06-05 22:08:42 +000097void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000098 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +000099 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000100 switch (TheKind) {
101 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000102 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000103 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000104 Ty->print(OS);
105 else
106 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000107 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000108 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000109 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000110 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000111 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000112 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000113 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000114 case InAlloca:
115 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
116 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000117 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000118 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000119 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000120 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000121 break;
122 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000123 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 break;
125 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127}
128
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000129TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
130
John McCall3480ef22011-08-30 01:42:09 +0000131// If someone can figure out a general rule for this, that would be great.
132// It's probably just doomed to be platform-dependent, though.
133unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
134 // Verified for:
135 // x86-64 FreeBSD, Linux, Darwin
136 // x86-32 FreeBSD, Linux, Darwin
137 // PowerPC Linux, Darwin
138 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000139 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000140 return 32;
141}
142
John McCalla729c622012-02-17 03:33:10 +0000143bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
144 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000145 // The following conventions are known to require this to be false:
146 // x86_stdcall
147 // MIPS
148 // For everything else, we just prefer false unless we opt out.
149 return false;
150}
151
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000152void
153TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
154 llvm::SmallString<24> &Opt) const {
155 // This assumes the user is passing a library name like "rt" instead of a
156 // filename like "librt.a/so", and that they don't care whether it's static or
157 // dynamic.
158 Opt = "-l";
159 Opt += Lib;
160}
161
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000162static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000164/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000165/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000166static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
167 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000168 if (FD->isUnnamedBitfield())
169 return true;
170
171 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000172
Eli Friedman0b3f2012011-11-18 03:47:20 +0000173 // Constant arrays of empty records count as empty, strip them off.
174 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000175 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000176 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
177 if (AT->getSize() == 0)
178 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000179 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000180 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000181
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000182 const RecordType *RT = FT->getAs<RecordType>();
183 if (!RT)
184 return false;
185
186 // C++ record fields are never empty, at least in the Itanium ABI.
187 //
188 // FIXME: We should use a predicate for whether this behavior is true in the
189 // current ABI.
190 if (isa<CXXRecordDecl>(RT->getDecl()))
191 return false;
192
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000194}
195
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000196/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000197/// fields. Note that a structure with a flexible array member is not
198/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000199static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000200 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000201 if (!RT)
202 return 0;
203 const RecordDecl *RD = RT->getDecl();
204 if (RD->hasFlexibleArrayMember())
205 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000206
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000207 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000208 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000209 for (const auto &I : CXXRD->bases())
210 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000211 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000212
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000213 for (const auto *I : RD->fields())
214 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 return false;
216 return true;
217}
218
219/// isSingleElementStruct - Determine if a structure is a "single
220/// element struct", i.e. it has exactly one non-empty field or
221/// exactly one field which is itself a single element
222/// struct. Structures with flexible array members are never
223/// considered single element structs.
224///
225/// \return The field declaration for the single non-empty field, if
226/// it exists.
227static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
228 const RecordType *RT = T->getAsStructureType();
229 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000230 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000231
232 const RecordDecl *RD = RT->getDecl();
233 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000234 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000235
Craig Topper8a13c412014-05-21 05:09:00 +0000236 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000237
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000238 // If this is a C++ record, check the bases first.
239 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000240 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000241 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000242 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000243 continue;
244
245 // If we already found an element then this isn't a single-element struct.
246 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000247 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000248
249 // If this is non-empty and not a single element struct, the composite
250 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000251 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000252 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000253 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000254 }
255 }
256
257 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000258 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000259 QualType FT = FD->getType();
260
261 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000262 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000263 continue;
264
265 // If we already found an element then this isn't a single-element
266 // struct.
267 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000268 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000269
270 // Treat single element arrays as the element.
271 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
272 if (AT->getSize().getZExtValue() != 1)
273 break;
274 FT = AT->getElementType();
275 }
276
John McCalla1dee5302010-08-22 10:59:02 +0000277 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000278 Found = FT.getTypePtr();
279 } else {
280 Found = isSingleElementStruct(FT, Context);
281 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000282 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000283 }
284 }
285
Eli Friedmanee945342011-11-18 01:25:50 +0000286 // We don't consider a struct a single-element struct if it has
287 // padding beyond the element type.
288 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000289 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000290
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000291 return Found;
292}
293
294static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000295 // Treat complex types as the element type.
296 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
297 Ty = CTy->getElementType();
298
299 // Check for a type which we know has a simple scalar argument-passing
300 // convention without any padding. (We're specifically looking for 32
301 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000302 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000303 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000304 return false;
305
306 uint64_t Size = Context.getTypeSize(Ty);
307 return Size == 32 || Size == 64;
308}
309
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000310/// canExpandIndirectArgument - Test whether an argument type which is to be
311/// passed indirectly (on the stack) would have the equivalent layout if it was
312/// expanded into separate arguments. If so, we prefer to do the latter to avoid
313/// inhibiting optimizations.
314///
315// FIXME: This predicate is missing many cases, currently it just follows
316// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
317// should probably make this smarter, or better yet make the LLVM backend
318// capable of handling it.
319static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
320 // We can only expand structure types.
321 const RecordType *RT = Ty->getAs<RecordType>();
322 if (!RT)
323 return false;
324
325 // We can only expand (C) structures.
326 //
327 // FIXME: This needs to be generalized to handle classes as well.
328 const RecordDecl *RD = RT->getDecl();
329 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
330 return false;
331
Eli Friedmane5c85622011-11-18 01:32:26 +0000332 uint64_t Size = 0;
333
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000334 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000335 if (!is32Or64BitBasicType(FD->getType(), Context))
336 return false;
337
338 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
339 // how to expand them yet, and the predicate for telling if a bitfield still
340 // counts as "basic" is more complicated than what we were doing previously.
341 if (FD->isBitField())
342 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000343
344 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000345 }
346
Eli Friedmane5c85622011-11-18 01:32:26 +0000347 // Make sure there are not any holes in the struct.
348 if (Size != Context.getTypeSize(Ty))
349 return false;
350
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000351 return true;
352}
353
354namespace {
355/// DefaultABIInfo - The default implementation for ABI specific
356/// details. This implementation provides information which results in
357/// self-consistent and sensible LLVM IR generation, but does not
358/// conform to any particular ABI.
359class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000360public:
361 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000362
Chris Lattner458b2aa2010-07-29 02:16:43 +0000363 ABIArgInfo classifyReturnType(QualType RetTy) const;
364 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000365
Craig Topper4f12f102014-03-12 06:41:41 +0000366 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000367 if (!getCXXABI().classifyReturnType(FI))
368 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000369 for (auto &I : FI.arguments())
370 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000371 }
372
Craig Topper4f12f102014-03-12 06:41:41 +0000373 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
374 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000375};
376
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000377class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
378public:
Chris Lattner2b037972010-07-29 02:01:43 +0000379 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
380 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000381};
382
383llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
384 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000385 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000386}
387
Chris Lattner458b2aa2010-07-29 02:16:43 +0000388ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000389 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000390 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000391
Chris Lattner9723d6c2010-03-11 18:19:55 +0000392 // Treat an enum type as its underlying type.
393 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
394 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000395
Chris Lattner9723d6c2010-03-11 18:19:55 +0000396 return (Ty->isPromotableIntegerType() ?
397 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000398}
399
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000400ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
401 if (RetTy->isVoidType())
402 return ABIArgInfo::getIgnore();
403
404 if (isAggregateTypeForABI(RetTy))
405 return ABIArgInfo::getIndirect(0);
406
407 // Treat an enum type as its underlying type.
408 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
409 RetTy = EnumTy->getDecl()->getIntegerType();
410
411 return (RetTy->isPromotableIntegerType() ?
412 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
413}
414
Derek Schuff09338a22012-09-06 17:37:28 +0000415//===----------------------------------------------------------------------===//
416// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000417//
418// This is a simplified version of the x86_32 ABI. Arguments and return values
419// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000420//===----------------------------------------------------------------------===//
421
422class PNaClABIInfo : public ABIInfo {
423 public:
424 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
425
426 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000427 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000428
Craig Topper4f12f102014-03-12 06:41:41 +0000429 void computeInfo(CGFunctionInfo &FI) const override;
430 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
431 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000432};
433
434class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
435 public:
436 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
437 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
438};
439
440void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000441 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000442 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
443
Reid Kleckner40ca9132014-05-13 22:05:45 +0000444 for (auto &I : FI.arguments())
445 I.info = classifyArgumentType(I.type);
446}
Derek Schuff09338a22012-09-06 17:37:28 +0000447
448llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
449 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000450 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000451}
452
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000453/// \brief Classify argument of given type \p Ty.
454ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000455 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000456 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000457 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000458 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000459 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
460 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000461 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000462 } else if (Ty->isFloatingType()) {
463 // Floating-point types don't go inreg.
464 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000465 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000466
467 return (Ty->isPromotableIntegerType() ?
468 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000469}
470
471ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
472 if (RetTy->isVoidType())
473 return ABIArgInfo::getIgnore();
474
Eli Benderskye20dad62013-04-04 22:49:35 +0000475 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000476 if (isAggregateTypeForABI(RetTy))
477 return ABIArgInfo::getIndirect(0);
478
479 // Treat an enum type as its underlying type.
480 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
481 RetTy = EnumTy->getDecl()->getIntegerType();
482
483 return (RetTy->isPromotableIntegerType() ?
484 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
485}
486
Chad Rosier651c1832013-03-25 21:00:27 +0000487/// IsX86_MMXType - Return true if this is an MMX type.
488bool IsX86_MMXType(llvm::Type *IRType) {
489 // 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 +0000490 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
491 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
492 IRType->getScalarSizeInBits() != 64;
493}
494
Jay Foad7c57be32011-07-11 09:56:20 +0000495static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000496 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000497 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000498 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
499 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
500 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000501 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000502 }
503
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000504 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000505 }
506
507 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000508 return Ty;
509}
510
Chris Lattner0cf24192010-06-28 20:05:43 +0000511//===----------------------------------------------------------------------===//
512// X86-32 ABI Implementation
513//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000514
Reid Kleckner661f35b2014-01-18 01:12:41 +0000515/// \brief Similar to llvm::CCState, but for Clang.
516struct CCState {
517 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
518
519 unsigned CC;
520 unsigned FreeRegs;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000521 unsigned StackOffset;
522 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000523};
524
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525/// X86_32ABIInfo - The X86-32 ABI information.
526class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000527 enum Class {
528 Integer,
529 Float
530 };
531
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000532 static const unsigned MinABIStackAlignInBytes = 4;
533
David Chisnallde3a0692009-08-17 23:08:21 +0000534 bool IsDarwinVectorABI;
535 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000536 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000537 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000538
539 static bool isRegisterSize(unsigned Size) {
540 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
541 }
542
Reid Kleckner40ca9132014-05-13 22:05:45 +0000543 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000544
Daniel Dunbar557893d2010-04-21 19:10:51 +0000545 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
546 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000547 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
548
549 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000550
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000551 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000552 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000553
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000554 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000555 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000556 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
557 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000558
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000559 /// \brief Rewrite the function info so that all memory arguments use
560 /// inalloca.
561 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
562
563 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
564 unsigned &StackOffset, ABIArgInfo &Info,
565 QualType Type) const;
566
Rafael Espindola75419dc2012-07-23 23:30:29 +0000567public:
568
Craig Topper4f12f102014-03-12 06:41:41 +0000569 void computeInfo(CGFunctionInfo &FI) const override;
570 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
571 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572
Chad Rosier651c1832013-03-25 21:00:27 +0000573 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000574 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000575 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000576 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000577};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000579class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
580public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000581 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000582 bool d, bool p, bool w, unsigned r)
583 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000584
John McCall1fe2a8c2013-06-18 02:46:29 +0000585 static bool isStructReturnInRegABI(
586 const llvm::Triple &Triple, const CodeGenOptions &Opts);
587
Charles Davis4ea31ab2010-02-13 15:54:06 +0000588 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000589 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000590
Craig Topper4f12f102014-03-12 06:41:41 +0000591 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000592 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000593 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000594 return 4;
595 }
596
597 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000598 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000599
Jay Foad7c57be32011-07-11 09:56:20 +0000600 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000602 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000603 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
604 }
605
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000606 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
607 std::string &Constraints,
608 std::vector<llvm::Type *> &ResultRegTypes,
609 std::vector<llvm::Type *> &ResultTruncRegTypes,
610 std::vector<LValue> &ResultRegDests,
611 std::string &AsmString,
612 unsigned NumOutputs) const override;
613
Craig Topper4f12f102014-03-12 06:41:41 +0000614 llvm::Constant *
615 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000616 unsigned Sig = (0xeb << 0) | // jmp rel8
617 (0x06 << 8) | // .+0x08
618 ('F' << 16) |
619 ('T' << 24);
620 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
621 }
622
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000623};
624
625}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000626
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000627/// Rewrite input constraint references after adding some output constraints.
628/// In the case where there is one output and one input and we add one output,
629/// we need to replace all operand references greater than or equal to 1:
630/// mov $0, $1
631/// mov eax, $1
632/// The result will be:
633/// mov $0, $2
634/// mov eax, $2
635static void rewriteInputConstraintReferences(unsigned FirstIn,
636 unsigned NumNewOuts,
637 std::string &AsmString) {
638 std::string Buf;
639 llvm::raw_string_ostream OS(Buf);
640 size_t Pos = 0;
641 while (Pos < AsmString.size()) {
642 size_t DollarStart = AsmString.find('$', Pos);
643 if (DollarStart == std::string::npos)
644 DollarStart = AsmString.size();
645 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
646 if (DollarEnd == std::string::npos)
647 DollarEnd = AsmString.size();
648 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
649 Pos = DollarEnd;
650 size_t NumDollars = DollarEnd - DollarStart;
651 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
652 // We have an operand reference.
653 size_t DigitStart = Pos;
654 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
655 if (DigitEnd == std::string::npos)
656 DigitEnd = AsmString.size();
657 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
658 unsigned OperandIndex;
659 if (!OperandStr.getAsInteger(10, OperandIndex)) {
660 if (OperandIndex >= FirstIn)
661 OperandIndex += NumNewOuts;
662 OS << OperandIndex;
663 } else {
664 OS << OperandStr;
665 }
666 Pos = DigitEnd;
667 }
668 }
669 AsmString = std::move(OS.str());
670}
671
672/// Add output constraints for EAX:EDX because they are return registers.
673void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
674 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
675 std::vector<llvm::Type *> &ResultRegTypes,
676 std::vector<llvm::Type *> &ResultTruncRegTypes,
677 std::vector<LValue> &ResultRegDests, std::string &AsmString,
678 unsigned NumOutputs) const {
679 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
680
681 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
682 // larger.
683 if (!Constraints.empty())
684 Constraints += ',';
685 if (RetWidth <= 32) {
686 Constraints += "={eax}";
687 ResultRegTypes.push_back(CGF.Int32Ty);
688 } else {
689 // Use the 'A' constraint for EAX:EDX.
690 Constraints += "=A";
691 ResultRegTypes.push_back(CGF.Int64Ty);
692 }
693
694 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
695 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
696 ResultTruncRegTypes.push_back(CoerceTy);
697
698 // Coerce the integer by bitcasting the return slot pointer.
699 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
700 CoerceTy->getPointerTo()));
701 ResultRegDests.push_back(ReturnSlot);
702
703 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
704}
705
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000706/// shouldReturnTypeInRegister - Determine if the given type should be
707/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000708bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
709 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000710 uint64_t Size = Context.getTypeSize(Ty);
711
712 // Type must be register sized.
713 if (!isRegisterSize(Size))
714 return false;
715
716 if (Ty->isVectorType()) {
717 // 64- and 128- bit vectors inside structures are not returned in
718 // registers.
719 if (Size == 64 || Size == 128)
720 return false;
721
722 return true;
723 }
724
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000725 // If this is a builtin, pointer, enum, complex type, member pointer, or
726 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000727 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000728 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000729 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000730 return true;
731
732 // Arrays are treated like records.
733 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000734 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000735
736 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000737 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000738 if (!RT) return false;
739
Anders Carlsson40446e82010-01-27 03:25:19 +0000740 // FIXME: Traverse bases here too.
741
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000742 // Structure types are passed in register if all fields would be
743 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000744 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000745 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000746 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000747 continue;
748
749 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000750 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000751 return false;
752 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000753 return true;
754}
755
Reid Kleckner661f35b2014-01-18 01:12:41 +0000756ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
757 // If the return value is indirect, then the hidden argument is consuming one
758 // integer register.
759 if (State.FreeRegs) {
760 --State.FreeRegs;
761 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
762 }
763 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
764}
765
Reid Kleckner40ca9132014-05-13 22:05:45 +0000766ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000767 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000768 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000769
Chris Lattner458b2aa2010-07-29 02:16:43 +0000770 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000771 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000772 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000773 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000774
775 // 128-bit vectors are a special case; they are returned in
776 // registers and we need to make sure to pick a type the LLVM
777 // backend will like.
778 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000779 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000780 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000781
782 // Always return in register if it fits in a general purpose
783 // register, or if it is 64 bits and has a single element.
784 if ((Size == 8 || Size == 16 || Size == 32) ||
785 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000786 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000787 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000788
Reid Kleckner661f35b2014-01-18 01:12:41 +0000789 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000790 }
791
792 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000793 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000794
John McCalla1dee5302010-08-22 10:59:02 +0000795 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000796 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000797 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000798 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000799 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000800 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000801
David Chisnallde3a0692009-08-17 23:08:21 +0000802 // If specified, structs and unions are always indirect.
803 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000804 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000805
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000806 // Small structures which are register sized are generally returned
807 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000808 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000809 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000810
811 // As a special-case, if the struct is a "single-element" struct, and
812 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000813 // floating-point register. (MSVC does not apply this special case.)
814 // We apply a similar transformation for pointer types to improve the
815 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000816 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000817 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000818 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000819 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
820
821 // FIXME: We should be able to narrow this integer in cases with dead
822 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000823 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000824 }
825
Reid Kleckner661f35b2014-01-18 01:12:41 +0000826 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000827 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000828
Chris Lattner458b2aa2010-07-29 02:16:43 +0000829 // Treat an enum type as its underlying type.
830 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
831 RetTy = EnumTy->getDecl()->getIntegerType();
832
833 return (RetTy->isPromotableIntegerType() ?
834 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000835}
836
Eli Friedman7919bea2012-06-05 19:40:46 +0000837static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
838 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
839}
840
Daniel Dunbared23de32010-09-16 20:42:00 +0000841static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
842 const RecordType *RT = Ty->getAs<RecordType>();
843 if (!RT)
844 return 0;
845 const RecordDecl *RD = RT->getDecl();
846
847 // If this is a C++ record, check the bases first.
848 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000849 for (const auto &I : CXXRD->bases())
850 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000851 return false;
852
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000853 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000854 QualType FT = i->getType();
855
Eli Friedman7919bea2012-06-05 19:40:46 +0000856 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000857 return true;
858
859 if (isRecordWithSSEVectorType(Context, FT))
860 return true;
861 }
862
863 return false;
864}
865
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000866unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
867 unsigned Align) const {
868 // Otherwise, if the alignment is less than or equal to the minimum ABI
869 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000870 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000871 return 0; // Use default alignment.
872
873 // On non-Darwin, the stack type alignment is always 4.
874 if (!IsDarwinVectorABI) {
875 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000876 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000877 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000878
Daniel Dunbared23de32010-09-16 20:42:00 +0000879 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000880 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
881 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000882 return 16;
883
884 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000885}
886
Rafael Espindola703c47f2012-10-19 05:04:37 +0000887ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000888 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000889 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000890 if (State.FreeRegs) {
891 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000892 return ABIArgInfo::getIndirectInReg(0, false);
893 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000894 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000895 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000896
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000897 // Compute the byval alignment.
898 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
899 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
900 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000901 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000902
903 // If the stack alignment is less than the type alignment, realign the
904 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000905 bool Realign = TypeAlign > StackAlign;
906 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000907}
908
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000909X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
910 const Type *T = isSingleElementStruct(Ty, getContext());
911 if (!T)
912 T = Ty.getTypePtr();
913
914 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
915 BuiltinType::Kind K = BT->getKind();
916 if (K == BuiltinType::Float || K == BuiltinType::Double)
917 return Float;
918 }
919 return Integer;
920}
921
Reid Kleckner661f35b2014-01-18 01:12:41 +0000922bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
923 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000924 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000925 Class C = classify(Ty);
926 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000927 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000928
Rafael Espindola077dd592012-10-24 01:58:58 +0000929 unsigned Size = getContext().getTypeSize(Ty);
930 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000931
932 if (SizeInRegs == 0)
933 return false;
934
Reid Kleckner661f35b2014-01-18 01:12:41 +0000935 if (SizeInRegs > State.FreeRegs) {
936 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000937 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000938 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000939
Reid Kleckner661f35b2014-01-18 01:12:41 +0000940 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000941
Reid Kleckner661f35b2014-01-18 01:12:41 +0000942 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000943 if (Size > 32)
944 return false;
945
946 if (Ty->isIntegralOrEnumerationType())
947 return true;
948
949 if (Ty->isPointerType())
950 return true;
951
952 if (Ty->isReferenceType())
953 return true;
954
Reid Kleckner661f35b2014-01-18 01:12:41 +0000955 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000956 NeedsPadding = true;
957
Rafael Espindola077dd592012-10-24 01:58:58 +0000958 return false;
959 }
960
Rafael Espindola703c47f2012-10-19 05:04:37 +0000961 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000962}
963
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000964ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
965 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000966 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000967 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000968 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000969 // Check with the C++ ABI first.
970 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
971 if (RAA == CGCXXABI::RAA_Indirect) {
972 return getIndirectResult(Ty, false, State);
973 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
974 // The field index doesn't matter, we'll fix it up later.
975 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
976 }
977
978 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000979 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000980 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000981
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000982 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000983 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000984 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000985 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000986
Eli Friedman9f061a32011-11-18 00:28:11 +0000987 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000988 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000989 return ABIArgInfo::getIgnore();
990
Rafael Espindolafad28de2012-10-24 01:59:00 +0000991 llvm::LLVMContext &LLVMContext = getVMContext();
992 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
993 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000994 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000995 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000996 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000997 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
998 return ABIArgInfo::getDirectInReg(Result);
999 }
Craig Topper8a13c412014-05-21 05:09:00 +00001000 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001001
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001002 // Expand small (<= 128-bit) record types when we know that the stack layout
1003 // of those arguments will match the struct. This is important because the
1004 // LLVM backend isn't smart enough to remove byval, which inhibits many
1005 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001006 if (getContext().getTypeSize(Ty) <= 4*32 &&
1007 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001008 return ABIArgInfo::getExpandWithPadding(
1009 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001010
Reid Kleckner661f35b2014-01-18 01:12:41 +00001011 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001012 }
1013
Chris Lattnerd774ae92010-08-26 20:05:13 +00001014 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001015 // On Darwin, some vectors are passed in memory, we handle this by passing
1016 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001017 if (IsDarwinVectorABI) {
1018 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001019 if ((Size == 8 || Size == 16 || Size == 32) ||
1020 (Size == 64 && VT->getNumElements() == 1))
1021 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1022 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001023 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001024
Chad Rosier651c1832013-03-25 21:00:27 +00001025 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1026 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001027
Chris Lattnerd774ae92010-08-26 20:05:13 +00001028 return ABIArgInfo::getDirect();
1029 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001030
1031
Chris Lattner458b2aa2010-07-29 02:16:43 +00001032 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1033 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001034
Rafael Espindolafad28de2012-10-24 01:59:00 +00001035 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001036 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001037
1038 if (Ty->isPromotableIntegerType()) {
1039 if (InReg)
1040 return ABIArgInfo::getExtendInReg();
1041 return ABIArgInfo::getExtend();
1042 }
1043 if (InReg)
1044 return ABIArgInfo::getDirectInReg();
1045 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001046}
1047
Rafael Espindolaa6472962012-07-24 00:01:07 +00001048void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001049 CCState State(FI.getCallingConvention());
1050 if (State.CC == llvm::CallingConv::X86_FastCall)
1051 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +00001052 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001053 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001054 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001055 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001056
Reid Kleckner677539d2014-07-10 01:58:55 +00001057 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001058 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001059 } else if (FI.getReturnInfo().isIndirect()) {
1060 // The C++ ABI is not aware of register usage, so we have to check if the
1061 // return value was sret and put it in a register ourselves if appropriate.
1062 if (State.FreeRegs) {
1063 --State.FreeRegs; // The sret parameter consumes a register.
1064 FI.getReturnInfo().setInReg(true);
1065 }
1066 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001067
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001068 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001069 for (auto &I : FI.arguments()) {
1070 I.info = classifyArgumentType(I.type, State);
1071 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001072 }
1073
1074 // If we needed to use inalloca for any argument, do a second pass and rewrite
1075 // all the memory arguments to use inalloca.
1076 if (UsedInAlloca)
1077 rewriteWithInAlloca(FI);
1078}
1079
1080void
1081X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1082 unsigned &StackOffset,
1083 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001084 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1085 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1086 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1087 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1088
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001089 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1090 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001091 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001092 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001093 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001094 unsigned NumBytes = StackOffset - OldOffset;
1095 assert(NumBytes);
1096 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1097 Ty = llvm::ArrayType::get(Ty, NumBytes);
1098 FrameFields.push_back(Ty);
1099 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001100}
1101
Reid Kleckner852361d2014-07-26 00:12:26 +00001102static bool isArgInAlloca(const ABIArgInfo &Info) {
1103 // Leave ignored and inreg arguments alone.
1104 switch (Info.getKind()) {
1105 case ABIArgInfo::InAlloca:
1106 return true;
1107 case ABIArgInfo::Indirect:
1108 assert(Info.getIndirectByVal());
1109 return true;
1110 case ABIArgInfo::Ignore:
1111 return false;
1112 case ABIArgInfo::Direct:
1113 case ABIArgInfo::Extend:
1114 case ABIArgInfo::Expand:
1115 if (Info.getInReg())
1116 return false;
1117 return true;
1118 }
1119 llvm_unreachable("invalid enum");
1120}
1121
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001122void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1123 assert(IsWin32StructABI && "inalloca only supported on win32");
1124
1125 // Build a packed struct type for all of the arguments in memory.
1126 SmallVector<llvm::Type *, 6> FrameFields;
1127
1128 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001129 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1130
1131 // Put 'this' into the struct before 'sret', if necessary.
1132 bool IsThisCall =
1133 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1134 ABIArgInfo &Ret = FI.getReturnInfo();
1135 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1136 isArgInAlloca(I->info)) {
1137 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1138 ++I;
1139 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001140
1141 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001142 if (Ret.isIndirect() && !Ret.getInReg()) {
1143 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1144 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001145 // On Windows, the hidden sret parameter is always returned in eax.
1146 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001147 }
1148
1149 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001150 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001151 ++I;
1152
1153 // Put arguments passed in memory into the struct.
1154 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001155 if (isArgInAlloca(I->info))
1156 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001157 }
1158
1159 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1160 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001161}
1162
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001163llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1164 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001165 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001166
1167 CGBuilderTy &Builder = CGF.Builder;
1168 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1169 "ap");
1170 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001171
1172 // Compute if the address needs to be aligned
1173 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1174 Align = getTypeStackAlignInBytes(Ty, Align);
1175 Align = std::max(Align, 4U);
1176 if (Align > 4) {
1177 // addr = (addr + align - 1) & -align;
1178 llvm::Value *Offset =
1179 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1180 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1181 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1182 CGF.Int32Ty);
1183 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1184 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1185 Addr->getType(),
1186 "ap.cur.aligned");
1187 }
1188
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001189 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001190 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001191 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1192
1193 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001194 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001195 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001196 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001197 "ap.next");
1198 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1199
1200 return AddrTyped;
1201}
1202
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001203bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1204 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1205 assert(Triple.getArch() == llvm::Triple::x86);
1206
1207 switch (Opts.getStructReturnConvention()) {
1208 case CodeGenOptions::SRCK_Default:
1209 break;
1210 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1211 return false;
1212 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1213 return true;
1214 }
1215
1216 if (Triple.isOSDarwin())
1217 return true;
1218
1219 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001220 case llvm::Triple::DragonFly:
1221 case llvm::Triple::FreeBSD:
1222 case llvm::Triple::OpenBSD:
1223 case llvm::Triple::Bitrig:
1224 return true;
1225 case llvm::Triple::Win32:
1226 switch (Triple.getEnvironment()) {
1227 case llvm::Triple::UnknownEnvironment:
1228 case llvm::Triple::Cygnus:
1229 case llvm::Triple::GNU:
1230 case llvm::Triple::MSVC:
1231 return true;
1232 default:
1233 return false;
1234 }
1235 default:
1236 return false;
1237 }
1238}
1239
Charles Davis4ea31ab2010-02-13 15:54:06 +00001240void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1241 llvm::GlobalValue *GV,
1242 CodeGen::CodeGenModule &CGM) const {
1243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1244 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1245 // Get the LLVM function.
1246 llvm::Function *Fn = cast<llvm::Function>(GV);
1247
1248 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001249 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001250 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001251 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1252 llvm::AttributeSet::get(CGM.getLLVMContext(),
1253 llvm::AttributeSet::FunctionIndex,
1254 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001255 }
1256 }
1257}
1258
John McCallbeec5a02010-03-06 00:35:14 +00001259bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1260 CodeGen::CodeGenFunction &CGF,
1261 llvm::Value *Address) const {
1262 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001263
Chris Lattnerece04092012-02-07 00:39:47 +00001264 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001265
John McCallbeec5a02010-03-06 00:35:14 +00001266 // 0-7 are the eight integer registers; the order is different
1267 // on Darwin (for EH), but the range is the same.
1268 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001269 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001270
John McCallc8e01702013-04-16 22:48:15 +00001271 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001272 // 12-16 are st(0..4). Not sure why we stop at 4.
1273 // These have size 16, which is sizeof(long double) on
1274 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001275 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001276 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001277
John McCallbeec5a02010-03-06 00:35:14 +00001278 } else {
1279 // 9 is %eflags, which doesn't get a size on Darwin for some
1280 // reason.
1281 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1282
1283 // 11-16 are st(0..5). Not sure why we stop at 5.
1284 // These have size 12, which is sizeof(long double) on
1285 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001286 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001287 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1288 }
John McCallbeec5a02010-03-06 00:35:14 +00001289
1290 return false;
1291}
1292
Chris Lattner0cf24192010-06-28 20:05:43 +00001293//===----------------------------------------------------------------------===//
1294// X86-64 ABI Implementation
1295//===----------------------------------------------------------------------===//
1296
1297
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001298namespace {
1299/// X86_64ABIInfo - The X86_64 ABI information.
1300class X86_64ABIInfo : public ABIInfo {
1301 enum Class {
1302 Integer = 0,
1303 SSE,
1304 SSEUp,
1305 X87,
1306 X87Up,
1307 ComplexX87,
1308 NoClass,
1309 Memory
1310 };
1311
1312 /// merge - Implement the X86_64 ABI merging algorithm.
1313 ///
1314 /// Merge an accumulating classification \arg Accum with a field
1315 /// classification \arg Field.
1316 ///
1317 /// \param Accum - The accumulating classification. This should
1318 /// always be either NoClass or the result of a previous merge
1319 /// call. In addition, this should never be Memory (the caller
1320 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001321 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001322
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001323 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1324 ///
1325 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1326 /// final MEMORY or SSE classes when necessary.
1327 ///
1328 /// \param AggregateSize - The size of the current aggregate in
1329 /// the classification process.
1330 ///
1331 /// \param Lo - The classification for the parts of the type
1332 /// residing in the low word of the containing object.
1333 ///
1334 /// \param Hi - The classification for the parts of the type
1335 /// residing in the higher words of the containing object.
1336 ///
1337 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1338
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001339 /// classify - Determine the x86_64 register classes in which the
1340 /// given type T should be passed.
1341 ///
1342 /// \param Lo - The classification for the parts of the type
1343 /// residing in the low word of the containing object.
1344 ///
1345 /// \param Hi - The classification for the parts of the type
1346 /// residing in the high word of the containing object.
1347 ///
1348 /// \param OffsetBase - The bit offset of this type in the
1349 /// containing object. Some parameters are classified different
1350 /// depending on whether they straddle an eightbyte boundary.
1351 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001352 /// \param isNamedArg - Whether the argument in question is a "named"
1353 /// argument, as used in AMD64-ABI 3.5.7.
1354 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001355 /// If a word is unused its result will be NoClass; if a type should
1356 /// be passed in Memory then at least the classification of \arg Lo
1357 /// will be Memory.
1358 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001359 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001360 ///
1361 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1362 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001363 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1364 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001365
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001366 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001367 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1368 unsigned IROffset, QualType SourceTy,
1369 unsigned SourceOffset) const;
1370 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1371 unsigned IROffset, QualType SourceTy,
1372 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001373
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001374 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001375 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001376 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001377
1378 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001379 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001380 ///
1381 /// \param freeIntRegs - The number of free integer registers remaining
1382 /// available.
1383 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001384
Chris Lattner458b2aa2010-07-29 02:16:43 +00001385 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001386
Bill Wendling5cd41c42010-10-18 03:41:31 +00001387 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001388 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001389 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001390 unsigned &neededSSE,
1391 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001392
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001393 bool IsIllegalVectorType(QualType Ty) const;
1394
John McCalle0fda732011-04-21 01:20:55 +00001395 /// The 0.98 ABI revision clarified a lot of ambiguities,
1396 /// unfortunately in ways that were not always consistent with
1397 /// certain previous compilers. In particular, platforms which
1398 /// required strict binary compatibility with older versions of GCC
1399 /// may need to exempt themselves.
1400 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001401 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001402 }
1403
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001404 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001405 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1406 // 64-bit hardware.
1407 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001408
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001409public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001410 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001411 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001412 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001413 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001414
John McCalla729c622012-02-17 03:33:10 +00001415 bool isPassedUsingAVXType(QualType type) const {
1416 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001417 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001418 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1419 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001420 if (info.isDirect()) {
1421 llvm::Type *ty = info.getCoerceToType();
1422 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1423 return (vectorTy->getBitWidth() > 128);
1424 }
1425 return false;
1426 }
1427
Craig Topper4f12f102014-03-12 06:41:41 +00001428 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001429
Craig Topper4f12f102014-03-12 06:41:41 +00001430 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1431 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001432};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001433
Chris Lattner04dc9572010-08-31 16:44:54 +00001434/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001435class WinX86_64ABIInfo : public ABIInfo {
1436
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001437 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001438
Chris Lattner04dc9572010-08-31 16:44:54 +00001439public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001440 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1441
Craig Topper4f12f102014-03-12 06:41:41 +00001442 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001443
Craig Topper4f12f102014-03-12 06:41:41 +00001444 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1445 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001446};
1447
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001448class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001449 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001450public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001451 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001452 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001453
John McCalla729c622012-02-17 03:33:10 +00001454 const X86_64ABIInfo &getABIInfo() const {
1455 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1456 }
1457
Craig Topper4f12f102014-03-12 06:41:41 +00001458 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001459 return 7;
1460 }
1461
1462 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001463 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001464 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001465
John McCall943fae92010-05-27 06:19:26 +00001466 // 0-15 are the 16 integer registers.
1467 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001468 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001469 return false;
1470 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001471
Jay Foad7c57be32011-07-11 09:56:20 +00001472 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001473 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001474 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001475 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1476 }
1477
John McCalla729c622012-02-17 03:33:10 +00001478 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001479 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001480 // The default CC on x86-64 sets %al to the number of SSA
1481 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001482 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001483 // that when AVX types are involved: the ABI explicitly states it is
1484 // undefined, and it doesn't work in practice because of how the ABI
1485 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001486 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001487 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001488 for (CallArgList::const_iterator
1489 it = args.begin(), ie = args.end(); it != ie; ++it) {
1490 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1491 HasAVXType = true;
1492 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001493 }
1494 }
John McCalla729c622012-02-17 03:33:10 +00001495
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001496 if (!HasAVXType)
1497 return true;
1498 }
John McCallcbc038a2011-09-21 08:08:30 +00001499
John McCalla729c622012-02-17 03:33:10 +00001500 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001501 }
1502
Craig Topper4f12f102014-03-12 06:41:41 +00001503 llvm::Constant *
1504 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001505 unsigned Sig = (0xeb << 0) | // jmp rel8
1506 (0x0a << 8) | // .+0x0c
1507 ('F' << 16) |
1508 ('T' << 24);
1509 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1510 }
1511
Alexander Musman09184fe2014-09-30 05:29:28 +00001512 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1513 return HasAVX ? 32 : 16;
1514 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001515};
1516
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001517static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1518 // If the argument does not end in .lib, automatically add the suffix. This
1519 // matches the behavior of MSVC.
1520 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001521 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001522 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001523 return ArgStr;
1524}
1525
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001526class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1527public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001528 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1529 bool d, bool p, bool w, unsigned RegParms)
1530 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001531
1532 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001533 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001534 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001535 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001536 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001537
1538 void getDetectMismatchOption(llvm::StringRef Name,
1539 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001540 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001541 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001542 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001543};
1544
Chris Lattner04dc9572010-08-31 16:44:54 +00001545class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001546 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001547public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001548 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1549 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001550
Craig Topper4f12f102014-03-12 06:41:41 +00001551 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001552 return 7;
1553 }
1554
1555 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001556 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001557 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001558
Chris Lattner04dc9572010-08-31 16:44:54 +00001559 // 0-15 are the 16 integer registers.
1560 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001561 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001562 return false;
1563 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001564
1565 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001566 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001567 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001568 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001569 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001570
1571 void getDetectMismatchOption(llvm::StringRef Name,
1572 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001573 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001574 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001575 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001576
1577 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1578 return HasAVX ? 32 : 16;
1579 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001580};
1581
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001582}
1583
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001584void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1585 Class &Hi) const {
1586 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1587 //
1588 // (a) If one of the classes is Memory, the whole argument is passed in
1589 // memory.
1590 //
1591 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1592 // memory.
1593 //
1594 // (c) If the size of the aggregate exceeds two eightbytes and the first
1595 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1596 // argument is passed in memory. NOTE: This is necessary to keep the
1597 // ABI working for processors that don't support the __m256 type.
1598 //
1599 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1600 //
1601 // Some of these are enforced by the merging logic. Others can arise
1602 // only with unions; for example:
1603 // union { _Complex double; unsigned; }
1604 //
1605 // Note that clauses (b) and (c) were added in 0.98.
1606 //
1607 if (Hi == Memory)
1608 Lo = Memory;
1609 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1610 Lo = Memory;
1611 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1612 Lo = Memory;
1613 if (Hi == SSEUp && Lo != SSE)
1614 Hi = SSE;
1615}
1616
Chris Lattnerd776fb12010-06-28 21:43:59 +00001617X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001618 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1619 // classified recursively so that always two fields are
1620 // considered. The resulting class is calculated according to
1621 // the classes of the fields in the eightbyte:
1622 //
1623 // (a) If both classes are equal, this is the resulting class.
1624 //
1625 // (b) If one of the classes is NO_CLASS, the resulting class is
1626 // the other class.
1627 //
1628 // (c) If one of the classes is MEMORY, the result is the MEMORY
1629 // class.
1630 //
1631 // (d) If one of the classes is INTEGER, the result is the
1632 // INTEGER.
1633 //
1634 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1635 // MEMORY is used as class.
1636 //
1637 // (f) Otherwise class SSE is used.
1638
1639 // Accum should never be memory (we should have returned) or
1640 // ComplexX87 (because this cannot be passed in a structure).
1641 assert((Accum != Memory && Accum != ComplexX87) &&
1642 "Invalid accumulated classification during merge.");
1643 if (Accum == Field || Field == NoClass)
1644 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001645 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001646 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001647 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001648 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001649 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001650 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001651 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1652 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001653 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001654 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001655}
1656
Chris Lattner5c740f12010-06-30 19:14:05 +00001657void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001658 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001659 // FIXME: This code can be simplified by introducing a simple value class for
1660 // Class pairs with appropriate constructor methods for the various
1661 // situations.
1662
1663 // FIXME: Some of the split computations are wrong; unaligned vectors
1664 // shouldn't be passed in registers for example, so there is no chance they
1665 // can straddle an eightbyte. Verify & simplify.
1666
1667 Lo = Hi = NoClass;
1668
1669 Class &Current = OffsetBase < 64 ? Lo : Hi;
1670 Current = Memory;
1671
John McCall9dd450b2009-09-21 23:43:11 +00001672 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001673 BuiltinType::Kind k = BT->getKind();
1674
1675 if (k == BuiltinType::Void) {
1676 Current = NoClass;
1677 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1678 Lo = Integer;
1679 Hi = Integer;
1680 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1681 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001682 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1683 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001684 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001685 Current = SSE;
1686 } else if (k == BuiltinType::LongDouble) {
1687 Lo = X87;
1688 Hi = X87Up;
1689 }
1690 // FIXME: _Decimal32 and _Decimal64 are SSE.
1691 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001692 return;
1693 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001694
Chris Lattnerd776fb12010-06-28 21:43:59 +00001695 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001696 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001697 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001698 return;
1699 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001700
Chris Lattnerd776fb12010-06-28 21:43:59 +00001701 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001702 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001703 return;
1704 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001705
Chris Lattnerd776fb12010-06-28 21:43:59 +00001706 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001707 if (Ty->isMemberFunctionPointerType()) {
1708 if (Has64BitPointers) {
1709 // If Has64BitPointers, this is an {i64, i64}, so classify both
1710 // Lo and Hi now.
1711 Lo = Hi = Integer;
1712 } else {
1713 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1714 // straddles an eightbyte boundary, Hi should be classified as well.
1715 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1716 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1717 if (EB_FuncPtr != EB_ThisAdj) {
1718 Lo = Hi = Integer;
1719 } else {
1720 Current = Integer;
1721 }
1722 }
1723 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001724 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001725 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001726 return;
1727 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001728
Chris Lattnerd776fb12010-06-28 21:43:59 +00001729 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001730 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001731 if (Size == 32) {
1732 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1733 // float> as integer.
1734 Current = Integer;
1735
1736 // If this type crosses an eightbyte boundary, it should be
1737 // split.
1738 uint64_t EB_Real = (OffsetBase) / 64;
1739 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1740 if (EB_Real != EB_Imag)
1741 Hi = Lo;
1742 } else if (Size == 64) {
1743 // gcc passes <1 x double> in memory. :(
1744 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1745 return;
1746
1747 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001748 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001749 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1750 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1751 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001752 Current = Integer;
1753 else
1754 Current = SSE;
1755
1756 // If this type crosses an eightbyte boundary, it should be
1757 // split.
1758 if (OffsetBase && OffsetBase != 64)
1759 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001760 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001761 // Arguments of 256-bits are split into four eightbyte chunks. The
1762 // least significant one belongs to class SSE and all the others to class
1763 // SSEUP. The original Lo and Hi design considers that types can't be
1764 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1765 // This design isn't correct for 256-bits, but since there're no cases
1766 // where the upper parts would need to be inspected, avoid adding
1767 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001768 //
1769 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1770 // registers if they are "named", i.e. not part of the "..." of a
1771 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001772 Lo = SSE;
1773 Hi = SSEUp;
1774 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001775 return;
1776 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001777
Chris Lattnerd776fb12010-06-28 21:43:59 +00001778 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001779 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001780
Chris Lattner2b037972010-07-29 02:01:43 +00001781 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001782 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001783 if (Size <= 64)
1784 Current = Integer;
1785 else if (Size <= 128)
1786 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001787 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001788 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001789 else if (ET == getContext().DoubleTy ||
1790 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001791 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001792 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001793 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001794 Current = ComplexX87;
1795
1796 // If this complex type crosses an eightbyte boundary then it
1797 // should be split.
1798 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001799 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001800 if (Hi == NoClass && EB_Real != EB_Imag)
1801 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001802
Chris Lattnerd776fb12010-06-28 21:43:59 +00001803 return;
1804 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001805
Chris Lattner2b037972010-07-29 02:01:43 +00001806 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001807 // Arrays are treated like structures.
1808
Chris Lattner2b037972010-07-29 02:01:43 +00001809 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001810
1811 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001812 // than four eightbytes, ..., it has class MEMORY.
1813 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001814 return;
1815
1816 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1817 // fields, it has class MEMORY.
1818 //
1819 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001820 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001821 return;
1822
1823 // Otherwise implement simplified merge. We could be smarter about
1824 // this, but it isn't worth it and would be harder to verify.
1825 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001826 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001827 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001828
1829 // The only case a 256-bit wide vector could be used is when the array
1830 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1831 // to work for sizes wider than 128, early check and fallback to memory.
1832 if (Size > 128 && EltSize != 256)
1833 return;
1834
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001835 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1836 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001837 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001838 Lo = merge(Lo, FieldLo);
1839 Hi = merge(Hi, FieldHi);
1840 if (Lo == Memory || Hi == Memory)
1841 break;
1842 }
1843
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001844 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001845 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001846 return;
1847 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001848
Chris Lattnerd776fb12010-06-28 21:43:59 +00001849 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001850 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001851
1852 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001853 // than four eightbytes, ..., it has class MEMORY.
1854 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001855 return;
1856
Anders Carlsson20759ad2009-09-16 15:53:40 +00001857 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1858 // copy constructor or a non-trivial destructor, it is passed by invisible
1859 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001860 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001861 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001862
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001863 const RecordDecl *RD = RT->getDecl();
1864
1865 // Assume variable sized types are passed in memory.
1866 if (RD->hasFlexibleArrayMember())
1867 return;
1868
Chris Lattner2b037972010-07-29 02:01:43 +00001869 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001870
1871 // Reset Lo class, this will be recomputed.
1872 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001873
1874 // If this is a C++ record, classify the bases first.
1875 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001876 for (const auto &I : CXXRD->bases()) {
1877 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001878 "Unexpected base class!");
1879 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001880 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001881
1882 // Classify this field.
1883 //
1884 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1885 // single eightbyte, each is classified separately. Each eightbyte gets
1886 // initialized to class NO_CLASS.
1887 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001888 uint64_t Offset =
1889 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001890 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001891 Lo = merge(Lo, FieldLo);
1892 Hi = merge(Hi, FieldHi);
1893 if (Lo == Memory || Hi == Memory)
1894 break;
1895 }
1896 }
1897
1898 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001899 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001900 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001901 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001902 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1903 bool BitField = i->isBitField();
1904
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001905 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1906 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001907 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001908 // The only case a 256-bit wide vector could be used is when the struct
1909 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1910 // to work for sizes wider than 128, early check and fallback to memory.
1911 //
1912 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1913 Lo = Memory;
1914 return;
1915 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001916 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001917 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001918 Lo = Memory;
1919 return;
1920 }
1921
1922 // Classify this field.
1923 //
1924 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1925 // exceeds a single eightbyte, each is classified
1926 // separately. Each eightbyte gets initialized to class
1927 // NO_CLASS.
1928 Class FieldLo, FieldHi;
1929
1930 // Bit-fields require special handling, they do not force the
1931 // structure to be passed in memory even if unaligned, and
1932 // therefore they can straddle an eightbyte.
1933 if (BitField) {
1934 // Ignore padding bit-fields.
1935 if (i->isUnnamedBitfield())
1936 continue;
1937
1938 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001939 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001940
1941 uint64_t EB_Lo = Offset / 64;
1942 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001943
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001944 if (EB_Lo) {
1945 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1946 FieldLo = NoClass;
1947 FieldHi = Integer;
1948 } else {
1949 FieldLo = Integer;
1950 FieldHi = EB_Hi ? Integer : NoClass;
1951 }
1952 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001953 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001954 Lo = merge(Lo, FieldLo);
1955 Hi = merge(Hi, FieldHi);
1956 if (Lo == Memory || Hi == Memory)
1957 break;
1958 }
1959
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001960 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001961 }
1962}
1963
Chris Lattner22a931e2010-06-29 06:01:59 +00001964ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001965 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1966 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001967 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001968 // Treat an enum type as its underlying type.
1969 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1970 Ty = EnumTy->getDecl()->getIntegerType();
1971
1972 return (Ty->isPromotableIntegerType() ?
1973 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1974 }
1975
1976 return ABIArgInfo::getIndirect(0);
1977}
1978
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001979bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1980 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1981 uint64_t Size = getContext().getTypeSize(VecTy);
1982 unsigned LargestVector = HasAVX ? 256 : 128;
1983 if (Size <= 64 || Size > LargestVector)
1984 return true;
1985 }
1986
1987 return false;
1988}
1989
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001990ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1991 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001992 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1993 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001994 //
1995 // This assumption is optimistic, as there could be free registers available
1996 // when we need to pass this argument in memory, and LLVM could try to pass
1997 // the argument in the free register. This does not seem to happen currently,
1998 // but this code would be much safer if we could mark the argument with
1999 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002000 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002001 // Treat an enum type as its underlying type.
2002 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2003 Ty = EnumTy->getDecl()->getIntegerType();
2004
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002005 return (Ty->isPromotableIntegerType() ?
2006 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002007 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002008
Mark Lacey3825e832013-10-06 01:33:34 +00002009 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002010 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002011
Chris Lattner44c2b902011-05-22 23:21:23 +00002012 // Compute the byval alignment. We specify the alignment of the byval in all
2013 // cases so that the mid-level optimizer knows the alignment of the byval.
2014 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002015
2016 // Attempt to avoid passing indirect results using byval when possible. This
2017 // is important for good codegen.
2018 //
2019 // We do this by coercing the value into a scalar type which the backend can
2020 // handle naturally (i.e., without using byval).
2021 //
2022 // For simplicity, we currently only do this when we have exhausted all of the
2023 // free integer registers. Doing this when there are free integer registers
2024 // would require more care, as we would have to ensure that the coerced value
2025 // did not claim the unused register. That would require either reording the
2026 // arguments to the function (so that any subsequent inreg values came first),
2027 // or only doing this optimization when there were no following arguments that
2028 // might be inreg.
2029 //
2030 // We currently expect it to be rare (particularly in well written code) for
2031 // arguments to be passed on the stack when there are still free integer
2032 // registers available (this would typically imply large structs being passed
2033 // by value), so this seems like a fair tradeoff for now.
2034 //
2035 // We can revisit this if the backend grows support for 'onstack' parameter
2036 // attributes. See PR12193.
2037 if (freeIntRegs == 0) {
2038 uint64_t Size = getContext().getTypeSize(Ty);
2039
2040 // If this type fits in an eightbyte, coerce it into the matching integral
2041 // type, which will end up on the stack (with alignment 8).
2042 if (Align == 8 && Size <= 64)
2043 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2044 Size));
2045 }
2046
Chris Lattner44c2b902011-05-22 23:21:23 +00002047 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002048}
2049
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002050/// GetByteVectorType - The ABI specifies that a value should be passed in an
2051/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00002052/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002053llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002054 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002055
Chris Lattner9fa15c32010-07-29 05:02:29 +00002056 // Wrapper structs that just contain vectors are passed just like vectors,
2057 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002058 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00002059 while (STy && STy->getNumElements() == 1) {
2060 IRType = STy->getElementType(0);
2061 STy = dyn_cast<llvm::StructType>(IRType);
2062 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002063
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00002064 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002065 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2066 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002067 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00002068 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00002069 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2070 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2071 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2072 EltTy->isIntegerTy(128)))
2073 return VT;
2074 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002075
Chris Lattner4200fe42010-07-29 04:56:46 +00002076 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2077}
2078
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002079/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2080/// is known to either be off the end of the specified type or being in
2081/// alignment padding. The user type specified is known to be at most 128 bits
2082/// in size, and have passed through X86_64ABIInfo::classify with a successful
2083/// classification that put one of the two halves in the INTEGER class.
2084///
2085/// It is conservatively correct to return false.
2086static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2087 unsigned EndBit, ASTContext &Context) {
2088 // If the bytes being queried are off the end of the type, there is no user
2089 // data hiding here. This handles analysis of builtins, vectors and other
2090 // types that don't contain interesting padding.
2091 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2092 if (TySize <= StartBit)
2093 return true;
2094
Chris Lattner98076a22010-07-29 07:43:55 +00002095 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2096 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2097 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2098
2099 // Check each element to see if the element overlaps with the queried range.
2100 for (unsigned i = 0; i != NumElts; ++i) {
2101 // If the element is after the span we care about, then we're done..
2102 unsigned EltOffset = i*EltSize;
2103 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002104
Chris Lattner98076a22010-07-29 07:43:55 +00002105 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2106 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2107 EndBit-EltOffset, Context))
2108 return false;
2109 }
2110 // If it overlaps no elements, then it is safe to process as padding.
2111 return true;
2112 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002113
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002114 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2115 const RecordDecl *RD = RT->getDecl();
2116 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002117
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002118 // If this is a C++ record, check the bases first.
2119 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002120 for (const auto &I : CXXRD->bases()) {
2121 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002122 "Unexpected base class!");
2123 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002124 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002125
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002126 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002127 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002128 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002129
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002130 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002131 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002132 EndBit-BaseOffset, Context))
2133 return false;
2134 }
2135 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002136
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002137 // Verify that no field has data that overlaps the region of interest. Yes
2138 // this could be sped up a lot by being smarter about queried fields,
2139 // however we're only looking at structs up to 16 bytes, so we don't care
2140 // much.
2141 unsigned idx = 0;
2142 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2143 i != e; ++i, ++idx) {
2144 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002145
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002146 // If we found a field after the region we care about, then we're done.
2147 if (FieldOffset >= EndBit) break;
2148
2149 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2150 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2151 Context))
2152 return false;
2153 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002154
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002155 // If nothing in this record overlapped the area of interest, then we're
2156 // clean.
2157 return true;
2158 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002159
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002160 return false;
2161}
2162
Chris Lattnere556a712010-07-29 18:39:32 +00002163/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2164/// float member at the specified offset. For example, {int,{float}} has a
2165/// float at offset 4. It is conservatively correct for this routine to return
2166/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002167static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002168 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002169 // Base case if we find a float.
2170 if (IROffset == 0 && IRType->isFloatTy())
2171 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002172
Chris Lattnere556a712010-07-29 18:39:32 +00002173 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002174 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002175 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2176 unsigned Elt = SL->getElementContainingOffset(IROffset);
2177 IROffset -= SL->getElementOffset(Elt);
2178 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2179 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002180
Chris Lattnere556a712010-07-29 18:39:32 +00002181 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002182 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2183 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002184 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2185 IROffset -= IROffset/EltSize*EltSize;
2186 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2187 }
2188
2189 return false;
2190}
2191
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002192
2193/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2194/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002195llvm::Type *X86_64ABIInfo::
2196GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002197 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002198 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002199 // pass as float if the last 4 bytes is just padding. This happens for
2200 // structs that contain 3 floats.
2201 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2202 SourceOffset*8+64, getContext()))
2203 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002204
Chris Lattnere556a712010-07-29 18:39:32 +00002205 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2206 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2207 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002208 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2209 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002210 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002211
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002212 return llvm::Type::getDoubleTy(getVMContext());
2213}
2214
2215
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002216/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2217/// an 8-byte GPR. This means that we either have a scalar or we are talking
2218/// about the high or low part of an up-to-16-byte struct. This routine picks
2219/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002220/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2221/// etc).
2222///
2223/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2224/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2225/// the 8-byte value references. PrefType may be null.
2226///
Alp Toker9907f082014-07-09 14:06:35 +00002227/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002228/// an offset into this that we're processing (which is always either 0 or 8).
2229///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002230llvm::Type *X86_64ABIInfo::
2231GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002232 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002233 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2234 // returning an 8-byte unit starting with it. See if we can safely use it.
2235 if (IROffset == 0) {
2236 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002237 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2238 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002239 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002240
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002241 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2242 // goodness in the source type is just tail padding. This is allowed to
2243 // kick in for struct {double,int} on the int, but not on
2244 // struct{double,int,int} because we wouldn't return the second int. We
2245 // have to do this analysis on the source type because we can't depend on
2246 // unions being lowered a specific way etc.
2247 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002248 IRType->isIntegerTy(32) ||
2249 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2250 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2251 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002252
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002253 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2254 SourceOffset*8+64, getContext()))
2255 return IRType;
2256 }
2257 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002258
Chris Lattner2192fe52011-07-18 04:24:23 +00002259 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002260 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002261 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002262 if (IROffset < SL->getSizeInBytes()) {
2263 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2264 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002265
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002266 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2267 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002268 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002269 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002270
Chris Lattner2192fe52011-07-18 04:24:23 +00002271 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002272 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002273 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002274 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002275 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2276 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002277 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002278
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002279 // Okay, we don't have any better idea of what to pass, so we pass this in an
2280 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002281 unsigned TySizeInBytes =
2282 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002283
Chris Lattner3f763422010-07-29 17:34:39 +00002284 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002285
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002286 // It is always safe to classify this as an integer type up to i64 that
2287 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002288 return llvm::IntegerType::get(getVMContext(),
2289 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002290}
2291
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002292
2293/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2294/// be used as elements of a two register pair to pass or return, return a
2295/// first class aggregate to represent them. For example, if the low part of
2296/// a by-value argument should be passed as i32* and the high part as float,
2297/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002298static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002299GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002300 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002301 // In order to correctly satisfy the ABI, we need to the high part to start
2302 // at offset 8. If the high and low parts we inferred are both 4-byte types
2303 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2304 // the second element at offset 8. Check for this:
2305 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2306 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002307 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002308 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002309
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002310 // To handle this, we have to increase the size of the low part so that the
2311 // second element will start at an 8 byte offset. We can't increase the size
2312 // of the second element because it might make us access off the end of the
2313 // struct.
2314 if (HiStart != 8) {
2315 // There are only two sorts of types the ABI generation code can produce for
2316 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2317 // Promote these to a larger type.
2318 if (Lo->isFloatTy())
2319 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2320 else {
2321 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2322 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2323 }
2324 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002325
Chris Lattnera5f58b02011-07-09 17:41:47 +00002326 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002327
2328
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002329 // Verify that the second element is at an 8-byte offset.
2330 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2331 "Invalid x86-64 argument pair!");
2332 return Result;
2333}
2334
Chris Lattner31faff52010-07-28 23:06:14 +00002335ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002336classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002337 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2338 // classification algorithm.
2339 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002340 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002341
2342 // Check some invariants.
2343 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002344 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2345
Craig Topper8a13c412014-05-21 05:09:00 +00002346 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002347 switch (Lo) {
2348 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002349 if (Hi == NoClass)
2350 return ABIArgInfo::getIgnore();
2351 // If the low part is just padding, it takes no register, leave ResType
2352 // null.
2353 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2354 "Unknown missing lo part");
2355 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002356
2357 case SSEUp:
2358 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002359 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002360
2361 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2362 // hidden argument.
2363 case Memory:
2364 return getIndirectReturnResult(RetTy);
2365
2366 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2367 // available register of the sequence %rax, %rdx is used.
2368 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002369 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002370
Chris Lattner1f3a0632010-07-29 21:42:50 +00002371 // If we have a sign or zero extended integer, make sure to return Extend
2372 // so that the parameter gets the right LLVM IR attributes.
2373 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2374 // Treat an enum type as its underlying type.
2375 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2376 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002377
Chris Lattner1f3a0632010-07-29 21:42:50 +00002378 if (RetTy->isIntegralOrEnumerationType() &&
2379 RetTy->isPromotableIntegerType())
2380 return ABIArgInfo::getExtend();
2381 }
Chris Lattner31faff52010-07-28 23:06:14 +00002382 break;
2383
2384 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2385 // available SSE register of the sequence %xmm0, %xmm1 is used.
2386 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002387 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002388 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002389
2390 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2391 // returned on the X87 stack in %st0 as 80-bit x87 number.
2392 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002393 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002394 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002395
2396 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2397 // part of the value is returned in %st0 and the imaginary part in
2398 // %st1.
2399 case ComplexX87:
2400 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002401 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002402 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002403 NULL);
2404 break;
2405 }
2406
Craig Topper8a13c412014-05-21 05:09:00 +00002407 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002408 switch (Hi) {
2409 // Memory was handled previously and X87 should
2410 // never occur as a hi class.
2411 case Memory:
2412 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002413 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002414
2415 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002416 case NoClass:
2417 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002418
Chris Lattner52b3c132010-09-01 00:20:33 +00002419 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002420 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002421 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2422 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002423 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002424 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002425 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002426 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2427 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002428 break;
2429
2430 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002431 // is passed in the next available eightbyte chunk if the last used
2432 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002433 //
Chris Lattner57540c52011-04-15 05:22:18 +00002434 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002435 case SSEUp:
2436 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002437 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002438 break;
2439
2440 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2441 // returned together with the previous X87 value in %st0.
2442 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002443 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002444 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002445 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002446 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002447 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002448 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002449 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2450 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002451 }
Chris Lattner31faff52010-07-28 23:06:14 +00002452 break;
2453 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002454
Chris Lattner52b3c132010-09-01 00:20:33 +00002455 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002456 // known to pass in the high eightbyte of the result. We do this by forming a
2457 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002458 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002459 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002460
Chris Lattner1f3a0632010-07-29 21:42:50 +00002461 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002462}
2463
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002464ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002465 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2466 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002467 const
2468{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002469 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002470 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002471
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002472 // Check some invariants.
2473 // FIXME: Enforce these by construction.
2474 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002475 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2476
2477 neededInt = 0;
2478 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002479 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002480 switch (Lo) {
2481 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002482 if (Hi == NoClass)
2483 return ABIArgInfo::getIgnore();
2484 // If the low part is just padding, it takes no register, leave ResType
2485 // null.
2486 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2487 "Unknown missing lo part");
2488 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002489
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002490 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2491 // on the stack.
2492 case Memory:
2493
2494 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2495 // COMPLEX_X87, it is passed in memory.
2496 case X87:
2497 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002498 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002499 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002500 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002501
2502 case SSEUp:
2503 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002504 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002505
2506 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2507 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2508 // and %r9 is used.
2509 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002510 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002511
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002512 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002513 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002514
2515 // If we have a sign or zero extended integer, make sure to return Extend
2516 // so that the parameter gets the right LLVM IR attributes.
2517 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2518 // Treat an enum type as its underlying type.
2519 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2520 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002521
Chris Lattner1f3a0632010-07-29 21:42:50 +00002522 if (Ty->isIntegralOrEnumerationType() &&
2523 Ty->isPromotableIntegerType())
2524 return ABIArgInfo::getExtend();
2525 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002526
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 break;
2528
2529 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2530 // available SSE register is used, the registers are taken in the
2531 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002532 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002533 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002534 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002535 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002536 break;
2537 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002538 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002539
Craig Topper8a13c412014-05-21 05:09:00 +00002540 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002541 switch (Hi) {
2542 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002543 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002544 // which is passed in memory.
2545 case Memory:
2546 case X87:
2547 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002548 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002549
2550 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002551
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002552 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002553 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002554 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002555 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002556
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002557 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2558 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002559 break;
2560
2561 // X87Up generally doesn't occur here (long double is passed in
2562 // memory), except in situations involving unions.
2563 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002564 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002565 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002566
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002567 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2568 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002569
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002570 ++neededSSE;
2571 break;
2572
2573 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2574 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002575 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002576 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002577 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002578 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002579 break;
2580 }
2581
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002582 // If a high part was specified, merge it together with the low part. It is
2583 // known to pass in the high eightbyte of the result. We do this by forming a
2584 // first class struct aggregate with the high and low part: {low, high}
2585 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002586 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002587
Chris Lattner1f3a0632010-07-29 21:42:50 +00002588 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002589}
2590
Chris Lattner22326a12010-07-29 02:31:05 +00002591void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002592
Reid Kleckner40ca9132014-05-13 22:05:45 +00002593 if (!getCXXABI().classifyReturnType(FI))
2594 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002595
2596 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002597 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002598
2599 // If the return value is indirect, then the hidden argument is consuming one
2600 // integer register.
2601 if (FI.getReturnInfo().isIndirect())
2602 --freeIntRegs;
2603
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002604 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002605 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2606 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002607 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002608 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002609 it != ie; ++it, ++ArgNo) {
2610 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002611
Bill Wendling9987c0e2010-10-18 23:51:38 +00002612 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002613 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002614 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002615
2616 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2617 // eightbyte of an argument, the whole argument is passed on the
2618 // stack. If registers have already been assigned for some
2619 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002620 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002621 freeIntRegs -= neededInt;
2622 freeSSERegs -= neededSSE;
2623 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002624 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625 }
2626 }
2627}
2628
2629static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2630 QualType Ty,
2631 CodeGenFunction &CGF) {
2632 llvm::Value *overflow_arg_area_p =
2633 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2634 llvm::Value *overflow_arg_area =
2635 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2636
2637 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2638 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002639 // It isn't stated explicitly in the standard, but in practice we use
2640 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002641 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2642 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002643 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002644 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002645 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002646 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2647 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002648 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002649 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002650 overflow_arg_area =
2651 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2652 overflow_arg_area->getType(),
2653 "overflow_arg_area.align");
2654 }
2655
2656 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002657 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002658 llvm::Value *Res =
2659 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002660 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661
2662 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2663 // l->overflow_arg_area + sizeof(type).
2664 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2665 // an 8 byte boundary.
2666
2667 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002668 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002669 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002670 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2671 "overflow_arg_area.next");
2672 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2673
2674 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2675 return Res;
2676}
2677
2678llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2679 CodeGenFunction &CGF) const {
2680 // Assume that va_list type is correct; should be pointer to LLVM type:
2681 // struct {
2682 // i32 gp_offset;
2683 // i32 fp_offset;
2684 // i8* overflow_arg_area;
2685 // i8* reg_save_area;
2686 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002687 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002688
Chris Lattner9723d6c2010-03-11 18:19:55 +00002689 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002690 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2691 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692
2693 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2694 // in the registers. If not go to step 7.
2695 if (!neededInt && !neededSSE)
2696 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2697
2698 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2699 // general purpose registers needed to pass type and num_fp to hold
2700 // the number of floating point registers needed.
2701
2702 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2703 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2704 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2705 //
2706 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2707 // register save space).
2708
Craig Topper8a13c412014-05-21 05:09:00 +00002709 llvm::Value *InRegs = nullptr;
2710 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2711 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002712 if (neededInt) {
2713 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2714 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002715 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2716 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002717 }
2718
2719 if (neededSSE) {
2720 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2721 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2722 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002723 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2724 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002725 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2726 }
2727
2728 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2729 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2730 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2731 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2732
2733 // Emit code to load the value if it was passed in registers.
2734
2735 CGF.EmitBlock(InRegBlock);
2736
2737 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2738 // an offset of l->gp_offset and/or l->fp_offset. This may require
2739 // copying to a temporary location in case the parameter is passed
2740 // in different register classes or requires an alignment greater
2741 // than 8 for general purpose registers and 16 for XMM registers.
2742 //
2743 // FIXME: This really results in shameful code when we end up needing to
2744 // collect arguments from different places; often what should result in a
2745 // simple assembling of a structure from scattered addresses has many more
2746 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002747 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002748 llvm::Value *RegAddr =
2749 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2750 "reg_save_area");
2751 if (neededInt && neededSSE) {
2752 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002753 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002754 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002755 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2756 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002757 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002758 llvm::Type *TyLo = ST->getElementType(0);
2759 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002760 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002761 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002762 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2763 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002764 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2765 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002766 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2767 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002768 llvm::Value *V =
2769 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2770 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2771 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2772 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2773
Owen Anderson170229f2009-07-14 23:10:40 +00002774 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002775 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002776 } else if (neededInt) {
2777 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2778 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002779 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002780
2781 // Copy to a temporary if necessary to ensure the appropriate alignment.
2782 std::pair<CharUnits, CharUnits> SizeAlign =
2783 CGF.getContext().getTypeInfoInChars(Ty);
2784 uint64_t TySize = SizeAlign.first.getQuantity();
2785 unsigned TyAlign = SizeAlign.second.getQuantity();
2786 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002787 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2788 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2789 RegAddr = Tmp;
2790 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002791 } else if (neededSSE == 1) {
2792 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2793 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2794 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002795 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002796 assert(neededSSE == 2 && "Invalid number of needed registers!");
2797 // SSE registers are spaced 16 bytes apart in the register save
2798 // area, we need to collect the two eightbytes together.
2799 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002800 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002801 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002802 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002803 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002804 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2805 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2806 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002807 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2808 DblPtrTy));
2809 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2810 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2811 DblPtrTy));
2812 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2813 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2814 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002815 }
2816
2817 // AMD64-ABI 3.5.7p5: Step 5. Set:
2818 // l->gp_offset = l->gp_offset + num_gp * 8
2819 // l->fp_offset = l->fp_offset + num_fp * 16.
2820 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002821 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002822 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2823 gp_offset_p);
2824 }
2825 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002826 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002827 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2828 fp_offset_p);
2829 }
2830 CGF.EmitBranch(ContBlock);
2831
2832 // Emit code to load the value if it was passed in memory.
2833
2834 CGF.EmitBlock(InMemBlock);
2835 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2836
2837 // Return the appropriate result.
2838
2839 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002840 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002842 ResAddr->addIncoming(RegAddr, InRegBlock);
2843 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002844 return ResAddr;
2845}
2846
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002847ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002848
2849 if (Ty->isVoidType())
2850 return ABIArgInfo::getIgnore();
2851
2852 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2853 Ty = EnumTy->getDecl()->getIntegerType();
2854
2855 uint64_t Size = getContext().getTypeSize(Ty);
2856
Reid Kleckner9005f412014-05-02 00:51:20 +00002857 const RecordType *RT = Ty->getAs<RecordType>();
2858 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002859 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002860 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002861 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2862 }
2863
2864 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002865 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2866
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002867 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00002868 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002869 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2870 Size));
Reid Kleckner9005f412014-05-02 00:51:20 +00002871 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002872
Reid Klecknerec87fec2014-05-02 01:17:12 +00002873 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002874 // If the member pointer is represented by an LLVM int or ptr, pass it
2875 // directly.
2876 llvm::Type *LLTy = CGT.ConvertType(Ty);
2877 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2878 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002879 }
2880
2881 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002882 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2883 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner9005f412014-05-02 00:51:20 +00002884 if (Size > 64 || !llvm::isPowerOf2_64(Size))
2885 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002886
Reid Kleckner9005f412014-05-02 00:51:20 +00002887 // Otherwise, coerce it to a small integer.
2888 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002889 }
2890
Julien Lerouge10dcff82014-08-27 00:36:55 +00002891 // Bool type is always extended to the ABI, other builtin types are not
2892 // extended.
2893 const BuiltinType *BT = Ty->getAs<BuiltinType>();
2894 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00002895 return ABIArgInfo::getExtend();
2896
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002897 return ABIArgInfo::getDirect();
2898}
2899
2900void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002901 if (!getCXXABI().classifyReturnType(FI))
2902 FI.getReturnInfo() = classify(FI.getReturnType(), true);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002903
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002904 for (auto &I : FI.arguments())
2905 I.info = classify(I.type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002906}
2907
Chris Lattner04dc9572010-08-31 16:44:54 +00002908llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2909 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002910 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002911
Chris Lattner04dc9572010-08-31 16:44:54 +00002912 CGBuilderTy &Builder = CGF.Builder;
2913 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2914 "ap");
2915 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2916 llvm::Type *PTy =
2917 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2918 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2919
2920 uint64_t Offset =
2921 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2922 llvm::Value *NextAddr =
2923 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2924 "ap.next");
2925 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2926
2927 return AddrTyped;
2928}
Chris Lattner0cf24192010-06-28 20:05:43 +00002929
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002930namespace {
2931
Derek Schuffa2020962012-10-16 22:30:41 +00002932class NaClX86_64ABIInfo : public ABIInfo {
2933 public:
2934 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2935 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002936 void computeInfo(CGFunctionInfo &FI) const override;
2937 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2938 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00002939 private:
2940 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2941 X86_64ABIInfo NInfo; // Used for everything else.
2942};
2943
2944class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00002945 bool HasAVX;
Derek Schuffa2020962012-10-16 22:30:41 +00002946 public:
Alexander Musman09184fe2014-09-30 05:29:28 +00002947 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2948 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {
2949 }
2950 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
2951 return HasAVX ? 32 : 16;
2952 }
Derek Schuffa2020962012-10-16 22:30:41 +00002953};
2954
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002955}
2956
Derek Schuffa2020962012-10-16 22:30:41 +00002957void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2958 if (FI.getASTCallingConvention() == CC_PnaclCall)
2959 PInfo.computeInfo(FI);
2960 else
2961 NInfo.computeInfo(FI);
2962}
2963
2964llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2965 CodeGenFunction &CGF) const {
2966 // Always use the native convention; calling pnacl-style varargs functions
2967 // is unuspported.
2968 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2969}
2970
2971
John McCallea8d8bb2010-03-11 00:10:12 +00002972// PowerPC-32
2973
2974namespace {
2975class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2976public:
Chris Lattner2b037972010-07-29 02:01:43 +00002977 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002978
Craig Topper4f12f102014-03-12 06:41:41 +00002979 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00002980 // This is recovered from gcc output.
2981 return 1; // r1 is the dedicated stack pointer
2982 }
2983
2984 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002985 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00002986
2987 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
2988 return 16; // Natural alignment for Altivec vectors.
2989 }
John McCallea8d8bb2010-03-11 00:10:12 +00002990};
2991
2992}
2993
2994bool
2995PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2996 llvm::Value *Address) const {
2997 // This is calculated from the LLVM and GCC tables and verified
2998 // against gcc output. AFAIK all ABIs use the same encoding.
2999
3000 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003001
Chris Lattnerece04092012-02-07 00:39:47 +00003002 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003003 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3004 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3005 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3006
3007 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003008 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003009
3010 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003011 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003012
3013 // 64-76 are various 4-byte special-purpose registers:
3014 // 64: mq
3015 // 65: lr
3016 // 66: ctr
3017 // 67: ap
3018 // 68-75 cr0-7
3019 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003020 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003021
3022 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003023 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003024
3025 // 109: vrsave
3026 // 110: vscr
3027 // 111: spe_acc
3028 // 112: spefscr
3029 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003030 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003031
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003032 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003033}
3034
Roman Divackyd966e722012-05-09 18:22:46 +00003035// PowerPC-64
3036
3037namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003038/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3039class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003040public:
3041 enum ABIKind {
3042 ELFv1 = 0,
3043 ELFv2
3044 };
3045
3046private:
3047 static const unsigned GPRBits = 64;
3048 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003049
3050public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003051 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3052 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003053
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003054 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003055 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003056
3057 ABIArgInfo classifyReturnType(QualType RetTy) const;
3058 ABIArgInfo classifyArgumentType(QualType Ty) const;
3059
Reid Klecknere9f6a712014-10-31 17:10:41 +00003060 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3061 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3062 uint64_t Members) const override;
3063
Bill Schmidt84d37792012-10-12 19:26:17 +00003064 // TODO: We can add more logic to computeInfo to improve performance.
3065 // Example: For aggregate arguments that fit in a register, we could
3066 // use getDirectInReg (as is done below for structs containing a single
3067 // floating-point value) to avoid pushing them to memory on function
3068 // entry. This would require changing the logic in PPCISelLowering
3069 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003070 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003071 if (!getCXXABI().classifyReturnType(FI))
3072 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003073 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003074 // We rely on the default argument classification for the most part.
3075 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003076 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003077 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003078 if (T) {
3079 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003080 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3081 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003082 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003083 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003084 continue;
3085 }
3086 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003087 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003088 }
3089 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003090
Craig Topper4f12f102014-03-12 06:41:41 +00003091 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3092 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003093};
3094
3095class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3096public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003097 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3098 PPC64_SVR4_ABIInfo::ABIKind Kind)
3099 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003100
Craig Topper4f12f102014-03-12 06:41:41 +00003101 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003102 // This is recovered from gcc output.
3103 return 1; // r1 is the dedicated stack pointer
3104 }
3105
3106 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003107 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003108
3109 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3110 return 16; // Natural alignment for Altivec and VSX vectors.
3111 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003112};
3113
Roman Divackyd966e722012-05-09 18:22:46 +00003114class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3115public:
3116 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3117
Craig Topper4f12f102014-03-12 06:41:41 +00003118 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003119 // This is recovered from gcc output.
3120 return 1; // r1 is the dedicated stack pointer
3121 }
3122
3123 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003124 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003125
3126 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3127 return 16; // Natural alignment for Altivec vectors.
3128 }
Roman Divackyd966e722012-05-09 18:22:46 +00003129};
3130
3131}
3132
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003133// Return true if the ABI requires Ty to be passed sign- or zero-
3134// extended to 64 bits.
3135bool
3136PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3137 // Treat an enum type as its underlying type.
3138 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3139 Ty = EnumTy->getDecl()->getIntegerType();
3140
3141 // Promotable integer types are required to be promoted by the ABI.
3142 if (Ty->isPromotableIntegerType())
3143 return true;
3144
3145 // In addition to the usual promotable integer types, we also need to
3146 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3147 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3148 switch (BT->getKind()) {
3149 case BuiltinType::Int:
3150 case BuiltinType::UInt:
3151 return true;
3152 default:
3153 break;
3154 }
3155
3156 return false;
3157}
3158
Ulrich Weigand581badc2014-07-10 17:20:07 +00003159/// isAlignedParamType - Determine whether a type requires 16-byte
3160/// alignment in the parameter area.
3161bool
3162PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3163 // Complex types are passed just like their elements.
3164 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3165 Ty = CTy->getElementType();
3166
3167 // Only vector types of size 16 bytes need alignment (larger types are
3168 // passed via reference, smaller types are not aligned).
3169 if (Ty->isVectorType())
3170 return getContext().getTypeSize(Ty) == 128;
3171
3172 // For single-element float/vector structs, we consider the whole type
3173 // to have the same alignment requirements as its single element.
3174 const Type *AlignAsType = nullptr;
3175 const Type *EltType = isSingleElementStruct(Ty, getContext());
3176 if (EltType) {
3177 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3178 if ((EltType->isVectorType() &&
3179 getContext().getTypeSize(EltType) == 128) ||
3180 (BT && BT->isFloatingPoint()))
3181 AlignAsType = EltType;
3182 }
3183
Ulrich Weigandb7122372014-07-21 00:48:09 +00003184 // Likewise for ELFv2 homogeneous aggregates.
3185 const Type *Base = nullptr;
3186 uint64_t Members = 0;
3187 if (!AlignAsType && Kind == ELFv2 &&
3188 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3189 AlignAsType = Base;
3190
Ulrich Weigand581badc2014-07-10 17:20:07 +00003191 // With special case aggregates, only vector base types need alignment.
3192 if (AlignAsType)
3193 return AlignAsType->isVectorType();
3194
3195 // Otherwise, we only need alignment for any aggregate type that
3196 // has an alignment requirement of >= 16 bytes.
3197 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3198 return true;
3199
3200 return false;
3201}
3202
Ulrich Weigandb7122372014-07-21 00:48:09 +00003203/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3204/// aggregate. Base is set to the base element type, and Members is set
3205/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003206bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3207 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003208 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3209 uint64_t NElements = AT->getSize().getZExtValue();
3210 if (NElements == 0)
3211 return false;
3212 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3213 return false;
3214 Members *= NElements;
3215 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3216 const RecordDecl *RD = RT->getDecl();
3217 if (RD->hasFlexibleArrayMember())
3218 return false;
3219
3220 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003221
3222 // If this is a C++ record, check the bases first.
3223 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3224 for (const auto &I : CXXRD->bases()) {
3225 // Ignore empty records.
3226 if (isEmptyRecord(getContext(), I.getType(), true))
3227 continue;
3228
3229 uint64_t FldMembers;
3230 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3231 return false;
3232
3233 Members += FldMembers;
3234 }
3235 }
3236
Ulrich Weigandb7122372014-07-21 00:48:09 +00003237 for (const auto *FD : RD->fields()) {
3238 // Ignore (non-zero arrays of) empty records.
3239 QualType FT = FD->getType();
3240 while (const ConstantArrayType *AT =
3241 getContext().getAsConstantArrayType(FT)) {
3242 if (AT->getSize().getZExtValue() == 0)
3243 return false;
3244 FT = AT->getElementType();
3245 }
3246 if (isEmptyRecord(getContext(), FT, true))
3247 continue;
3248
3249 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3250 if (getContext().getLangOpts().CPlusPlus &&
3251 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3252 continue;
3253
3254 uint64_t FldMembers;
3255 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3256 return false;
3257
3258 Members = (RD->isUnion() ?
3259 std::max(Members, FldMembers) : Members + FldMembers);
3260 }
3261
3262 if (!Base)
3263 return false;
3264
3265 // Ensure there is no padding.
3266 if (getContext().getTypeSize(Base) * Members !=
3267 getContext().getTypeSize(Ty))
3268 return false;
3269 } else {
3270 Members = 1;
3271 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3272 Members = 2;
3273 Ty = CT->getElementType();
3274 }
3275
Reid Klecknere9f6a712014-10-31 17:10:41 +00003276 // Most ABIs only support float, double, and some vector type widths.
3277 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003278 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003279
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 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003291 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3292}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003293
Reid Klecknere9f6a712014-10-31 17:10:41 +00003294bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3295 // Homogeneous aggregates for ELFv2 must have base types of float,
3296 // double, long double, or 128-bit vectors.
3297 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3298 if (BT->getKind() == BuiltinType::Float ||
3299 BT->getKind() == BuiltinType::Double ||
3300 BT->getKind() == BuiltinType::LongDouble)
3301 return true;
3302 }
3303 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3304 if (getContext().getTypeSize(VT) == 128)
3305 return true;
3306 }
3307 return false;
3308}
3309
3310bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3311 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003312 // Vector types require one register, floating point types require one
3313 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003314 uint32_t NumRegs =
3315 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003316
3317 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003318 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003319}
3320
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003321ABIArgInfo
3322PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00003323 if (Ty->isAnyComplexType())
3324 return ABIArgInfo::getDirect();
3325
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003326 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3327 // or via reference (larger than 16 bytes).
3328 if (Ty->isVectorType()) {
3329 uint64_t Size = getContext().getTypeSize(Ty);
3330 if (Size > 128)
3331 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3332 else if (Size < 128) {
3333 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3334 return ABIArgInfo::getDirect(CoerceTy);
3335 }
3336 }
3337
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003338 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003339 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003340 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003341
Ulrich Weigand581badc2014-07-10 17:20:07 +00003342 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3343 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003344
3345 // ELFv2 homogeneous aggregates are passed as array types.
3346 const Type *Base = nullptr;
3347 uint64_t Members = 0;
3348 if (Kind == ELFv2 &&
3349 isHomogeneousAggregate(Ty, Base, Members)) {
3350 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3351 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3352 return ABIArgInfo::getDirect(CoerceTy);
3353 }
3354
Ulrich Weigand601957f2014-07-21 00:56:36 +00003355 // If an aggregate may end up fully in registers, we do not
3356 // use the ByVal method, but pass the aggregate as array.
3357 // This is usually beneficial since we avoid forcing the
3358 // back-end to store the argument to memory.
3359 uint64_t Bits = getContext().getTypeSize(Ty);
3360 if (Bits > 0 && Bits <= 8 * GPRBits) {
3361 llvm::Type *CoerceTy;
3362
3363 // Types up to 8 bytes are passed as integer type (which will be
3364 // properly aligned in the argument save area doubleword).
3365 if (Bits <= GPRBits)
3366 CoerceTy = llvm::IntegerType::get(getVMContext(),
3367 llvm::RoundUpToAlignment(Bits, 8));
3368 // Larger types are passed as arrays, with the base type selected
3369 // according to the required alignment in the save area.
3370 else {
3371 uint64_t RegBits = ABIAlign * 8;
3372 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3373 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3374 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3375 }
3376
3377 return ABIArgInfo::getDirect(CoerceTy);
3378 }
3379
Ulrich Weigandb7122372014-07-21 00:48:09 +00003380 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003381 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3382 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003383 }
3384
3385 return (isPromotableTypeForABI(Ty) ?
3386 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3387}
3388
3389ABIArgInfo
3390PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3391 if (RetTy->isVoidType())
3392 return ABIArgInfo::getIgnore();
3393
Bill Schmidta3d121c2012-12-17 04:20:17 +00003394 if (RetTy->isAnyComplexType())
3395 return ABIArgInfo::getDirect();
3396
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003397 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3398 // or via reference (larger than 16 bytes).
3399 if (RetTy->isVectorType()) {
3400 uint64_t Size = getContext().getTypeSize(RetTy);
3401 if (Size > 128)
3402 return ABIArgInfo::getIndirect(0);
3403 else if (Size < 128) {
3404 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3405 return ABIArgInfo::getDirect(CoerceTy);
3406 }
3407 }
3408
Ulrich Weigandb7122372014-07-21 00:48:09 +00003409 if (isAggregateTypeForABI(RetTy)) {
3410 // ELFv2 homogeneous aggregates are returned as array types.
3411 const Type *Base = nullptr;
3412 uint64_t Members = 0;
3413 if (Kind == ELFv2 &&
3414 isHomogeneousAggregate(RetTy, Base, Members)) {
3415 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3416 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3417 return ABIArgInfo::getDirect(CoerceTy);
3418 }
3419
3420 // ELFv2 small aggregates are returned in up to two registers.
3421 uint64_t Bits = getContext().getTypeSize(RetTy);
3422 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3423 if (Bits == 0)
3424 return ABIArgInfo::getIgnore();
3425
3426 llvm::Type *CoerceTy;
3427 if (Bits > GPRBits) {
3428 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3429 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3430 } else
3431 CoerceTy = llvm::IntegerType::get(getVMContext(),
3432 llvm::RoundUpToAlignment(Bits, 8));
3433 return ABIArgInfo::getDirect(CoerceTy);
3434 }
3435
3436 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003437 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003438 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003439
3440 return (isPromotableTypeForABI(RetTy) ?
3441 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3442}
3443
Bill Schmidt25cb3492012-10-03 19:18:57 +00003444// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3445llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3446 QualType Ty,
3447 CodeGenFunction &CGF) const {
3448 llvm::Type *BP = CGF.Int8PtrTy;
3449 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3450
3451 CGBuilderTy &Builder = CGF.Builder;
3452 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3453 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3454
Ulrich Weigand581badc2014-07-10 17:20:07 +00003455 // Handle types that require 16-byte alignment in the parameter save area.
3456 if (isAlignedParamType(Ty)) {
3457 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3458 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3459 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3460 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3461 }
3462
Bill Schmidt924c4782013-01-14 17:45:36 +00003463 // Update the va_list pointer. The pointer should be bumped by the
3464 // size of the object. We can trust getTypeSize() except for a complex
3465 // type whose base type is smaller than a doubleword. For these, the
3466 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003467 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003468 QualType BaseTy;
3469 unsigned CplxBaseSize = 0;
3470
3471 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3472 BaseTy = CTy->getElementType();
3473 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3474 if (CplxBaseSize < 8)
3475 SizeInBytes = 16;
3476 }
3477
Bill Schmidt25cb3492012-10-03 19:18:57 +00003478 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3479 llvm::Value *NextAddr =
3480 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3481 "ap.next");
3482 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3483
Bill Schmidt924c4782013-01-14 17:45:36 +00003484 // If we have a complex type and the base type is smaller than 8 bytes,
3485 // the ABI calls for the real and imaginary parts to be right-adjusted
3486 // in separate doublewords. However, Clang expects us to produce a
3487 // pointer to a structure with the two parts packed tightly. So generate
3488 // loads of the real and imaginary parts relative to the va_list pointer,
3489 // and store them to a temporary structure.
3490 if (CplxBaseSize && CplxBaseSize < 8) {
3491 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3492 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003493 if (CGF.CGM.getDataLayout().isBigEndian()) {
3494 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3495 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3496 } else {
3497 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3498 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003499 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3500 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3501 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3502 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3503 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3504 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3505 "vacplx");
3506 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3507 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3508 Builder.CreateStore(Real, RealPtr, false);
3509 Builder.CreateStore(Imag, ImagPtr, false);
3510 return Ptr;
3511 }
3512
Bill Schmidt25cb3492012-10-03 19:18:57 +00003513 // If the argument is smaller than 8 bytes, it is right-adjusted in
3514 // its doubleword slot. Adjust the pointer to pick it up from the
3515 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003516 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003517 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3518 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3519 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3520 }
3521
3522 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3523 return Builder.CreateBitCast(Addr, PTy);
3524}
3525
3526static bool
3527PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3528 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003529 // This is calculated from the LLVM and GCC tables and verified
3530 // against gcc output. AFAIK all ABIs use the same encoding.
3531
3532 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3533
3534 llvm::IntegerType *i8 = CGF.Int8Ty;
3535 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3536 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3537 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3538
3539 // 0-31: r0-31, the 8-byte general-purpose registers
3540 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3541
3542 // 32-63: fp0-31, the 8-byte floating-point registers
3543 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3544
3545 // 64-76 are various 4-byte special-purpose registers:
3546 // 64: mq
3547 // 65: lr
3548 // 66: ctr
3549 // 67: ap
3550 // 68-75 cr0-7
3551 // 76: xer
3552 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3553
3554 // 77-108: v0-31, the 16-byte vector registers
3555 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3556
3557 // 109: vrsave
3558 // 110: vscr
3559 // 111: spe_acc
3560 // 112: spefscr
3561 // 113: sfp
3562 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3563
3564 return false;
3565}
John McCallea8d8bb2010-03-11 00:10:12 +00003566
Bill Schmidt25cb3492012-10-03 19:18:57 +00003567bool
3568PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3569 CodeGen::CodeGenFunction &CGF,
3570 llvm::Value *Address) const {
3571
3572 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3573}
3574
3575bool
3576PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3577 llvm::Value *Address) const {
3578
3579 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3580}
3581
Chris Lattner0cf24192010-06-28 20:05:43 +00003582//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003583// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003584//===----------------------------------------------------------------------===//
3585
3586namespace {
3587
Tim Northover573cbee2014-05-24 12:52:07 +00003588class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003589public:
3590 enum ABIKind {
3591 AAPCS = 0,
3592 DarwinPCS
3593 };
3594
3595private:
3596 ABIKind Kind;
3597
3598public:
Tim Northover573cbee2014-05-24 12:52:07 +00003599 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003600
3601private:
3602 ABIKind getABIKind() const { return Kind; }
3603 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3604
3605 ABIArgInfo classifyReturnType(QualType RetTy) const;
3606 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3607 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003608 bool &IsSmallAggr, bool IsNamedArg) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003609 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3610 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3611 uint64_t Members) const override;
3612
Tim Northovera2ee4332014-03-29 15:09:45 +00003613 bool isIllegalVectorType(QualType Ty) const;
3614
3615 virtual void computeInfo(CGFunctionInfo &FI) const {
3616 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3617 // number of SIMD and Floating-point registers allocated so far.
3618 // If the argument is an HFA or an HVA and there are sufficient unallocated
3619 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3620 // and Floating-point Registers (with one register per member of the HFA or
3621 // HVA). Otherwise, the NSRN is set to 8.
3622 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003623
Tim Northovera2ee4332014-03-29 15:09:45 +00003624 // To correctly handle small aggregates, we need to keep track of the number
3625 // of GPRs allocated so far. If the small aggregate can't all fit into
3626 // registers, it will be on stack. We don't allow the aggregate to be
3627 // partially in registers.
3628 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003629
3630 // Find the number of named arguments. Variadic arguments get special
3631 // treatment with the Darwin ABI.
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003632 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Bob Wilson373af732014-04-21 01:23:39 +00003633
Reid Kleckner40ca9132014-05-13 22:05:45 +00003634 if (!getCXXABI().classifyReturnType(FI))
3635 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003636 unsigned ArgNo = 0;
Tim Northovera2ee4332014-03-29 15:09:45 +00003637 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003638 it != ie; ++it, ++ArgNo) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003639 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3640 bool IsHA = false, IsSmallAggr = false;
3641 const unsigned NumVFPs = 8;
3642 const unsigned NumGPRs = 8;
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003643 bool IsNamedArg = ArgNo < NumRequiredArgs;
Tim Northovera2ee4332014-03-29 15:09:45 +00003644 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003645 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003646
3647 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3648 // as sequences of floats since they'll get "holes" inserted as
3649 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003650 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3651 getContext().getTypeAlign(it->type) < 64) {
3652 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3653 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003654
Tim Northover07f16242014-04-18 10:47:44 +00003655 llvm::Type *CoerceTy = llvm::ArrayType::get(
3656 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3657 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003658 }
3659
Tim Northovera2ee4332014-03-29 15:09:45 +00003660 // If we do not have enough VFP registers for the HA, any VFP registers
3661 // that are unallocated are marked as unavailable. To achieve this, we add
3662 // padding of (NumVFPs - PreAllocation) floats.
3663 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3664 llvm::Type *PaddingTy = llvm::ArrayType::get(
3665 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003666 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003667 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003668
Tim Northovera2ee4332014-03-29 15:09:45 +00003669 // If we do not have enough GPRs for the small aggregate, any GPR regs
3670 // that are unallocated are marked as unavailable.
3671 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3672 llvm::Type *PaddingTy = llvm::ArrayType::get(
3673 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3674 it->info =
3675 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3676 }
3677 }
3678 }
3679
3680 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3681 CodeGenFunction &CGF) const;
3682
3683 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3684 CodeGenFunction &CGF) const;
3685
3686 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3687 CodeGenFunction &CGF) const {
3688 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3689 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3690 }
3691};
3692
Tim Northover573cbee2014-05-24 12:52:07 +00003693class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003694public:
Tim Northover573cbee2014-05-24 12:52:07 +00003695 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3696 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003697
3698 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3699 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3700 }
3701
3702 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3703
3704 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3705};
3706}
3707
Tim Northover573cbee2014-05-24 12:52:07 +00003708ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3709 unsigned &AllocatedVFP,
3710 bool &IsHA,
3711 unsigned &AllocatedGPR,
3712 bool &IsSmallAggr,
3713 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003714 // Handle illegal vector types here.
3715 if (isIllegalVectorType(Ty)) {
3716 uint64_t Size = getContext().getTypeSize(Ty);
3717 if (Size <= 32) {
3718 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3719 AllocatedGPR++;
3720 return ABIArgInfo::getDirect(ResType);
3721 }
3722 if (Size == 64) {
3723 llvm::Type *ResType =
3724 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3725 AllocatedVFP++;
3726 return ABIArgInfo::getDirect(ResType);
3727 }
3728 if (Size == 128) {
3729 llvm::Type *ResType =
3730 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3731 AllocatedVFP++;
3732 return ABIArgInfo::getDirect(ResType);
3733 }
3734 AllocatedGPR++;
3735 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3736 }
3737 if (Ty->isVectorType())
3738 // Size of a legal vector should be either 64 or 128.
3739 AllocatedVFP++;
3740 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3741 if (BT->getKind() == BuiltinType::Half ||
3742 BT->getKind() == BuiltinType::Float ||
3743 BT->getKind() == BuiltinType::Double ||
3744 BT->getKind() == BuiltinType::LongDouble)
3745 AllocatedVFP++;
3746 }
3747
3748 if (!isAggregateTypeForABI(Ty)) {
3749 // Treat an enum type as its underlying type.
3750 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3751 Ty = EnumTy->getDecl()->getIntegerType();
3752
3753 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003754 unsigned Alignment = getContext().getTypeAlign(Ty);
3755 if (!isDarwinPCS() && Alignment > 64)
3756 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3757
Tim Northovera2ee4332014-03-29 15:09:45 +00003758 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3759 AllocatedGPR += RegsNeeded;
3760 }
3761 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3762 ? ABIArgInfo::getExtend()
3763 : ABIArgInfo::getDirect());
3764 }
3765
3766 // Structures with either a non-trivial destructor or a non-trivial
3767 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003768 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003769 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003770 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3771 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003772 }
3773
3774 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3775 // elsewhere for GNU compatibility.
3776 if (isEmptyRecord(getContext(), Ty, true)) {
3777 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3778 return ABIArgInfo::getIgnore();
3779
3780 ++AllocatedGPR;
3781 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3782 }
3783
3784 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003785 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003786 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003787 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003788 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003789 if (!IsNamedArg && isDarwinPCS()) {
3790 // With the Darwin ABI, variadic arguments are always passed on the stack
3791 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3792 uint64_t Size = getContext().getTypeSize(Ty);
3793 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3794 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3795 }
3796 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003797 return ABIArgInfo::getExpand();
3798 }
3799
3800 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3801 uint64_t Size = getContext().getTypeSize(Ty);
3802 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003803 unsigned Alignment = getContext().getTypeAlign(Ty);
3804 if (!isDarwinPCS() && Alignment > 64)
3805 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3806
Tim Northovera2ee4332014-03-29 15:09:45 +00003807 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3808 AllocatedGPR += Size / 64;
3809 IsSmallAggr = true;
3810 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3811 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003812 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003813 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3814 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3815 }
3816 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3817 }
3818
3819 AllocatedGPR++;
3820 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3821}
3822
Tim Northover573cbee2014-05-24 12:52:07 +00003823ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003824 if (RetTy->isVoidType())
3825 return ABIArgInfo::getIgnore();
3826
3827 // Large vector types should be returned via memory.
3828 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3829 return ABIArgInfo::getIndirect(0);
3830
3831 if (!isAggregateTypeForABI(RetTy)) {
3832 // Treat an enum type as its underlying type.
3833 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3834 RetTy = EnumTy->getDecl()->getIntegerType();
3835
Tim Northover4dab6982014-04-18 13:46:08 +00003836 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3837 ? ABIArgInfo::getExtend()
3838 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003839 }
3840
Tim Northovera2ee4332014-03-29 15:09:45 +00003841 if (isEmptyRecord(getContext(), RetTy, true))
3842 return ABIArgInfo::getIgnore();
3843
Craig Topper8a13c412014-05-21 05:09:00 +00003844 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003845 uint64_t Members = 0;
3846 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00003847 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3848 return ABIArgInfo::getDirect();
3849
3850 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3851 uint64_t Size = getContext().getTypeSize(RetTy);
3852 if (Size <= 128) {
3853 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3854 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3855 }
3856
3857 return ABIArgInfo::getIndirect(0);
3858}
3859
Tim Northover573cbee2014-05-24 12:52:07 +00003860/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3861bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003862 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3863 // Check whether VT is legal.
3864 unsigned NumElements = VT->getNumElements();
3865 uint64_t Size = getContext().getTypeSize(VT);
3866 // NumElements should be power of 2 between 1 and 16.
3867 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3868 return true;
3869 return Size != 64 && (Size != 128 || NumElements == 1);
3870 }
3871 return false;
3872}
3873
Reid Klecknere9f6a712014-10-31 17:10:41 +00003874bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3875 // Homogeneous aggregates for AAPCS64 must have base types of a floating
3876 // point type or a short-vector type. This is the same as the 32-bit ABI,
3877 // but with the difference that any floating-point type is allowed,
3878 // including __fp16.
3879 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3880 if (BT->isFloatingPoint())
3881 return true;
3882 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3883 unsigned VecSize = getContext().getTypeSize(VT);
3884 if (VecSize == 64 || VecSize == 128)
3885 return true;
3886 }
3887 return false;
3888}
3889
3890bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
3891 uint64_t Members) const {
3892 return Members <= 4;
3893}
3894
3895llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3896 CodeGenFunction &CGF) const {
3897 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
3898 bool IsHA = false, IsSmallAggr = false;
3899 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
3900 IsSmallAggr, false /*IsNamedArg*/);
3901 bool IsIndirect = AI.isIndirect();
3902
Tim Northovera2ee4332014-03-29 15:09:45 +00003903 // The AArch64 va_list type and handling is specified in the Procedure Call
3904 // Standard, section B.4:
3905 //
3906 // struct {
3907 // void *__stack;
3908 // void *__gr_top;
3909 // void *__vr_top;
3910 // int __gr_offs;
3911 // int __vr_offs;
3912 // };
3913
3914 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3915 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3916 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3917 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3918 auto &Ctx = CGF.getContext();
3919
Craig Topper8a13c412014-05-21 05:09:00 +00003920 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003921 int reg_top_index;
3922 int RegSize;
3923 if (AllocatedGPR) {
3924 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3925 // 3 is the field number of __gr_offs
3926 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3927 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3928 reg_top_index = 1; // field number for __gr_top
3929 RegSize = 8 * AllocatedGPR;
3930 } else {
3931 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3932 // 4 is the field number of __vr_offs.
3933 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3934 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3935 reg_top_index = 2; // field number for __vr_top
3936 RegSize = 16 * AllocatedVFP;
3937 }
3938
3939 //=======================================
3940 // Find out where argument was passed
3941 //=======================================
3942
3943 // If reg_offs >= 0 we're already using the stack for this type of
3944 // argument. We don't want to keep updating reg_offs (in case it overflows,
3945 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3946 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00003947 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003948 UsingStack = CGF.Builder.CreateICmpSGE(
3949 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3950
3951 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3952
3953 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00003954 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00003955 CGF.EmitBlock(MaybeRegBlock);
3956
3957 // Integer arguments may need to correct register alignment (for example a
3958 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3959 // align __gr_offs to calculate the potential address.
3960 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3961 int Align = Ctx.getTypeAlign(Ty) / 8;
3962
3963 reg_offs = CGF.Builder.CreateAdd(
3964 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3965 "align_regoffs");
3966 reg_offs = CGF.Builder.CreateAnd(
3967 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3968 "aligned_regoffs");
3969 }
3970
3971 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00003972 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003973 NewOffset = CGF.Builder.CreateAdd(
3974 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3975 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3976
3977 // Now we're in a position to decide whether this argument really was in
3978 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00003979 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003980 InRegs = CGF.Builder.CreateICmpSLE(
3981 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3982
3983 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3984
3985 //=======================================
3986 // Argument was in registers
3987 //=======================================
3988
3989 // Now we emit the code for if the argument was originally passed in
3990 // registers. First start the appropriate block:
3991 CGF.EmitBlock(InRegBlock);
3992
Craig Topper8a13c412014-05-21 05:09:00 +00003993 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003994 reg_top_p =
3995 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3996 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3997 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00003998 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003999 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4000
4001 if (IsIndirect) {
4002 // If it's been passed indirectly (actually a struct), whatever we find from
4003 // stored registers or on the stack will actually be a struct **.
4004 MemTy = llvm::PointerType::getUnqual(MemTy);
4005 }
4006
Craig Topper8a13c412014-05-21 05:09:00 +00004007 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004008 uint64_t NumMembers = 0;
4009 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004010 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004011 // Homogeneous aggregates passed in registers will have their elements split
4012 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4013 // qN+1, ...). We reload and store into a temporary local variable
4014 // contiguously.
4015 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4016 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4017 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4018 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4019 int Offset = 0;
4020
4021 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4022 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4023 for (unsigned i = 0; i < NumMembers; ++i) {
4024 llvm::Value *BaseOffset =
4025 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4026 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4027 LoadAddr = CGF.Builder.CreateBitCast(
4028 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4029 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4030
4031 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4032 CGF.Builder.CreateStore(Elem, StoreAddr);
4033 }
4034
4035 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4036 } else {
4037 // Otherwise the object is contiguous in memory
4038 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004039 if (CGF.CGM.getDataLayout().isBigEndian() &&
4040 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004041 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4042 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4043 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4044
4045 BaseAddr = CGF.Builder.CreateAdd(
4046 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4047
4048 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4049 }
4050
4051 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4052 }
4053
4054 CGF.EmitBranch(ContBlock);
4055
4056 //=======================================
4057 // Argument was on the stack
4058 //=======================================
4059 CGF.EmitBlock(OnStackBlock);
4060
Craig Topper8a13c412014-05-21 05:09:00 +00004061 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004062 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4063 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4064
4065 // Again, stack arguments may need realigmnent. In this case both integer and
4066 // floating-point ones might be affected.
4067 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4068 int Align = Ctx.getTypeAlign(Ty) / 8;
4069
4070 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4071
4072 OnStackAddr = CGF.Builder.CreateAdd(
4073 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4074 "align_stack");
4075 OnStackAddr = CGF.Builder.CreateAnd(
4076 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4077 "align_stack");
4078
4079 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4080 }
4081
4082 uint64_t StackSize;
4083 if (IsIndirect)
4084 StackSize = 8;
4085 else
4086 StackSize = Ctx.getTypeSize(Ty) / 8;
4087
4088 // All stack slots are 8 bytes
4089 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4090
4091 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4092 llvm::Value *NewStack =
4093 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4094
4095 // Write the new value of __stack for the next call to va_arg
4096 CGF.Builder.CreateStore(NewStack, stack_p);
4097
4098 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4099 Ctx.getTypeSize(Ty) < 64) {
4100 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4101 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4102
4103 OnStackAddr = CGF.Builder.CreateAdd(
4104 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4105
4106 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4107 }
4108
4109 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4110
4111 CGF.EmitBranch(ContBlock);
4112
4113 //=======================================
4114 // Tidy up
4115 //=======================================
4116 CGF.EmitBlock(ContBlock);
4117
4118 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4119 ResAddr->addIncoming(RegAddr, InRegBlock);
4120 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4121
4122 if (IsIndirect)
4123 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4124
4125 return ResAddr;
4126}
4127
Tim Northover573cbee2014-05-24 12:52:07 +00004128llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004129 CodeGenFunction &CGF) const {
4130 // We do not support va_arg for aggregates or illegal vector types.
4131 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4132 // other cases.
4133 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004134 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004135
4136 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4137 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4138
Craig Topper8a13c412014-05-21 05:09:00 +00004139 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004140 uint64_t Members = 0;
4141 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004142
4143 bool isIndirect = false;
4144 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4145 // be passed indirectly.
4146 if (Size > 16 && !isHA) {
4147 isIndirect = true;
4148 Size = 8;
4149 Align = 8;
4150 }
4151
4152 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4153 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4154
4155 CGBuilderTy &Builder = CGF.Builder;
4156 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4157 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4158
4159 if (isEmptyRecord(getContext(), Ty, true)) {
4160 // These are ignored for parameter passing purposes.
4161 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4162 return Builder.CreateBitCast(Addr, PTy);
4163 }
4164
4165 const uint64_t MinABIAlign = 8;
4166 if (Align > MinABIAlign) {
4167 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4168 Addr = Builder.CreateGEP(Addr, Offset);
4169 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4170 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4171 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4172 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4173 }
4174
4175 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4176 llvm::Value *NextAddr = Builder.CreateGEP(
4177 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4178 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4179
4180 if (isIndirect)
4181 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4182 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4183 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4184
4185 return AddrTyped;
4186}
4187
4188//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004189// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004190//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004191
4192namespace {
4193
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004194class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004195public:
4196 enum ABIKind {
4197 APCS = 0,
4198 AAPCS = 1,
4199 AAPCS_VFP
4200 };
4201
4202private:
4203 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004204 mutable int VFPRegs[16];
4205 const unsigned NumVFPs;
4206 const unsigned NumGPRs;
4207 mutable unsigned AllocatedGPRs;
4208 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004209
4210public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004211 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4212 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00004213 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004214 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004215 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004216
John McCall3480ef22011-08-30 01:42:09 +00004217 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004218 switch (getTarget().getTriple().getEnvironment()) {
4219 case llvm::Triple::Android:
4220 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004221 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004222 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004223 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004224 return true;
4225 default:
4226 return false;
4227 }
John McCall3480ef22011-08-30 01:42:09 +00004228 }
4229
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004230 bool isEABIHF() const {
4231 switch (getTarget().getTriple().getEnvironment()) {
4232 case llvm::Triple::EABIHF:
4233 case llvm::Triple::GNUEABIHF:
4234 return true;
4235 default:
4236 return false;
4237 }
4238 }
4239
Daniel Dunbar020daa92009-09-12 01:00:39 +00004240 ABIKind getABIKind() const { return Kind; }
4241
Tim Northovera484bc02013-10-01 14:34:25 +00004242private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004243 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004244 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004245 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004246 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004247
Reid Klecknere9f6a712014-10-31 17:10:41 +00004248 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4249 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4250 uint64_t Members) const override;
4251
Craig Topper4f12f102014-03-12 06:41:41 +00004252 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004253
Craig Topper4f12f102014-03-12 06:41:41 +00004254 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4255 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004256
4257 llvm::CallingConv::ID getLLVMDefaultCC() const;
4258 llvm::CallingConv::ID getABIDefaultCC() const;
4259 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004260
4261 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4262 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4263 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004264};
4265
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004266class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4267public:
Chris Lattner2b037972010-07-29 02:01:43 +00004268 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4269 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004270
John McCall3480ef22011-08-30 01:42:09 +00004271 const ARMABIInfo &getABIInfo() const {
4272 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4273 }
4274
Craig Topper4f12f102014-03-12 06:41:41 +00004275 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004276 return 13;
4277 }
Roman Divackyc1617352011-05-18 19:36:54 +00004278
Craig Topper4f12f102014-03-12 06:41:41 +00004279 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004280 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4281 }
4282
Roman Divackyc1617352011-05-18 19:36:54 +00004283 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004284 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004285 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004286
4287 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004288 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004289 return false;
4290 }
John McCall3480ef22011-08-30 01:42:09 +00004291
Craig Topper4f12f102014-03-12 06:41:41 +00004292 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004293 if (getABIInfo().isEABI()) return 88;
4294 return TargetCodeGenInfo::getSizeOfUnwindException();
4295 }
Tim Northovera484bc02013-10-01 14:34:25 +00004296
4297 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004298 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004299 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4300 if (!FD)
4301 return;
4302
4303 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4304 if (!Attr)
4305 return;
4306
4307 const char *Kind;
4308 switch (Attr->getInterrupt()) {
4309 case ARMInterruptAttr::Generic: Kind = ""; break;
4310 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4311 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4312 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4313 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4314 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4315 }
4316
4317 llvm::Function *Fn = cast<llvm::Function>(GV);
4318
4319 Fn->addFnAttr("interrupt", Kind);
4320
4321 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4322 return;
4323
4324 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4325 // however this is not necessarily true on taking any interrupt. Instruct
4326 // the backend to perform a realignment as part of the function prologue.
4327 llvm::AttrBuilder B;
4328 B.addStackAlignmentAttr(8);
4329 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4330 llvm::AttributeSet::get(CGM.getLLVMContext(),
4331 llvm::AttributeSet::FunctionIndex,
4332 B));
4333 }
4334
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004335};
4336
Daniel Dunbard59655c2009-09-12 00:59:49 +00004337}
4338
Chris Lattner22326a12010-07-29 02:31:05 +00004339void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004340 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004341 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004342 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4343 // VFP registers of the appropriate type unallocated then the argument is
4344 // allocated to the lowest-numbered sequence of such registers.
4345 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4346 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004347 resetAllocatedRegs();
4348
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004349 const bool isAAPCS_VFP =
4350 getABIKind() == ARMABIInfo::AAPCS_VFP && !FI.isVariadic();
4351
Reid Kleckner40ca9132014-05-13 22:05:45 +00004352 if (getCXXABI().classifyReturnType(FI)) {
4353 if (FI.getReturnInfo().isIndirect())
4354 markAllocatedGPRs(1, 1);
4355 } else {
4356 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4357 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004358 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004359 unsigned PreAllocationVFPs = AllocatedVFPs;
4360 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004361 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004362 // 6.1.2.3 There is one VFP co-processor register class using registers
4363 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004364 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004365
4366 // If we have allocated some arguments onto the stack (due to running
4367 // out of VFP registers), we cannot split an argument between GPRs and
4368 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004369 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004370 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4371 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004372 // We do not have to do this if the argument is being passed ByVal, as the
4373 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004374 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004375 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4376 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4377 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004378 llvm::Type *PaddingTy = llvm::ArrayType::get(
4379 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004380 if (I.info.canHaveCoerceToType()) {
4381 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004382 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004383 } else {
4384 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004385 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004386 }
Manman Ren2a523d82012-10-30 23:21:41 +00004387 }
4388 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004389
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004390 // Always honor user-specified calling convention.
4391 if (FI.getCallingConvention() != llvm::CallingConv::C)
4392 return;
4393
John McCall882987f2013-02-28 19:01:20 +00004394 llvm::CallingConv::ID cc = getRuntimeCC();
4395 if (cc != llvm::CallingConv::C)
4396 FI.setEffectiveCallingConvention(cc);
4397}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004398
John McCall882987f2013-02-28 19:01:20 +00004399/// Return the default calling convention that LLVM will use.
4400llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4401 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004402 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004403 return llvm::CallingConv::ARM_AAPCS_VFP;
4404 else if (isEABI())
4405 return llvm::CallingConv::ARM_AAPCS;
4406 else
4407 return llvm::CallingConv::ARM_APCS;
4408}
4409
4410/// Return the calling convention that our ABI would like us to use
4411/// as the C calling convention.
4412llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004413 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004414 case APCS: return llvm::CallingConv::ARM_APCS;
4415 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4416 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004417 }
John McCall882987f2013-02-28 19:01:20 +00004418 llvm_unreachable("bad ABI kind");
4419}
4420
4421void ARMABIInfo::setRuntimeCC() {
4422 assert(getRuntimeCC() == llvm::CallingConv::C);
4423
4424 // Don't muddy up the IR with a ton of explicit annotations if
4425 // they'd just match what LLVM will infer from the triple.
4426 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4427 if (abiCC != getLLVMDefaultCC())
4428 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004429}
4430
Manman Renb505d332012-10-31 19:02:26 +00004431/// markAllocatedVFPs - update VFPRegs according to the alignment and
4432/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004433void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4434 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004435 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004436 if (AllocatedVFPs >= 16) {
4437 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4438 // the stack.
4439 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004440 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004441 }
Manman Renb505d332012-10-31 19:02:26 +00004442 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4443 // VFP registers of the appropriate type unallocated then the argument is
4444 // allocated to the lowest-numbered sequence of such registers.
4445 for (unsigned I = 0; I < 16; I += Alignment) {
4446 bool FoundSlot = true;
4447 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4448 if (J >= 16 || VFPRegs[J]) {
4449 FoundSlot = false;
4450 break;
4451 }
4452 if (FoundSlot) {
4453 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4454 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004455 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004456 return;
4457 }
4458 }
4459 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4460 // unallocated are marked as unavailable.
4461 for (unsigned I = 0; I < 16; I++)
4462 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004463 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004464}
4465
Oliver Stannard405bded2014-02-11 09:25:50 +00004466/// Update AllocatedGPRs to record the number of general purpose registers
4467/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4468/// this represents arguments being stored on the stack.
4469void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004470 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004471 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4472
4473 if (Alignment == 2 && AllocatedGPRs & 0x1)
4474 AllocatedGPRs += 1;
4475
4476 AllocatedGPRs += NumRequired;
4477}
4478
4479void ARMABIInfo::resetAllocatedRegs(void) const {
4480 AllocatedGPRs = 0;
4481 AllocatedVFPs = 0;
4482 for (unsigned i = 0; i < NumVFPs; ++i)
4483 VFPRegs[i] = 0;
4484}
4485
James Molloy6f244b62014-05-09 16:21:39 +00004486ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004487 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004488 // We update number of allocated VFPs according to
4489 // 6.1.2.1 The following argument types are VFP CPRCs:
4490 // A single-precision floating-point type (including promoted
4491 // half-precision types); A double-precision floating-point type;
4492 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4493 // with a Base Type of a single- or double-precision floating-point type,
4494 // 64-bit containerized vectors or 128-bit containerized vectors with one
4495 // to four Elements.
4496
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004497 const bool isAAPCS_VFP =
4498 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4499
Manman Renfef9e312012-10-16 19:18:39 +00004500 // Handle illegal vector types here.
4501 if (isIllegalVectorType(Ty)) {
4502 uint64_t Size = getContext().getTypeSize(Ty);
4503 if (Size <= 32) {
4504 llvm::Type *ResType =
4505 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004506 markAllocatedGPRs(1, 1);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004507 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004508 }
4509 if (Size == 64) {
4510 llvm::Type *ResType = llvm::VectorType::get(
4511 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004512 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4513 markAllocatedGPRs(2, 2);
4514 } else {
4515 markAllocatedVFPs(2, 2);
4516 IsCPRC = true;
4517 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004518 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004519 }
4520 if (Size == 128) {
4521 llvm::Type *ResType = llvm::VectorType::get(
4522 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004523 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4524 markAllocatedGPRs(2, 4);
4525 } else {
4526 markAllocatedVFPs(4, 4);
4527 IsCPRC = true;
4528 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004529 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004530 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004531 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004532 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4533 }
Manman Renb505d332012-10-31 19:02:26 +00004534 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004535 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4536 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4537 uint64_t Size = getContext().getTypeSize(VT);
4538 // Size of a legal vector should be power of 2 and above 64.
4539 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4540 IsCPRC = true;
4541 }
Manman Ren2a523d82012-10-30 23:21:41 +00004542 }
Manman Renb505d332012-10-31 19:02:26 +00004543 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004544 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4545 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4546 if (BT->getKind() == BuiltinType::Half ||
4547 BT->getKind() == BuiltinType::Float) {
4548 markAllocatedVFPs(1, 1);
4549 IsCPRC = true;
4550 }
4551 if (BT->getKind() == BuiltinType::Double ||
4552 BT->getKind() == BuiltinType::LongDouble) {
4553 markAllocatedVFPs(2, 2);
4554 IsCPRC = true;
4555 }
4556 }
Manman Ren2a523d82012-10-30 23:21:41 +00004557 }
Manman Renfef9e312012-10-16 19:18:39 +00004558
John McCalla1dee5302010-08-22 10:59:02 +00004559 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004560 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004561 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004562 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004563 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004564
Oliver Stannard405bded2014-02-11 09:25:50 +00004565 unsigned Size = getContext().getTypeSize(Ty);
4566 if (!IsCPRC)
4567 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004568 return (Ty->isPromotableIntegerType()
4569 ? ABIArgInfo::getExtend()
4570 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004571 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004572
Oliver Stannard405bded2014-02-11 09:25:50 +00004573 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4574 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004575 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004576 }
Tim Northover1060eae2013-06-21 22:49:34 +00004577
Daniel Dunbar09d33622009-09-14 21:54:03 +00004578 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004579 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004580 return ABIArgInfo::getIgnore();
4581
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004582 if (isAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004583 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4584 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004585 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004586 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004587 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004588 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004589 // Base can be a floating-point or a vector.
4590 if (Base->isVectorType()) {
4591 // ElementSize is in number of floats.
4592 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004593 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004594 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004595 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004596 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004597 else {
4598 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4599 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004600 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004601 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004602 IsCPRC = true;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004603 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004604 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004605 }
4606
Manman Ren6c30e132012-08-13 21:23:55 +00004607 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004608 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4609 // most 8-byte. We realign the indirect argument if type alignment is bigger
4610 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004611 uint64_t ABIAlign = 4;
4612 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4613 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4614 getABIKind() == ARMABIInfo::AAPCS)
4615 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004616 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004617 // Update Allocated GPRs. Since this is only used when the size of the
4618 // argument is greater than 64 bytes, this will always use up any available
4619 // registers (of which there are 4). We also don't care about getting the
4620 // alignment right, because general-purpose registers cannot be back-filled.
4621 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004622 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004623 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004624 }
4625
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004626 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004627 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004628 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004629 // FIXME: Try to match the types of the arguments more accurately where
4630 // we can.
4631 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004632 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4633 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004634 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004635 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004636 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4637 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004638 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004639 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004640
Chris Lattnera5f58b02011-07-09 17:41:47 +00004641 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004642 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004643 return ABIArgInfo::getDirect(STy, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004644}
4645
Chris Lattner458b2aa2010-07-29 02:16:43 +00004646static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004647 llvm::LLVMContext &VMContext) {
4648 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4649 // is called integer-like if its size is less than or equal to one word, and
4650 // the offset of each of its addressable sub-fields is zero.
4651
4652 uint64_t Size = Context.getTypeSize(Ty);
4653
4654 // Check that the type fits in a word.
4655 if (Size > 32)
4656 return false;
4657
4658 // FIXME: Handle vector types!
4659 if (Ty->isVectorType())
4660 return false;
4661
Daniel Dunbard53bac72009-09-14 02:20:34 +00004662 // Float types are never treated as "integer like".
4663 if (Ty->isRealFloatingType())
4664 return false;
4665
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004666 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004667 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004668 return true;
4669
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004670 // Small complex integer types are "integer like".
4671 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4672 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004673
4674 // Single element and zero sized arrays should be allowed, by the definition
4675 // above, but they are not.
4676
4677 // Otherwise, it must be a record type.
4678 const RecordType *RT = Ty->getAs<RecordType>();
4679 if (!RT) return false;
4680
4681 // Ignore records with flexible arrays.
4682 const RecordDecl *RD = RT->getDecl();
4683 if (RD->hasFlexibleArrayMember())
4684 return false;
4685
4686 // Check that all sub-fields are at offset 0, and are themselves "integer
4687 // like".
4688 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4689
4690 bool HadField = false;
4691 unsigned idx = 0;
4692 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4693 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004694 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004695
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004696 // Bit-fields are not addressable, we only need to verify they are "integer
4697 // like". We still have to disallow a subsequent non-bitfield, for example:
4698 // struct { int : 0; int x }
4699 // is non-integer like according to gcc.
4700 if (FD->isBitField()) {
4701 if (!RD->isUnion())
4702 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004703
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004704 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4705 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004706
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004707 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004708 }
4709
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004710 // Check if this field is at offset 0.
4711 if (Layout.getFieldOffset(idx) != 0)
4712 return false;
4713
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004714 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4715 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004716
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004717 // Only allow at most one field in a structure. This doesn't match the
4718 // wording above, but follows gcc in situations with a field following an
4719 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004720 if (!RD->isUnion()) {
4721 if (HadField)
4722 return false;
4723
4724 HadField = true;
4725 }
4726 }
4727
4728 return true;
4729}
4730
Oliver Stannard405bded2014-02-11 09:25:50 +00004731ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4732 bool isVariadic) const {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004733 const bool isAAPCS_VFP =
4734 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4735
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004736 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004737 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004738
Daniel Dunbar19964db2010-09-23 01:54:32 +00004739 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004740 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4741 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004742 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004743 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004744
John McCalla1dee5302010-08-22 10:59:02 +00004745 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004746 // Treat an enum type as its underlying type.
4747 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4748 RetTy = EnumTy->getDecl()->getIntegerType();
4749
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004750 return (RetTy->isPromotableIntegerType()
4751 ? ABIArgInfo::getExtend()
4752 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004753 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004754
4755 // Are we following APCS?
4756 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004757 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004758 return ABIArgInfo::getIgnore();
4759
Daniel Dunbareedf1512010-02-01 23:31:19 +00004760 // Complex types are all returned as packed integers.
4761 //
4762 // FIXME: Consider using 2 x vector types if the back end handles them
4763 // correctly.
4764 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004765 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4766 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004767
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004768 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004769 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004770 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004771 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004772 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004773 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004774 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004775 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4776 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004777 }
4778
4779 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004780 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004781 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004782 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004783
4784 // Otherwise this is an AAPCS variant.
4785
Chris Lattner458b2aa2010-07-29 02:16:43 +00004786 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004787 return ABIArgInfo::getIgnore();
4788
Bob Wilson1d9269a2011-11-02 04:51:36 +00004789 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004790 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Craig Topper8a13c412014-05-21 05:09:00 +00004791 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004792 uint64_t Members;
4793 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004794 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004795 // Homogeneous Aggregates are returned directly.
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004796 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004797 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004798 }
4799
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004800 // Aggregates <= 4 bytes are returned in r0; other aggregates
4801 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004802 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004803 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004804 if (getDataLayout().isBigEndian())
4805 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004806 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4807 nullptr, !isAAPCS_VFP);
Christian Pirkerc3d32172014-07-03 09:28:12 +00004808
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004809 // Return in the smallest viable integer type.
4810 if (Size <= 8)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004811 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()), 0,
4812 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004813 if (Size <= 16)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004814 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()), 0,
4815 nullptr, !isAAPCS_VFP);
4816 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4817 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004818 }
4819
Oliver Stannard405bded2014-02-11 09:25:50 +00004820 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004821 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004822}
4823
Manman Renfef9e312012-10-16 19:18:39 +00004824/// isIllegalVector - check whether Ty is an illegal vector type.
4825bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4826 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4827 // Check whether VT is legal.
4828 unsigned NumElements = VT->getNumElements();
4829 uint64_t Size = getContext().getTypeSize(VT);
4830 // NumElements should be power of 2.
4831 if ((NumElements & (NumElements - 1)) != 0)
4832 return true;
4833 // Size should be greater than 32 bits.
4834 return Size <= 32;
4835 }
4836 return false;
4837}
4838
Reid Klecknere9f6a712014-10-31 17:10:41 +00004839bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4840 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4841 // double, or 64-bit or 128-bit vectors.
4842 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4843 if (BT->getKind() == BuiltinType::Float ||
4844 BT->getKind() == BuiltinType::Double ||
4845 BT->getKind() == BuiltinType::LongDouble)
4846 return true;
4847 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4848 unsigned VecSize = getContext().getTypeSize(VT);
4849 if (VecSize == 64 || VecSize == 128)
4850 return true;
4851 }
4852 return false;
4853}
4854
4855bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4856 uint64_t Members) const {
4857 return Members <= 4;
4858}
4859
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004860llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004861 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004862 llvm::Type *BP = CGF.Int8PtrTy;
4863 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004864
4865 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004866 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004867 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004868
Tim Northover1711cc92013-06-21 23:05:33 +00004869 if (isEmptyRecord(getContext(), Ty, true)) {
4870 // These are ignored for parameter passing purposes.
4871 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4872 return Builder.CreateBitCast(Addr, PTy);
4873 }
4874
Manman Rencca54d02012-10-16 19:01:37 +00004875 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004876 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004877 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004878
4879 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4880 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004881 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4882 getABIKind() == ARMABIInfo::AAPCS)
4883 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4884 else
4885 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004886 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4887 if (isIllegalVectorType(Ty) && Size > 16) {
4888 IsIndirect = true;
4889 Size = 4;
4890 TyAlign = 4;
4891 }
Manman Rencca54d02012-10-16 19:01:37 +00004892
4893 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004894 if (TyAlign > 4) {
4895 assert((TyAlign & (TyAlign - 1)) == 0 &&
4896 "Alignment is not power of 2!");
4897 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4898 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4899 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004900 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004901 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004902
4903 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004904 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004905 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004906 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004907 "ap.next");
4908 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4909
Manman Renfef9e312012-10-16 19:18:39 +00004910 if (IsIndirect)
4911 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004912 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004913 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4914 // may not be correctly aligned for the vector type. We create an aligned
4915 // temporary space and copy the content over from ap.cur to the temporary
4916 // space. This is necessary if the natural alignment of the type is greater
4917 // than the ABI alignment.
4918 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4919 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4920 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4921 "var.align");
4922 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4923 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4924 Builder.CreateMemCpy(Dst, Src,
4925 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4926 TyAlign, false);
4927 Addr = AlignedTemp; //The content is in aligned location.
4928 }
4929 llvm::Type *PTy =
4930 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4931 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4932
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004933 return AddrTyped;
4934}
4935
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004936namespace {
4937
Derek Schuffa2020962012-10-16 22:30:41 +00004938class NaClARMABIInfo : public ABIInfo {
4939 public:
4940 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4941 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004942 void computeInfo(CGFunctionInfo &FI) const override;
4943 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4944 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00004945 private:
4946 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4947 ARMABIInfo NInfo; // Used for everything else.
4948};
4949
4950class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4951 public:
4952 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4953 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4954};
4955
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004956}
4957
Derek Schuffa2020962012-10-16 22:30:41 +00004958void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4959 if (FI.getASTCallingConvention() == CC_PnaclCall)
4960 PInfo.computeInfo(FI);
4961 else
4962 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4963}
4964
4965llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4966 CodeGenFunction &CGF) const {
4967 // Always use the native convention; calling pnacl-style varargs functions
4968 // is unsupported.
4969 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4970}
4971
Chris Lattner0cf24192010-06-28 20:05:43 +00004972//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004973// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004974//===----------------------------------------------------------------------===//
4975
4976namespace {
4977
Justin Holewinski83e96682012-05-24 17:43:12 +00004978class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004979public:
Justin Holewinski36837432013-03-30 14:38:24 +00004980 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004981
4982 ABIArgInfo classifyReturnType(QualType RetTy) const;
4983 ABIArgInfo classifyArgumentType(QualType Ty) const;
4984
Craig Topper4f12f102014-03-12 06:41:41 +00004985 void computeInfo(CGFunctionInfo &FI) const override;
4986 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4987 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004988};
4989
Justin Holewinski83e96682012-05-24 17:43:12 +00004990class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004991public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004992 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4993 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004994
4995 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4996 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004997private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00004998 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4999 // resulting MDNode to the nvvm.annotations MDNode.
5000 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005001};
5002
Justin Holewinski83e96682012-05-24 17:43:12 +00005003ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005004 if (RetTy->isVoidType())
5005 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005006
5007 // note: this is different from default ABI
5008 if (!RetTy->isScalarType())
5009 return ABIArgInfo::getDirect();
5010
5011 // Treat an enum type as its underlying type.
5012 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5013 RetTy = EnumTy->getDecl()->getIntegerType();
5014
5015 return (RetTy->isPromotableIntegerType() ?
5016 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005017}
5018
Justin Holewinski83e96682012-05-24 17:43:12 +00005019ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005020 // Treat an enum type as its underlying type.
5021 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5022 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005023
Eli Bendersky95338a02014-10-29 13:43:21 +00005024 // Return aggregates type as indirect by value
5025 if (isAggregateTypeForABI(Ty))
5026 return ABIArgInfo::getIndirect(0, /* byval */ true);
5027
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005028 return (Ty->isPromotableIntegerType() ?
5029 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005030}
5031
Justin Holewinski83e96682012-05-24 17:43:12 +00005032void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005033 if (!getCXXABI().classifyReturnType(FI))
5034 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005035 for (auto &I : FI.arguments())
5036 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005037
5038 // Always honor user-specified calling convention.
5039 if (FI.getCallingConvention() != llvm::CallingConv::C)
5040 return;
5041
John McCall882987f2013-02-28 19:01:20 +00005042 FI.setEffectiveCallingConvention(getRuntimeCC());
5043}
5044
Justin Holewinski83e96682012-05-24 17:43:12 +00005045llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5046 CodeGenFunction &CFG) const {
5047 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005048}
5049
Justin Holewinski83e96682012-05-24 17:43:12 +00005050void NVPTXTargetCodeGenInfo::
5051SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5052 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005053 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5054 if (!FD) return;
5055
5056 llvm::Function *F = cast<llvm::Function>(GV);
5057
5058 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005059 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005060 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005061 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005062 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005063 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005064 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5065 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005066 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005067 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005068 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005069 }
Justin Holewinski38031972011-10-05 17:58:44 +00005070
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005071 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005072 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005073 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005074 // __global__ functions cannot be called from the device, we do not
5075 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005076 if (FD->hasAttr<CUDAGlobalAttr>()) {
5077 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5078 addNVVMMetadata(F, "kernel", 1);
5079 }
5080 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5081 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5082 addNVVMMetadata(F, "maxntidx",
5083 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5084 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5085 // zero value from getMinBlocks either means it was not specified in
5086 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5087 // don't have to add a PTX directive.
5088 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5089 if (MinCTASM > 0) {
5090 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5091 addNVVMMetadata(F, "minctasm", MinCTASM);
5092 }
5093 }
Justin Holewinski38031972011-10-05 17:58:44 +00005094 }
5095}
5096
Eli Benderskye06a2c42014-04-15 16:57:05 +00005097void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5098 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005099 llvm::Module *M = F->getParent();
5100 llvm::LLVMContext &Ctx = M->getContext();
5101
5102 // Get "nvvm.annotations" metadata node
5103 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5104
Eli Benderskye1627b42014-04-15 17:19:26 +00005105 llvm::Value *MDVals[] = {
5106 F, llvm::MDString::get(Ctx, Name),
5107 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00005108 // Append metadata to nvvm.annotations
5109 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5110}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005111}
5112
5113//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005114// SystemZ ABI Implementation
5115//===----------------------------------------------------------------------===//
5116
5117namespace {
5118
5119class SystemZABIInfo : public ABIInfo {
5120public:
5121 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5122
5123 bool isPromotableIntegerType(QualType Ty) const;
5124 bool isCompoundType(QualType Ty) const;
5125 bool isFPArgumentType(QualType Ty) const;
5126
5127 ABIArgInfo classifyReturnType(QualType RetTy) const;
5128 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5129
Craig Topper4f12f102014-03-12 06:41:41 +00005130 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005131 if (!getCXXABI().classifyReturnType(FI))
5132 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005133 for (auto &I : FI.arguments())
5134 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005135 }
5136
Craig Topper4f12f102014-03-12 06:41:41 +00005137 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5138 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005139};
5140
5141class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5142public:
5143 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5144 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5145};
5146
5147}
5148
5149bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5150 // Treat an enum type as its underlying type.
5151 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5152 Ty = EnumTy->getDecl()->getIntegerType();
5153
5154 // Promotable integer types are required to be promoted by the ABI.
5155 if (Ty->isPromotableIntegerType())
5156 return true;
5157
5158 // 32-bit values must also be promoted.
5159 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5160 switch (BT->getKind()) {
5161 case BuiltinType::Int:
5162 case BuiltinType::UInt:
5163 return true;
5164 default:
5165 return false;
5166 }
5167 return false;
5168}
5169
5170bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5171 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5172}
5173
5174bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5175 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5176 switch (BT->getKind()) {
5177 case BuiltinType::Float:
5178 case BuiltinType::Double:
5179 return true;
5180 default:
5181 return false;
5182 }
5183
5184 if (const RecordType *RT = Ty->getAsStructureType()) {
5185 const RecordDecl *RD = RT->getDecl();
5186 bool Found = false;
5187
5188 // If this is a C++ record, check the bases first.
5189 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005190 for (const auto &I : CXXRD->bases()) {
5191 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005192
5193 // Empty bases don't affect things either way.
5194 if (isEmptyRecord(getContext(), Base, true))
5195 continue;
5196
5197 if (Found)
5198 return false;
5199 Found = isFPArgumentType(Base);
5200 if (!Found)
5201 return false;
5202 }
5203
5204 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005205 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005206 // Empty bitfields don't affect things either way.
5207 // Unlike isSingleElementStruct(), empty structure and array fields
5208 // do count. So do anonymous bitfields that aren't zero-sized.
5209 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5210 return true;
5211
5212 // Unlike isSingleElementStruct(), arrays do not count.
5213 // Nested isFPArgumentType structures still do though.
5214 if (Found)
5215 return false;
5216 Found = isFPArgumentType(FD->getType());
5217 if (!Found)
5218 return false;
5219 }
5220
5221 // Unlike isSingleElementStruct(), trailing padding is allowed.
5222 // An 8-byte aligned struct s { float f; } is passed as a double.
5223 return Found;
5224 }
5225
5226 return false;
5227}
5228
5229llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5230 CodeGenFunction &CGF) const {
5231 // Assume that va_list type is correct; should be pointer to LLVM type:
5232 // struct {
5233 // i64 __gpr;
5234 // i64 __fpr;
5235 // i8 *__overflow_arg_area;
5236 // i8 *__reg_save_area;
5237 // };
5238
5239 // Every argument occupies 8 bytes and is passed by preference in either
5240 // GPRs or FPRs.
5241 Ty = CGF.getContext().getCanonicalType(Ty);
5242 ABIArgInfo AI = classifyArgumentType(Ty);
5243 bool InFPRs = isFPArgumentType(Ty);
5244
5245 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5246 bool IsIndirect = AI.isIndirect();
5247 unsigned UnpaddedBitSize;
5248 if (IsIndirect) {
5249 APTy = llvm::PointerType::getUnqual(APTy);
5250 UnpaddedBitSize = 64;
5251 } else
5252 UnpaddedBitSize = getContext().getTypeSize(Ty);
5253 unsigned PaddedBitSize = 64;
5254 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5255
5256 unsigned PaddedSize = PaddedBitSize / 8;
5257 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5258
5259 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5260 if (InFPRs) {
5261 MaxRegs = 4; // Maximum of 4 FPR arguments
5262 RegCountField = 1; // __fpr
5263 RegSaveIndex = 16; // save offset for f0
5264 RegPadding = 0; // floats are passed in the high bits of an FPR
5265 } else {
5266 MaxRegs = 5; // Maximum of 5 GPR arguments
5267 RegCountField = 0; // __gpr
5268 RegSaveIndex = 2; // save offset for r2
5269 RegPadding = Padding; // values are passed in the low bits of a GPR
5270 }
5271
5272 llvm::Value *RegCountPtr =
5273 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5274 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5275 llvm::Type *IndexTy = RegCount->getType();
5276 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5277 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005278 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005279
5280 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5281 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5282 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5283 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5284
5285 // Emit code to load the value if it was passed in registers.
5286 CGF.EmitBlock(InRegBlock);
5287
5288 // Work out the address of an argument register.
5289 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5290 llvm::Value *ScaledRegCount =
5291 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5292 llvm::Value *RegBase =
5293 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5294 llvm::Value *RegOffset =
5295 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5296 llvm::Value *RegSaveAreaPtr =
5297 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5298 llvm::Value *RegSaveArea =
5299 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5300 llvm::Value *RawRegAddr =
5301 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5302 llvm::Value *RegAddr =
5303 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5304
5305 // Update the register count
5306 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5307 llvm::Value *NewRegCount =
5308 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5309 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5310 CGF.EmitBranch(ContBlock);
5311
5312 // Emit code to load the value if it was passed in memory.
5313 CGF.EmitBlock(InMemBlock);
5314
5315 // Work out the address of a stack argument.
5316 llvm::Value *OverflowArgAreaPtr =
5317 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5318 llvm::Value *OverflowArgArea =
5319 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5320 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5321 llvm::Value *RawMemAddr =
5322 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5323 llvm::Value *MemAddr =
5324 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5325
5326 // Update overflow_arg_area_ptr pointer
5327 llvm::Value *NewOverflowArgArea =
5328 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5329 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5330 CGF.EmitBranch(ContBlock);
5331
5332 // Return the appropriate result.
5333 CGF.EmitBlock(ContBlock);
5334 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5335 ResAddr->addIncoming(RegAddr, InRegBlock);
5336 ResAddr->addIncoming(MemAddr, InMemBlock);
5337
5338 if (IsIndirect)
5339 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5340
5341 return ResAddr;
5342}
5343
Ulrich Weigand47445072013-05-06 16:26:41 +00005344ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5345 if (RetTy->isVoidType())
5346 return ABIArgInfo::getIgnore();
5347 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5348 return ABIArgInfo::getIndirect(0);
5349 return (isPromotableIntegerType(RetTy) ?
5350 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5351}
5352
5353ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5354 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005355 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005356 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5357
5358 // Integers and enums are extended to full register width.
5359 if (isPromotableIntegerType(Ty))
5360 return ABIArgInfo::getExtend();
5361
5362 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5363 uint64_t Size = getContext().getTypeSize(Ty);
5364 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005365 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005366
5367 // Handle small structures.
5368 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5369 // Structures with flexible arrays have variable length, so really
5370 // fail the size test above.
5371 const RecordDecl *RD = RT->getDecl();
5372 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005373 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005374
5375 // The structure is passed as an unextended integer, a float, or a double.
5376 llvm::Type *PassTy;
5377 if (isFPArgumentType(Ty)) {
5378 assert(Size == 32 || Size == 64);
5379 if (Size == 32)
5380 PassTy = llvm::Type::getFloatTy(getVMContext());
5381 else
5382 PassTy = llvm::Type::getDoubleTy(getVMContext());
5383 } else
5384 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5385 return ABIArgInfo::getDirect(PassTy);
5386 }
5387
5388 // Non-structure compounds are passed indirectly.
5389 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005390 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005391
Craig Topper8a13c412014-05-21 05:09:00 +00005392 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005393}
5394
5395//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005396// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005397//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005398
5399namespace {
5400
5401class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5402public:
Chris Lattner2b037972010-07-29 02:01:43 +00005403 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5404 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005405 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005406 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005407};
5408
5409}
5410
5411void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5412 llvm::GlobalValue *GV,
5413 CodeGen::CodeGenModule &M) const {
5414 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5415 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5416 // Handle 'interrupt' attribute:
5417 llvm::Function *F = cast<llvm::Function>(GV);
5418
5419 // Step 1: Set ISR calling convention.
5420 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5421
5422 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005423 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005424
5425 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005426 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005427 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5428 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005429 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005430 }
5431}
5432
Chris Lattner0cf24192010-06-28 20:05:43 +00005433//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005434// MIPS ABI Implementation. This works for both little-endian and
5435// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005436//===----------------------------------------------------------------------===//
5437
John McCall943fae92010-05-27 06:19:26 +00005438namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005439class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005440 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005441 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5442 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005443 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005444 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005445 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005446 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005447public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005448 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005449 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005450 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005451
5452 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005453 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005454 void computeInfo(CGFunctionInfo &FI) const override;
5455 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5456 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005457};
5458
John McCall943fae92010-05-27 06:19:26 +00005459class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005460 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005461public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005462 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5463 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005464 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005465
Craig Topper4f12f102014-03-12 06:41:41 +00005466 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005467 return 29;
5468 }
5469
Reed Kotler373feca2013-01-16 17:10:28 +00005470 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005471 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005472 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5473 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005474 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005475 if (FD->hasAttr<Mips16Attr>()) {
5476 Fn->addFnAttr("mips16");
5477 }
5478 else if (FD->hasAttr<NoMips16Attr>()) {
5479 Fn->addFnAttr("nomips16");
5480 }
Reed Kotler373feca2013-01-16 17:10:28 +00005481 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005482
John McCall943fae92010-05-27 06:19:26 +00005483 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005484 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005485
Craig Topper4f12f102014-03-12 06:41:41 +00005486 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005487 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005488 }
John McCall943fae92010-05-27 06:19:26 +00005489};
5490}
5491
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005492void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005493 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005494 llvm::IntegerType *IntTy =
5495 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005496
5497 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5498 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5499 ArgList.push_back(IntTy);
5500
5501 // If necessary, add one more integer type to ArgList.
5502 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5503
5504 if (R)
5505 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005506}
5507
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005508// In N32/64, an aligned double precision floating point field is passed in
5509// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005510llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005511 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5512
5513 if (IsO32) {
5514 CoerceToIntArgs(TySize, ArgList);
5515 return llvm::StructType::get(getVMContext(), ArgList);
5516 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005517
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005518 if (Ty->isComplexType())
5519 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005520
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005521 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005522
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005523 // Unions/vectors are passed in integer registers.
5524 if (!RT || !RT->isStructureOrClassType()) {
5525 CoerceToIntArgs(TySize, ArgList);
5526 return llvm::StructType::get(getVMContext(), ArgList);
5527 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005528
5529 const RecordDecl *RD = RT->getDecl();
5530 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005531 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005532
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005533 uint64_t LastOffset = 0;
5534 unsigned idx = 0;
5535 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5536
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005537 // Iterate over fields in the struct/class and check if there are any aligned
5538 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005539 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5540 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005541 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005542 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5543
5544 if (!BT || BT->getKind() != BuiltinType::Double)
5545 continue;
5546
5547 uint64_t Offset = Layout.getFieldOffset(idx);
5548 if (Offset % 64) // Ignore doubles that are not aligned.
5549 continue;
5550
5551 // Add ((Offset - LastOffset) / 64) args of type i64.
5552 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5553 ArgList.push_back(I64);
5554
5555 // Add double type.
5556 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5557 LastOffset = Offset + 64;
5558 }
5559
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005560 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5561 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005562
5563 return llvm::StructType::get(getVMContext(), ArgList);
5564}
5565
Akira Hatanakaddd66342013-10-29 18:41:15 +00005566llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5567 uint64_t Offset) const {
5568 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005569 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005570
Akira Hatanakaddd66342013-10-29 18:41:15 +00005571 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005572}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005573
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005574ABIArgInfo
5575MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005576 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005577 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005578 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005579
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005580 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5581 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005582 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5583 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005584
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005585 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005586 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005587 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005588 return ABIArgInfo::getIgnore();
5589
Mark Lacey3825e832013-10-06 01:33:34 +00005590 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005591 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005592 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005593 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005594
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005595 // If we have reached here, aggregates are passed directly by coercing to
5596 // another structure type. Padding is inserted if the offset of the
5597 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005598 ABIArgInfo ArgInfo =
5599 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5600 getPaddingType(OrigOffset, CurrOffset));
5601 ArgInfo.setInReg(true);
5602 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005603 }
5604
5605 // Treat an enum type as its underlying type.
5606 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5607 Ty = EnumTy->getDecl()->getIntegerType();
5608
Daniel Sanders5b445b32014-10-24 14:42:42 +00005609 // All integral types are promoted to the GPR width.
5610 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005611 return ABIArgInfo::getExtend();
5612
Akira Hatanakaddd66342013-10-29 18:41:15 +00005613 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005614 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005615}
5616
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005617llvm::Type*
5618MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005619 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005620 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005621
Akira Hatanakab6f74432012-02-09 18:49:26 +00005622 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005623 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005624 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5625 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005626
Akira Hatanakab6f74432012-02-09 18:49:26 +00005627 // N32/64 returns struct/classes in floating point registers if the
5628 // following conditions are met:
5629 // 1. The size of the struct/class is no larger than 128-bit.
5630 // 2. The struct/class has one or two fields all of which are floating
5631 // point types.
5632 // 3. The offset of the first field is zero (this follows what gcc does).
5633 //
5634 // Any other composite results are returned in integer registers.
5635 //
5636 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5637 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5638 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005639 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005640
Akira Hatanakab6f74432012-02-09 18:49:26 +00005641 if (!BT || !BT->isFloatingPoint())
5642 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005643
David Blaikie2d7c57e2012-04-30 02:36:29 +00005644 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005645 }
5646
5647 if (b == e)
5648 return llvm::StructType::get(getVMContext(), RTList,
5649 RD->hasAttr<PackedAttr>());
5650
5651 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005652 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005653 }
5654
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005655 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005656 return llvm::StructType::get(getVMContext(), RTList);
5657}
5658
Akira Hatanakab579fe52011-06-02 00:09:17 +00005659ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005660 uint64_t Size = getContext().getTypeSize(RetTy);
5661
Daniel Sandersed39f582014-09-04 13:28:14 +00005662 if (RetTy->isVoidType())
5663 return ABIArgInfo::getIgnore();
5664
5665 // O32 doesn't treat zero-sized structs differently from other structs.
5666 // However, N32/N64 ignores zero sized return values.
5667 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005668 return ABIArgInfo::getIgnore();
5669
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005670 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005671 if (Size <= 128) {
5672 if (RetTy->isAnyComplexType())
5673 return ABIArgInfo::getDirect();
5674
Daniel Sanderse5018b62014-09-04 15:05:39 +00005675 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005676 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005677 if (!IsO32 ||
5678 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5679 ABIArgInfo ArgInfo =
5680 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5681 ArgInfo.setInReg(true);
5682 return ArgInfo;
5683 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005684 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005685
5686 return ABIArgInfo::getIndirect(0);
5687 }
5688
5689 // Treat an enum type as its underlying type.
5690 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5691 RetTy = EnumTy->getDecl()->getIntegerType();
5692
5693 return (RetTy->isPromotableIntegerType() ?
5694 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5695}
5696
5697void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005698 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005699 if (!getCXXABI().classifyReturnType(FI))
5700 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005701
5702 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005703 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005704
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005705 for (auto &I : FI.arguments())
5706 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005707}
5708
5709llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5710 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005711 llvm::Type *BP = CGF.Int8PtrTy;
5712 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5713
5714 CGBuilderTy &Builder = CGF.Builder;
5715 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5716 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005717 int64_t TypeAlign =
5718 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005719 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5720 llvm::Value *AddrTyped;
5721 unsigned PtrWidth = getTarget().getPointerWidth(0);
5722 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5723
5724 if (TypeAlign > MinABIStackAlignInBytes) {
5725 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5726 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5727 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5728 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5729 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5730 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5731 }
5732 else
5733 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5734
5735 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5736 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5737 uint64_t Offset =
5738 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5739 llvm::Value *NextAddr =
5740 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5741 "ap.next");
5742 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5743
5744 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005745}
5746
John McCall943fae92010-05-27 06:19:26 +00005747bool
5748MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5749 llvm::Value *Address) const {
5750 // This information comes from gcc's implementation, which seems to
5751 // as canonical as it gets.
5752
John McCall943fae92010-05-27 06:19:26 +00005753 // Everything on MIPS is 4 bytes. Double-precision FP registers
5754 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005755 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005756
5757 // 0-31 are the general purpose registers, $0 - $31.
5758 // 32-63 are the floating-point registers, $f0 - $f31.
5759 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5760 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005761 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005762
5763 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5764 // They are one bit wide and ignored here.
5765
5766 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5767 // (coprocessor 1 is the FP unit)
5768 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5769 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5770 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005771 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005772 return false;
5773}
5774
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005775//===----------------------------------------------------------------------===//
5776// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5777// Currently subclassed only to implement custom OpenCL C function attribute
5778// handling.
5779//===----------------------------------------------------------------------===//
5780
5781namespace {
5782
5783class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5784public:
5785 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5786 : DefaultTargetCodeGenInfo(CGT) {}
5787
Craig Topper4f12f102014-03-12 06:41:41 +00005788 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5789 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005790};
5791
5792void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5793 llvm::GlobalValue *GV,
5794 CodeGen::CodeGenModule &M) const {
5795 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5796 if (!FD) return;
5797
5798 llvm::Function *F = cast<llvm::Function>(GV);
5799
David Blaikiebbafb8a2012-03-11 07:00:24 +00005800 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005801 if (FD->hasAttr<OpenCLKernelAttr>()) {
5802 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005803 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005804 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5805 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005806 // Convert the reqd_work_group_size() attributes to metadata.
5807 llvm::LLVMContext &Context = F->getContext();
5808 llvm::NamedMDNode *OpenCLMetadata =
5809 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5810
5811 SmallVector<llvm::Value*, 5> Operands;
5812 Operands.push_back(F);
5813
Chris Lattnerece04092012-02-07 00:39:47 +00005814 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005815 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005816 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005817 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005818 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005819 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005820
5821 // Add a boolean constant operand for "required" (true) or "hint" (false)
5822 // for implementing the work_group_size_hint attr later. Currently
5823 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005824 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005825 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5826 }
5827 }
5828 }
5829}
5830
5831}
John McCall943fae92010-05-27 06:19:26 +00005832
Tony Linthicum76329bf2011-12-12 21:14:55 +00005833//===----------------------------------------------------------------------===//
5834// Hexagon ABI Implementation
5835//===----------------------------------------------------------------------===//
5836
5837namespace {
5838
5839class HexagonABIInfo : public ABIInfo {
5840
5841
5842public:
5843 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5844
5845private:
5846
5847 ABIArgInfo classifyReturnType(QualType RetTy) const;
5848 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5849
Craig Topper4f12f102014-03-12 06:41:41 +00005850 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005851
Craig Topper4f12f102014-03-12 06:41:41 +00005852 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5853 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005854};
5855
5856class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5857public:
5858 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5859 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5860
Craig Topper4f12f102014-03-12 06:41:41 +00005861 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005862 return 29;
5863 }
5864};
5865
5866}
5867
5868void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005869 if (!getCXXABI().classifyReturnType(FI))
5870 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005871 for (auto &I : FI.arguments())
5872 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005873}
5874
5875ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5876 if (!isAggregateTypeForABI(Ty)) {
5877 // Treat an enum type as its underlying type.
5878 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5879 Ty = EnumTy->getDecl()->getIntegerType();
5880
5881 return (Ty->isPromotableIntegerType() ?
5882 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5883 }
5884
5885 // Ignore empty records.
5886 if (isEmptyRecord(getContext(), Ty, true))
5887 return ABIArgInfo::getIgnore();
5888
Mark Lacey3825e832013-10-06 01:33:34 +00005889 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005890 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005891
5892 uint64_t Size = getContext().getTypeSize(Ty);
5893 if (Size > 64)
5894 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5895 // Pass in the smallest viable integer type.
5896 else if (Size > 32)
5897 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5898 else if (Size > 16)
5899 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5900 else if (Size > 8)
5901 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5902 else
5903 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5904}
5905
5906ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5907 if (RetTy->isVoidType())
5908 return ABIArgInfo::getIgnore();
5909
5910 // Large vector types should be returned via memory.
5911 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5912 return ABIArgInfo::getIndirect(0);
5913
5914 if (!isAggregateTypeForABI(RetTy)) {
5915 // Treat an enum type as its underlying type.
5916 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5917 RetTy = EnumTy->getDecl()->getIntegerType();
5918
5919 return (RetTy->isPromotableIntegerType() ?
5920 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5921 }
5922
Tony Linthicum76329bf2011-12-12 21:14:55 +00005923 if (isEmptyRecord(getContext(), RetTy, true))
5924 return ABIArgInfo::getIgnore();
5925
5926 // Aggregates <= 8 bytes are returned in r0; other aggregates
5927 // are returned indirectly.
5928 uint64_t Size = getContext().getTypeSize(RetTy);
5929 if (Size <= 64) {
5930 // Return in the smallest viable integer type.
5931 if (Size <= 8)
5932 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5933 if (Size <= 16)
5934 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5935 if (Size <= 32)
5936 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5937 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5938 }
5939
5940 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5941}
5942
5943llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005944 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005945 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005946 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005947
5948 CGBuilderTy &Builder = CGF.Builder;
5949 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5950 "ap");
5951 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5952 llvm::Type *PTy =
5953 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5954 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5955
5956 uint64_t Offset =
5957 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5958 llvm::Value *NextAddr =
5959 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5960 "ap.next");
5961 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5962
5963 return AddrTyped;
5964}
5965
5966
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005967//===----------------------------------------------------------------------===//
5968// SPARC v9 ABI Implementation.
5969// Based on the SPARC Compliance Definition version 2.4.1.
5970//
5971// Function arguments a mapped to a nominal "parameter array" and promoted to
5972// registers depending on their type. Each argument occupies 8 or 16 bytes in
5973// the array, structs larger than 16 bytes are passed indirectly.
5974//
5975// One case requires special care:
5976//
5977// struct mixed {
5978// int i;
5979// float f;
5980// };
5981//
5982// When a struct mixed is passed by value, it only occupies 8 bytes in the
5983// parameter array, but the int is passed in an integer register, and the float
5984// is passed in a floating point register. This is represented as two arguments
5985// with the LLVM IR inreg attribute:
5986//
5987// declare void f(i32 inreg %i, float inreg %f)
5988//
5989// The code generator will only allocate 4 bytes from the parameter array for
5990// the inreg arguments. All other arguments are allocated a multiple of 8
5991// bytes.
5992//
5993namespace {
5994class SparcV9ABIInfo : public ABIInfo {
5995public:
5996 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5997
5998private:
5999 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006000 void computeInfo(CGFunctionInfo &FI) const override;
6001 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6002 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006003
6004 // Coercion type builder for structs passed in registers. The coercion type
6005 // serves two purposes:
6006 //
6007 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6008 // in registers.
6009 // 2. Expose aligned floating point elements as first-level elements, so the
6010 // code generator knows to pass them in floating point registers.
6011 //
6012 // We also compute the InReg flag which indicates that the struct contains
6013 // aligned 32-bit floats.
6014 //
6015 struct CoerceBuilder {
6016 llvm::LLVMContext &Context;
6017 const llvm::DataLayout &DL;
6018 SmallVector<llvm::Type*, 8> Elems;
6019 uint64_t Size;
6020 bool InReg;
6021
6022 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6023 : Context(c), DL(dl), Size(0), InReg(false) {}
6024
6025 // Pad Elems with integers until Size is ToSize.
6026 void pad(uint64_t ToSize) {
6027 assert(ToSize >= Size && "Cannot remove elements");
6028 if (ToSize == Size)
6029 return;
6030
6031 // Finish the current 64-bit word.
6032 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6033 if (Aligned > Size && Aligned <= ToSize) {
6034 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6035 Size = Aligned;
6036 }
6037
6038 // Add whole 64-bit words.
6039 while (Size + 64 <= ToSize) {
6040 Elems.push_back(llvm::Type::getInt64Ty(Context));
6041 Size += 64;
6042 }
6043
6044 // Final in-word padding.
6045 if (Size < ToSize) {
6046 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6047 Size = ToSize;
6048 }
6049 }
6050
6051 // Add a floating point element at Offset.
6052 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6053 // Unaligned floats are treated as integers.
6054 if (Offset % Bits)
6055 return;
6056 // The InReg flag is only required if there are any floats < 64 bits.
6057 if (Bits < 64)
6058 InReg = true;
6059 pad(Offset);
6060 Elems.push_back(Ty);
6061 Size = Offset + Bits;
6062 }
6063
6064 // Add a struct type to the coercion type, starting at Offset (in bits).
6065 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6066 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6067 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6068 llvm::Type *ElemTy = StrTy->getElementType(i);
6069 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6070 switch (ElemTy->getTypeID()) {
6071 case llvm::Type::StructTyID:
6072 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6073 break;
6074 case llvm::Type::FloatTyID:
6075 addFloat(ElemOffset, ElemTy, 32);
6076 break;
6077 case llvm::Type::DoubleTyID:
6078 addFloat(ElemOffset, ElemTy, 64);
6079 break;
6080 case llvm::Type::FP128TyID:
6081 addFloat(ElemOffset, ElemTy, 128);
6082 break;
6083 case llvm::Type::PointerTyID:
6084 if (ElemOffset % 64 == 0) {
6085 pad(ElemOffset);
6086 Elems.push_back(ElemTy);
6087 Size += 64;
6088 }
6089 break;
6090 default:
6091 break;
6092 }
6093 }
6094 }
6095
6096 // Check if Ty is a usable substitute for the coercion type.
6097 bool isUsableType(llvm::StructType *Ty) const {
6098 if (Ty->getNumElements() != Elems.size())
6099 return false;
6100 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6101 if (Elems[i] != Ty->getElementType(i))
6102 return false;
6103 return true;
6104 }
6105
6106 // Get the coercion type as a literal struct type.
6107 llvm::Type *getType() const {
6108 if (Elems.size() == 1)
6109 return Elems.front();
6110 else
6111 return llvm::StructType::get(Context, Elems);
6112 }
6113 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006114};
6115} // end anonymous namespace
6116
6117ABIArgInfo
6118SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6119 if (Ty->isVoidType())
6120 return ABIArgInfo::getIgnore();
6121
6122 uint64_t Size = getContext().getTypeSize(Ty);
6123
6124 // Anything too big to fit in registers is passed with an explicit indirect
6125 // pointer / sret pointer.
6126 if (Size > SizeLimit)
6127 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6128
6129 // Treat an enum type as its underlying type.
6130 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6131 Ty = EnumTy->getDecl()->getIntegerType();
6132
6133 // Integer types smaller than a register are extended.
6134 if (Size < 64 && Ty->isIntegerType())
6135 return ABIArgInfo::getExtend();
6136
6137 // Other non-aggregates go in registers.
6138 if (!isAggregateTypeForABI(Ty))
6139 return ABIArgInfo::getDirect();
6140
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006141 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6142 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6143 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6144 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6145
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006146 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006147 // Build a coercion type from the LLVM struct type.
6148 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6149 if (!StrTy)
6150 return ABIArgInfo::getDirect();
6151
6152 CoerceBuilder CB(getVMContext(), getDataLayout());
6153 CB.addStruct(0, StrTy);
6154 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6155
6156 // Try to use the original type for coercion.
6157 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6158
6159 if (CB.InReg)
6160 return ABIArgInfo::getDirectInReg(CoerceTy);
6161 else
6162 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006163}
6164
6165llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6166 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006167 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6168 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6169 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6170 AI.setCoerceToType(ArgTy);
6171
6172 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6173 CGBuilderTy &Builder = CGF.Builder;
6174 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6175 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6176 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6177 llvm::Value *ArgAddr;
6178 unsigned Stride;
6179
6180 switch (AI.getKind()) {
6181 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006182 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006183 llvm_unreachable("Unsupported ABI kind for va_arg");
6184
6185 case ABIArgInfo::Extend:
6186 Stride = 8;
6187 ArgAddr = Builder
6188 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6189 "extend");
6190 break;
6191
6192 case ABIArgInfo::Direct:
6193 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6194 ArgAddr = Addr;
6195 break;
6196
6197 case ABIArgInfo::Indirect:
6198 Stride = 8;
6199 ArgAddr = Builder.CreateBitCast(Addr,
6200 llvm::PointerType::getUnqual(ArgPtrTy),
6201 "indirect");
6202 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6203 break;
6204
6205 case ABIArgInfo::Ignore:
6206 return llvm::UndefValue::get(ArgPtrTy);
6207 }
6208
6209 // Update VAList.
6210 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6211 Builder.CreateStore(Addr, VAListAddrAsBPP);
6212
6213 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006214}
6215
6216void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6217 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006218 for (auto &I : FI.arguments())
6219 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006220}
6221
6222namespace {
6223class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6224public:
6225 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6226 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006227
Craig Topper4f12f102014-03-12 06:41:41 +00006228 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006229 return 14;
6230 }
6231
6232 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006233 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006234};
6235} // end anonymous namespace
6236
Roman Divackyf02c9942014-02-24 18:46:27 +00006237bool
6238SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6239 llvm::Value *Address) const {
6240 // This is calculated from the LLVM and GCC tables and verified
6241 // against gcc output. AFAIK all ABIs use the same encoding.
6242
6243 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6244
6245 llvm::IntegerType *i8 = CGF.Int8Ty;
6246 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6247 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6248
6249 // 0-31: the 8-byte general-purpose registers
6250 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6251
6252 // 32-63: f0-31, the 4-byte floating-point registers
6253 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6254
6255 // Y = 64
6256 // PSR = 65
6257 // WIM = 66
6258 // TBR = 67
6259 // PC = 68
6260 // NPC = 69
6261 // FSR = 70
6262 // CSR = 71
6263 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6264
6265 // 72-87: d0-15, the 8-byte floating-point registers
6266 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6267
6268 return false;
6269}
6270
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006271
Robert Lytton0e076492013-08-13 09:43:10 +00006272//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006273// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006274//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006275
Robert Lytton0e076492013-08-13 09:43:10 +00006276namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006277
6278/// A SmallStringEnc instance is used to build up the TypeString by passing
6279/// it by reference between functions that append to it.
6280typedef llvm::SmallString<128> SmallStringEnc;
6281
6282/// TypeStringCache caches the meta encodings of Types.
6283///
6284/// The reason for caching TypeStrings is two fold:
6285/// 1. To cache a type's encoding for later uses;
6286/// 2. As a means to break recursive member type inclusion.
6287///
6288/// A cache Entry can have a Status of:
6289/// NonRecursive: The type encoding is not recursive;
6290/// Recursive: The type encoding is recursive;
6291/// Incomplete: An incomplete TypeString;
6292/// IncompleteUsed: An incomplete TypeString that has been used in a
6293/// Recursive type encoding.
6294///
6295/// A NonRecursive entry will have all of its sub-members expanded as fully
6296/// as possible. Whilst it may contain types which are recursive, the type
6297/// itself is not recursive and thus its encoding may be safely used whenever
6298/// the type is encountered.
6299///
6300/// A Recursive entry will have all of its sub-members expanded as fully as
6301/// possible. The type itself is recursive and it may contain other types which
6302/// are recursive. The Recursive encoding must not be used during the expansion
6303/// of a recursive type's recursive branch. For simplicity the code uses
6304/// IncompleteCount to reject all usage of Recursive encodings for member types.
6305///
6306/// An Incomplete entry is always a RecordType and only encodes its
6307/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6308/// are placed into the cache during type expansion as a means to identify and
6309/// handle recursive inclusion of types as sub-members. If there is recursion
6310/// the entry becomes IncompleteUsed.
6311///
6312/// During the expansion of a RecordType's members:
6313///
6314/// If the cache contains a NonRecursive encoding for the member type, the
6315/// cached encoding is used;
6316///
6317/// If the cache contains a Recursive encoding for the member type, the
6318/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6319///
6320/// If the member is a RecordType, an Incomplete encoding is placed into the
6321/// cache to break potential recursive inclusion of itself as a sub-member;
6322///
6323/// Once a member RecordType has been expanded, its temporary incomplete
6324/// entry is removed from the cache. If a Recursive encoding was swapped out
6325/// it is swapped back in;
6326///
6327/// If an incomplete entry is used to expand a sub-member, the incomplete
6328/// entry is marked as IncompleteUsed. The cache keeps count of how many
6329/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6330///
6331/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6332/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6333/// Else the member is part of a recursive type and thus the recursion has
6334/// been exited too soon for the encoding to be correct for the member.
6335///
6336class TypeStringCache {
6337 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6338 struct Entry {
6339 std::string Str; // The encoded TypeString for the type.
6340 enum Status State; // Information about the encoding in 'Str'.
6341 std::string Swapped; // A temporary place holder for a Recursive encoding
6342 // during the expansion of RecordType's members.
6343 };
6344 std::map<const IdentifierInfo *, struct Entry> Map;
6345 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6346 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6347public:
Robert Lyttond263f142014-05-06 09:38:54 +00006348 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006349 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6350 bool removeIncomplete(const IdentifierInfo *ID);
6351 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6352 bool IsRecursive);
6353 StringRef lookupStr(const IdentifierInfo *ID);
6354};
6355
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006356/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006357/// FieldEncoding is a helper for this ordering process.
6358class FieldEncoding {
6359 bool HasName;
6360 std::string Enc;
6361public:
6362 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6363 StringRef str() {return Enc.c_str();};
6364 bool operator<(const FieldEncoding &rhs) const {
6365 if (HasName != rhs.HasName) return HasName;
6366 return Enc < rhs.Enc;
6367 }
6368};
6369
Robert Lytton7d1db152013-08-19 09:46:39 +00006370class XCoreABIInfo : public DefaultABIInfo {
6371public:
6372 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006373 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6374 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006375};
6376
Robert Lyttond21e2d72014-03-03 13:45:29 +00006377class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006378 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006379public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006380 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006381 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006382 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6383 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006384};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006385
Robert Lytton2d196952013-10-11 10:29:34 +00006386} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006387
Robert Lytton7d1db152013-08-19 09:46:39 +00006388llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6389 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006390 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006391
Robert Lytton2d196952013-10-11 10:29:34 +00006392 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006393 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6394 CGF.Int8PtrPtrTy);
6395 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006396
Robert Lytton2d196952013-10-11 10:29:34 +00006397 // Handle the argument.
6398 ABIArgInfo AI = classifyArgumentType(Ty);
6399 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6400 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6401 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006402 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006403 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006404 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006405 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006406 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006407 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006408 llvm_unreachable("Unsupported ABI kind for va_arg");
6409 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006410 Val = llvm::UndefValue::get(ArgPtrTy);
6411 ArgSize = 0;
6412 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006413 case ABIArgInfo::Extend:
6414 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006415 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6416 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6417 if (ArgSize < 4)
6418 ArgSize = 4;
6419 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006420 case ABIArgInfo::Indirect:
6421 llvm::Value *ArgAddr;
6422 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6423 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006424 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6425 ArgSize = 4;
6426 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006427 }
Robert Lytton2d196952013-10-11 10:29:34 +00006428
6429 // Increment the VAList.
6430 if (ArgSize) {
6431 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6432 Builder.CreateStore(APN, VAListAddrAsBPP);
6433 }
6434 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006435}
Robert Lytton0e076492013-08-13 09:43:10 +00006436
Robert Lytton844aeeb2014-05-02 09:33:20 +00006437/// During the expansion of a RecordType, an incomplete TypeString is placed
6438/// into the cache as a means to identify and break recursion.
6439/// If there is a Recursive encoding in the cache, it is swapped out and will
6440/// be reinserted by removeIncomplete().
6441/// All other types of encoding should have been used rather than arriving here.
6442void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6443 std::string StubEnc) {
6444 if (!ID)
6445 return;
6446 Entry &E = Map[ID];
6447 assert( (E.Str.empty() || E.State == Recursive) &&
6448 "Incorrectly use of addIncomplete");
6449 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6450 E.Swapped.swap(E.Str); // swap out the Recursive
6451 E.Str.swap(StubEnc);
6452 E.State = Incomplete;
6453 ++IncompleteCount;
6454}
6455
6456/// Once the RecordType has been expanded, the temporary incomplete TypeString
6457/// must be removed from the cache.
6458/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6459/// Returns true if the RecordType was defined recursively.
6460bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6461 if (!ID)
6462 return false;
6463 auto I = Map.find(ID);
6464 assert(I != Map.end() && "Entry not present");
6465 Entry &E = I->second;
6466 assert( (E.State == Incomplete ||
6467 E.State == IncompleteUsed) &&
6468 "Entry must be an incomplete type");
6469 bool IsRecursive = false;
6470 if (E.State == IncompleteUsed) {
6471 // We made use of our Incomplete encoding, thus we are recursive.
6472 IsRecursive = true;
6473 --IncompleteUsedCount;
6474 }
6475 if (E.Swapped.empty())
6476 Map.erase(I);
6477 else {
6478 // Swap the Recursive back.
6479 E.Swapped.swap(E.Str);
6480 E.Swapped.clear();
6481 E.State = Recursive;
6482 }
6483 --IncompleteCount;
6484 return IsRecursive;
6485}
6486
6487/// Add the encoded TypeString to the cache only if it is NonRecursive or
6488/// Recursive (viz: all sub-members were expanded as fully as possible).
6489void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6490 bool IsRecursive) {
6491 if (!ID || IncompleteUsedCount)
6492 return; // No key or it is is an incomplete sub-type so don't add.
6493 Entry &E = Map[ID];
6494 if (IsRecursive && !E.Str.empty()) {
6495 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6496 "This is not the same Recursive entry");
6497 // The parent container was not recursive after all, so we could have used
6498 // this Recursive sub-member entry after all, but we assumed the worse when
6499 // we started viz: IncompleteCount!=0.
6500 return;
6501 }
6502 assert(E.Str.empty() && "Entry already present");
6503 E.Str = Str.str();
6504 E.State = IsRecursive? Recursive : NonRecursive;
6505}
6506
6507/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6508/// are recursively expanding a type (IncompleteCount != 0) and the cached
6509/// encoding is Recursive, return an empty StringRef.
6510StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6511 if (!ID)
6512 return StringRef(); // We have no key.
6513 auto I = Map.find(ID);
6514 if (I == Map.end())
6515 return StringRef(); // We have no encoding.
6516 Entry &E = I->second;
6517 if (E.State == Recursive && IncompleteCount)
6518 return StringRef(); // We don't use Recursive encodings for member types.
6519
6520 if (E.State == Incomplete) {
6521 // The incomplete type is being used to break out of recursion.
6522 E.State = IncompleteUsed;
6523 ++IncompleteUsedCount;
6524 }
6525 return E.Str.c_str();
6526}
6527
6528/// The XCore ABI includes a type information section that communicates symbol
6529/// type information to the linker. The linker uses this information to verify
6530/// safety/correctness of things such as array bound and pointers et al.
6531/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6532/// This type information (TypeString) is emitted into meta data for all global
6533/// symbols: definitions, declarations, functions & variables.
6534///
6535/// The TypeString carries type, qualifier, name, size & value details.
6536/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6537/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6538/// The output is tested by test/CodeGen/xcore-stringtype.c.
6539///
6540static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6541 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6542
6543/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6544void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6545 CodeGen::CodeGenModule &CGM) const {
6546 SmallStringEnc Enc;
6547 if (getTypeString(Enc, D, CGM, TSC)) {
6548 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6549 llvm::SmallVector<llvm::Value *, 2> MDVals;
6550 MDVals.push_back(GV);
6551 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6552 llvm::NamedMDNode *MD =
6553 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6554 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6555 }
6556}
6557
6558static bool appendType(SmallStringEnc &Enc, QualType QType,
6559 const CodeGen::CodeGenModule &CGM,
6560 TypeStringCache &TSC);
6561
6562/// Helper function for appendRecordType().
6563/// Builds a SmallVector containing the encoded field types in declaration order.
6564static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6565 const RecordDecl *RD,
6566 const CodeGen::CodeGenModule &CGM,
6567 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006568 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006569 SmallStringEnc Enc;
6570 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006571 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006572 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006573 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006574 Enc += "b(";
6575 llvm::raw_svector_ostream OS(Enc);
6576 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006577 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006578 OS.flush();
6579 Enc += ':';
6580 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006581 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006582 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006583 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006584 Enc += ')';
6585 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006586 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006587 }
6588 return true;
6589}
6590
6591/// Appends structure and union types to Enc and adds encoding to cache.
6592/// Recursively calls appendType (via extractFieldType) for each field.
6593/// Union types have their fields ordered according to the ABI.
6594static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6595 const CodeGen::CodeGenModule &CGM,
6596 TypeStringCache &TSC, const IdentifierInfo *ID) {
6597 // Append the cached TypeString if we have one.
6598 StringRef TypeString = TSC.lookupStr(ID);
6599 if (!TypeString.empty()) {
6600 Enc += TypeString;
6601 return true;
6602 }
6603
6604 // Start to emit an incomplete TypeString.
6605 size_t Start = Enc.size();
6606 Enc += (RT->isUnionType()? 'u' : 's');
6607 Enc += '(';
6608 if (ID)
6609 Enc += ID->getName();
6610 Enc += "){";
6611
6612 // We collect all encoded fields and order as necessary.
6613 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006614 const RecordDecl *RD = RT->getDecl()->getDefinition();
6615 if (RD && !RD->field_empty()) {
6616 // An incomplete TypeString stub is placed in the cache for this RecordType
6617 // so that recursive calls to this RecordType will use it whilst building a
6618 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006619 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006620 std::string StubEnc(Enc.substr(Start).str());
6621 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6622 TSC.addIncomplete(ID, std::move(StubEnc));
6623 if (!extractFieldType(FE, RD, CGM, TSC)) {
6624 (void) TSC.removeIncomplete(ID);
6625 return false;
6626 }
6627 IsRecursive = TSC.removeIncomplete(ID);
6628 // The ABI requires unions to be sorted but not structures.
6629 // See FieldEncoding::operator< for sort algorithm.
6630 if (RT->isUnionType())
6631 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006632 // We can now complete the TypeString.
6633 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006634 for (unsigned I = 0; I != E; ++I) {
6635 if (I)
6636 Enc += ',';
6637 Enc += FE[I].str();
6638 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006639 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006640 Enc += '}';
6641 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6642 return true;
6643}
6644
6645/// Appends enum types to Enc and adds the encoding to the cache.
6646static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6647 TypeStringCache &TSC,
6648 const IdentifierInfo *ID) {
6649 // Append the cached TypeString if we have one.
6650 StringRef TypeString = TSC.lookupStr(ID);
6651 if (!TypeString.empty()) {
6652 Enc += TypeString;
6653 return true;
6654 }
6655
6656 size_t Start = Enc.size();
6657 Enc += "e(";
6658 if (ID)
6659 Enc += ID->getName();
6660 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006661
6662 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006663 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006664 SmallVector<FieldEncoding, 16> FE;
6665 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6666 ++I) {
6667 SmallStringEnc EnumEnc;
6668 EnumEnc += "m(";
6669 EnumEnc += I->getName();
6670 EnumEnc += "){";
6671 I->getInitVal().toString(EnumEnc);
6672 EnumEnc += '}';
6673 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6674 }
6675 std::sort(FE.begin(), FE.end());
6676 unsigned E = FE.size();
6677 for (unsigned I = 0; I != E; ++I) {
6678 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006679 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006680 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006681 }
6682 }
6683 Enc += '}';
6684 TSC.addIfComplete(ID, Enc.substr(Start), false);
6685 return true;
6686}
6687
6688/// Appends type's qualifier to Enc.
6689/// This is done prior to appending the type's encoding.
6690static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6691 // Qualifiers are emitted in alphabetical order.
6692 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6693 int Lookup = 0;
6694 if (QT.isConstQualified())
6695 Lookup += 1<<0;
6696 if (QT.isRestrictQualified())
6697 Lookup += 1<<1;
6698 if (QT.isVolatileQualified())
6699 Lookup += 1<<2;
6700 Enc += Table[Lookup];
6701}
6702
6703/// Appends built-in types to Enc.
6704static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6705 const char *EncType;
6706 switch (BT->getKind()) {
6707 case BuiltinType::Void:
6708 EncType = "0";
6709 break;
6710 case BuiltinType::Bool:
6711 EncType = "b";
6712 break;
6713 case BuiltinType::Char_U:
6714 EncType = "uc";
6715 break;
6716 case BuiltinType::UChar:
6717 EncType = "uc";
6718 break;
6719 case BuiltinType::SChar:
6720 EncType = "sc";
6721 break;
6722 case BuiltinType::UShort:
6723 EncType = "us";
6724 break;
6725 case BuiltinType::Short:
6726 EncType = "ss";
6727 break;
6728 case BuiltinType::UInt:
6729 EncType = "ui";
6730 break;
6731 case BuiltinType::Int:
6732 EncType = "si";
6733 break;
6734 case BuiltinType::ULong:
6735 EncType = "ul";
6736 break;
6737 case BuiltinType::Long:
6738 EncType = "sl";
6739 break;
6740 case BuiltinType::ULongLong:
6741 EncType = "ull";
6742 break;
6743 case BuiltinType::LongLong:
6744 EncType = "sll";
6745 break;
6746 case BuiltinType::Float:
6747 EncType = "ft";
6748 break;
6749 case BuiltinType::Double:
6750 EncType = "d";
6751 break;
6752 case BuiltinType::LongDouble:
6753 EncType = "ld";
6754 break;
6755 default:
6756 return false;
6757 }
6758 Enc += EncType;
6759 return true;
6760}
6761
6762/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6763static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6764 const CodeGen::CodeGenModule &CGM,
6765 TypeStringCache &TSC) {
6766 Enc += "p(";
6767 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6768 return false;
6769 Enc += ')';
6770 return true;
6771}
6772
6773/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006774static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6775 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006776 const CodeGen::CodeGenModule &CGM,
6777 TypeStringCache &TSC, StringRef NoSizeEnc) {
6778 if (AT->getSizeModifier() != ArrayType::Normal)
6779 return false;
6780 Enc += "a(";
6781 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6782 CAT->getSize().toStringUnsigned(Enc);
6783 else
6784 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6785 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006786 // The Qualifiers should be attached to the type rather than the array.
6787 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006788 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6789 return false;
6790 Enc += ')';
6791 return true;
6792}
6793
6794/// Appends a function encoding to Enc, calling appendType for the return type
6795/// and the arguments.
6796static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6797 const CodeGen::CodeGenModule &CGM,
6798 TypeStringCache &TSC) {
6799 Enc += "f{";
6800 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6801 return false;
6802 Enc += "}(";
6803 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6804 // N.B. we are only interested in the adjusted param types.
6805 auto I = FPT->param_type_begin();
6806 auto E = FPT->param_type_end();
6807 if (I != E) {
6808 do {
6809 if (!appendType(Enc, *I, CGM, TSC))
6810 return false;
6811 ++I;
6812 if (I != E)
6813 Enc += ',';
6814 } while (I != E);
6815 if (FPT->isVariadic())
6816 Enc += ",va";
6817 } else {
6818 if (FPT->isVariadic())
6819 Enc += "va";
6820 else
6821 Enc += '0';
6822 }
6823 }
6824 Enc += ')';
6825 return true;
6826}
6827
6828/// Handles the type's qualifier before dispatching a call to handle specific
6829/// type encodings.
6830static bool appendType(SmallStringEnc &Enc, QualType QType,
6831 const CodeGen::CodeGenModule &CGM,
6832 TypeStringCache &TSC) {
6833
6834 QualType QT = QType.getCanonicalType();
6835
Robert Lytton6adb20f2014-06-05 09:06:21 +00006836 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6837 // The Qualifiers should be attached to the type rather than the array.
6838 // Thus we don't call appendQualifier() here.
6839 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6840
Robert Lytton844aeeb2014-05-02 09:33:20 +00006841 appendQualifier(Enc, QT);
6842
6843 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6844 return appendBuiltinType(Enc, BT);
6845
Robert Lytton844aeeb2014-05-02 09:33:20 +00006846 if (const PointerType *PT = QT->getAs<PointerType>())
6847 return appendPointerType(Enc, PT, CGM, TSC);
6848
6849 if (const EnumType *ET = QT->getAs<EnumType>())
6850 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6851
6852 if (const RecordType *RT = QT->getAsStructureType())
6853 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6854
6855 if (const RecordType *RT = QT->getAsUnionType())
6856 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6857
6858 if (const FunctionType *FT = QT->getAs<FunctionType>())
6859 return appendFunctionType(Enc, FT, CGM, TSC);
6860
6861 return false;
6862}
6863
6864static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6865 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6866 if (!D)
6867 return false;
6868
6869 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6870 if (FD->getLanguageLinkage() != CLanguageLinkage)
6871 return false;
6872 return appendType(Enc, FD->getType(), CGM, TSC);
6873 }
6874
6875 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6876 if (VD->getLanguageLinkage() != CLanguageLinkage)
6877 return false;
6878 QualType QT = VD->getType().getCanonicalType();
6879 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6880 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006881 // The Qualifiers should be attached to the type rather than the array.
6882 // Thus we don't call appendQualifier() here.
6883 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00006884 }
6885 return appendType(Enc, QT, CGM, TSC);
6886 }
6887 return false;
6888}
6889
6890
Robert Lytton0e076492013-08-13 09:43:10 +00006891//===----------------------------------------------------------------------===//
6892// Driver code
6893//===----------------------------------------------------------------------===//
6894
Rafael Espindola9f834732014-09-19 01:54:22 +00006895const llvm::Triple &CodeGenModule::getTriple() const {
6896 return getTarget().getTriple();
6897}
6898
6899bool CodeGenModule::supportsCOMDAT() const {
6900 return !getTriple().isOSBinFormatMachO();
6901}
6902
Chris Lattner2b037972010-07-29 02:01:43 +00006903const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006904 if (TheTargetCodeGenInfo)
6905 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006906
John McCallc8e01702013-04-16 22:48:15 +00006907 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00006908 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00006909 default:
Chris Lattner2b037972010-07-29 02:01:43 +00006910 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00006911
Derek Schuff09338a22012-09-06 17:37:28 +00006912 case llvm::Triple::le32:
6913 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00006914 case llvm::Triple::mips:
6915 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006916 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6917
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00006918 case llvm::Triple::mips64:
6919 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006920 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6921
Tim Northover25e8a672014-05-24 12:51:25 +00006922 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00006923 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00006924 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006925 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00006926 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00006927
Tim Northover573cbee2014-05-24 12:52:07 +00006928 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00006929 }
6930
Daniel Dunbard59655c2009-09-12 00:59:49 +00006931 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006932 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00006933 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006934 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006935 {
6936 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006937 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006938 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00006939 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00006940 (CodeGenOpts.FloatABI != "soft" &&
6941 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006942 Kind = ARMABIInfo::AAPCS_VFP;
6943
Derek Schuffa2020962012-10-16 22:30:41 +00006944 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00006945 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00006946 return *(TheTargetCodeGenInfo =
6947 new NaClARMTargetCodeGenInfo(Types, Kind));
6948 default:
6949 return *(TheTargetCodeGenInfo =
6950 new ARMTargetCodeGenInfo(Types, Kind));
6951 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006952 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00006953
John McCallea8d8bb2010-03-11 00:10:12 +00006954 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00006955 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00006956 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00006957 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00006958 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006959 if (getTarget().getABI() == "elfv2")
6960 Kind = PPC64_SVR4_ABIInfo::ELFv2;
6961
Ulrich Weigandb7122372014-07-21 00:48:09 +00006962 return *(TheTargetCodeGenInfo =
6963 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6964 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00006965 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00006966 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00006967 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00006968 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006969 if (getTarget().getABI() == "elfv1")
6970 Kind = PPC64_SVR4_ABIInfo::ELFv1;
6971
Ulrich Weigandb7122372014-07-21 00:48:09 +00006972 return *(TheTargetCodeGenInfo =
6973 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6974 }
John McCallea8d8bb2010-03-11 00:10:12 +00006975
Peter Collingbournec947aae2012-05-20 23:28:41 +00006976 case llvm::Triple::nvptx:
6977 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00006978 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006979
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006980 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00006981 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00006982
Ulrich Weigand47445072013-05-06 16:26:41 +00006983 case llvm::Triple::systemz:
6984 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6985
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006986 case llvm::Triple::tce:
6987 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6988
Eli Friedman33465822011-07-08 23:31:17 +00006989 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00006990 bool IsDarwinVectorABI = Triple.isOSDarwin();
6991 bool IsSmallStructInRegABI =
6992 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00006993 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00006994
John McCall1fe2a8c2013-06-18 02:46:29 +00006995 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00006996 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006997 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00006998 IsDarwinVectorABI, IsSmallStructInRegABI,
6999 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007000 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007001 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007002 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007003 new X86_32TargetCodeGenInfo(Types,
7004 IsDarwinVectorABI, IsSmallStructInRegABI,
7005 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007006 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007007 }
Eli Friedman33465822011-07-08 23:31:17 +00007008 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007009
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007010 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007011 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007012
Chris Lattner04dc9572010-08-31 16:44:54 +00007013 switch (Triple.getOS()) {
7014 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007015 return *(TheTargetCodeGenInfo =
7016 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Eli Benderskyd7c92032012-12-04 18:38:10 +00007017 case llvm::Triple::NaCl:
Alexander Musman09184fe2014-09-30 05:29:28 +00007018 return *(TheTargetCodeGenInfo =
7019 new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007020 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007021 return *(TheTargetCodeGenInfo =
7022 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007023 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007024 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007025 case llvm::Triple::hexagon:
7026 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007027 case llvm::Triple::sparcv9:
7028 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007029 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007030 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007031 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007032}