blob: 2226b7d9539ec08a113126aebd401ba83c44d9cf [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
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
Reid Klecknerb1be6832014-11-15 01:41:41 +000068/// Pass transparent unions as if they were the type of the first element. Sema
69/// should ensure that all elements of the union have the same "machine type".
70static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
71 if (const RecordType *UT = Ty->getAsUnionType()) {
72 const RecordDecl *UD = UT->getDecl();
73 if (UD->hasAttr<TransparentUnionAttr>()) {
74 assert(!UD->field_empty() && "sema created an empty transparent union");
75 return UD->field_begin()->getType();
76 }
77 }
78 return Ty;
79}
80
Mark Lacey3825e832013-10-06 01:33:34 +000081CGCXXABI &ABIInfo::getCXXABI() const {
82 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000083}
84
Chris Lattner2b037972010-07-29 02:01:43 +000085ASTContext &ABIInfo::getContext() const {
86 return CGT.getContext();
87}
88
89llvm::LLVMContext &ABIInfo::getVMContext() const {
90 return CGT.getLLVMContext();
91}
92
Micah Villmowdd31ca12012-10-08 16:25:52 +000093const llvm::DataLayout &ABIInfo::getDataLayout() const {
94 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000095}
96
John McCallc8e01702013-04-16 22:48:15 +000097const TargetInfo &ABIInfo::getTarget() const {
98 return CGT.getTarget();
99}
Chris Lattner2b037972010-07-29 02:01:43 +0000100
Reid Klecknere9f6a712014-10-31 17:10:41 +0000101bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
102 return false;
103}
104
105bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
106 uint64_t Members) const {
107 return false;
108}
109
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000110void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000111 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000112 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000113 switch (TheKind) {
114 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000115 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000116 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000117 Ty->print(OS);
118 else
119 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000120 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000121 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000122 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000123 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000124 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000125 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000126 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000127 case InAlloca:
128 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
129 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000130 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000131 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000132 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000133 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000134 break;
135 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000136 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000137 break;
138 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000139 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000140}
141
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000142TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
143
John McCall3480ef22011-08-30 01:42:09 +0000144// If someone can figure out a general rule for this, that would be great.
145// It's probably just doomed to be platform-dependent, though.
146unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
147 // Verified for:
148 // x86-64 FreeBSD, Linux, Darwin
149 // x86-32 FreeBSD, Linux, Darwin
150 // PowerPC Linux, Darwin
151 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000152 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000153 return 32;
154}
155
John McCalla729c622012-02-17 03:33:10 +0000156bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
157 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000158 // The following conventions are known to require this to be false:
159 // x86_stdcall
160 // MIPS
161 // For everything else, we just prefer false unless we opt out.
162 return false;
163}
164
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000165void
166TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
167 llvm::SmallString<24> &Opt) const {
168 // This assumes the user is passing a library name like "rt" instead of a
169 // filename like "librt.a/so", and that they don't care whether it's static or
170 // dynamic.
171 Opt = "-l";
172 Opt += Lib;
173}
174
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000175static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000176
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000177/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000178/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000179static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
180 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000181 if (FD->isUnnamedBitfield())
182 return true;
183
184 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000185
Eli Friedman0b3f2012011-11-18 03:47:20 +0000186 // Constant arrays of empty records count as empty, strip them off.
187 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000188 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000189 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
190 if (AT->getSize() == 0)
191 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000192 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000193 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000194
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000195 const RecordType *RT = FT->getAs<RecordType>();
196 if (!RT)
197 return false;
198
199 // C++ record fields are never empty, at least in the Itanium ABI.
200 //
201 // FIXME: We should use a predicate for whether this behavior is true in the
202 // current ABI.
203 if (isa<CXXRecordDecl>(RT->getDecl()))
204 return false;
205
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000206 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000207}
208
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000209/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000210/// fields. Note that a structure with a flexible array member is not
211/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000212static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000213 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000214 if (!RT)
215 return 0;
216 const RecordDecl *RD = RT->getDecl();
217 if (RD->hasFlexibleArrayMember())
218 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000219
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000220 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000221 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000222 for (const auto &I : CXXRD->bases())
223 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000224 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000225
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000226 for (const auto *I : RD->fields())
227 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000228 return false;
229 return true;
230}
231
232/// isSingleElementStruct - Determine if a structure is a "single
233/// element struct", i.e. it has exactly one non-empty field or
234/// exactly one field which is itself a single element
235/// struct. Structures with flexible array members are never
236/// considered single element structs.
237///
238/// \return The field declaration for the single non-empty field, if
239/// it exists.
240static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000241 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000242 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000243 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000244
245 const RecordDecl *RD = RT->getDecl();
246 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000247 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000248
Craig Topper8a13c412014-05-21 05:09:00 +0000249 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000250
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000251 // If this is a C++ record, check the bases first.
252 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000253 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000254 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000255 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000256 continue;
257
258 // If we already found an element then this isn't a single-element struct.
259 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000260 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000261
262 // If this is non-empty and not a single element struct, the composite
263 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000264 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000265 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000266 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000267 }
268 }
269
270 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000271 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000272 QualType FT = FD->getType();
273
274 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000275 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000276 continue;
277
278 // If we already found an element then this isn't a single-element
279 // struct.
280 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000281 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000282
283 // Treat single element arrays as the element.
284 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
285 if (AT->getSize().getZExtValue() != 1)
286 break;
287 FT = AT->getElementType();
288 }
289
John McCalla1dee5302010-08-22 10:59:02 +0000290 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000291 Found = FT.getTypePtr();
292 } else {
293 Found = isSingleElementStruct(FT, Context);
294 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000295 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000296 }
297 }
298
Eli Friedmanee945342011-11-18 01:25:50 +0000299 // We don't consider a struct a single-element struct if it has
300 // padding beyond the element type.
301 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000302 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000303
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000304 return Found;
305}
306
307static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000308 // Treat complex types as the element type.
309 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
310 Ty = CTy->getElementType();
311
312 // Check for a type which we know has a simple scalar argument-passing
313 // convention without any padding. (We're specifically looking for 32
314 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000315 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000316 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000317 return false;
318
319 uint64_t Size = Context.getTypeSize(Ty);
320 return Size == 32 || Size == 64;
321}
322
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000323/// canExpandIndirectArgument - Test whether an argument type which is to be
324/// passed indirectly (on the stack) would have the equivalent layout if it was
325/// expanded into separate arguments. If so, we prefer to do the latter to avoid
326/// inhibiting optimizations.
327///
328// FIXME: This predicate is missing many cases, currently it just follows
329// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
330// should probably make this smarter, or better yet make the LLVM backend
331// capable of handling it.
332static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
333 // We can only expand structure types.
334 const RecordType *RT = Ty->getAs<RecordType>();
335 if (!RT)
336 return false;
337
338 // We can only expand (C) structures.
339 //
340 // FIXME: This needs to be generalized to handle classes as well.
341 const RecordDecl *RD = RT->getDecl();
342 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
343 return false;
344
Eli Friedmane5c85622011-11-18 01:32:26 +0000345 uint64_t Size = 0;
346
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000347 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000348 if (!is32Or64BitBasicType(FD->getType(), Context))
349 return false;
350
351 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
352 // how to expand them yet, and the predicate for telling if a bitfield still
353 // counts as "basic" is more complicated than what we were doing previously.
354 if (FD->isBitField())
355 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000356
357 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000358 }
359
Eli Friedmane5c85622011-11-18 01:32:26 +0000360 // Make sure there are not any holes in the struct.
361 if (Size != Context.getTypeSize(Ty))
362 return false;
363
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000364 return true;
365}
366
367namespace {
368/// DefaultABIInfo - The default implementation for ABI specific
369/// details. This implementation provides information which results in
370/// self-consistent and sensible LLVM IR generation, but does not
371/// conform to any particular ABI.
372class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000373public:
374 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000375
Chris Lattner458b2aa2010-07-29 02:16:43 +0000376 ABIArgInfo classifyReturnType(QualType RetTy) const;
377 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000378
Craig Topper4f12f102014-03-12 06:41:41 +0000379 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000380 if (!getCXXABI().classifyReturnType(FI))
381 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000382 for (auto &I : FI.arguments())
383 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000384 }
385
Craig Topper4f12f102014-03-12 06:41:41 +0000386 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
387 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000388};
389
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000390class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
391public:
Chris Lattner2b037972010-07-29 02:01:43 +0000392 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
393 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000394};
395
396llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
397 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000398 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000399}
400
Chris Lattner458b2aa2010-07-29 02:16:43 +0000401ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000402 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000403 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000404
Chris Lattner9723d6c2010-03-11 18:19:55 +0000405 // Treat an enum type as its underlying type.
406 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
407 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000408
Chris Lattner9723d6c2010-03-11 18:19:55 +0000409 return (Ty->isPromotableIntegerType() ?
410 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000411}
412
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000413ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
414 if (RetTy->isVoidType())
415 return ABIArgInfo::getIgnore();
416
417 if (isAggregateTypeForABI(RetTy))
418 return ABIArgInfo::getIndirect(0);
419
420 // Treat an enum type as its underlying type.
421 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
422 RetTy = EnumTy->getDecl()->getIntegerType();
423
424 return (RetTy->isPromotableIntegerType() ?
425 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
426}
427
Derek Schuff09338a22012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000430//
431// This is a simplified version of the x86_32 ABI. Arguments and return values
432// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000433//===----------------------------------------------------------------------===//
434
435class PNaClABIInfo : public ABIInfo {
436 public:
437 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
438
439 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000440 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000441
Craig Topper4f12f102014-03-12 06:41:41 +0000442 void computeInfo(CGFunctionInfo &FI) const override;
443 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
444 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000445};
446
447class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
448 public:
449 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
450 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
451};
452
453void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000454 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
456
Reid Kleckner40ca9132014-05-13 22:05:45 +0000457 for (auto &I : FI.arguments())
458 I.info = classifyArgumentType(I.type);
459}
Derek Schuff09338a22012-09-06 17:37:28 +0000460
461llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
462 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000463 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000464}
465
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000466/// \brief Classify argument of given type \p Ty.
467ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000468 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000469 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000470 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000471 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000472 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
473 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000474 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000475 } else if (Ty->isFloatingType()) {
476 // Floating-point types don't go inreg.
477 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000478 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000479
480 return (Ty->isPromotableIntegerType() ?
481 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000482}
483
484ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
485 if (RetTy->isVoidType())
486 return ABIArgInfo::getIgnore();
487
Eli Benderskye20dad62013-04-04 22:49:35 +0000488 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000489 if (isAggregateTypeForABI(RetTy))
490 return ABIArgInfo::getIndirect(0);
491
492 // Treat an enum type as its underlying type.
493 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
494 RetTy = EnumTy->getDecl()->getIntegerType();
495
496 return (RetTy->isPromotableIntegerType() ?
497 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
498}
499
Chad Rosier651c1832013-03-25 21:00:27 +0000500/// IsX86_MMXType - Return true if this is an MMX type.
501bool IsX86_MMXType(llvm::Type *IRType) {
502 // 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 +0000503 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
504 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
505 IRType->getScalarSizeInBits() != 64;
506}
507
Jay Foad7c57be32011-07-11 09:56:20 +0000508static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000509 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000510 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000511 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
512 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
513 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000514 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000515 }
516
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000517 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000518 }
519
520 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000521 return Ty;
522}
523
Reid Kleckner80944df2014-10-31 22:00:51 +0000524/// Returns true if this type can be passed in SSE registers with the
525/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
526static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
527 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
528 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
529 return true;
530 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
531 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
532 // registers specially.
533 unsigned VecSize = Context.getTypeSize(VT);
534 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
535 return true;
536 }
537 return false;
538}
539
540/// Returns true if this aggregate is small enough to be passed in SSE registers
541/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
542static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
543 return NumMembers <= 4;
544}
545
Chris Lattner0cf24192010-06-28 20:05:43 +0000546//===----------------------------------------------------------------------===//
547// X86-32 ABI Implementation
548//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000549
Reid Kleckner661f35b2014-01-18 01:12:41 +0000550/// \brief Similar to llvm::CCState, but for Clang.
551struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000552 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000553
554 unsigned CC;
555 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000556 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000557};
558
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000559/// X86_32ABIInfo - The X86-32 ABI information.
560class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000561 enum Class {
562 Integer,
563 Float
564 };
565
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000566 static const unsigned MinABIStackAlignInBytes = 4;
567
David Chisnallde3a0692009-08-17 23:08:21 +0000568 bool IsDarwinVectorABI;
569 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000570 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000571 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572
573 static bool isRegisterSize(unsigned Size) {
574 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
575 }
576
Reid Kleckner80944df2014-10-31 22:00:51 +0000577 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
578 // FIXME: Assumes vectorcall is in use.
579 return isX86VectorTypeForVectorCall(getContext(), Ty);
580 }
581
582 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
583 uint64_t NumMembers) const override {
584 // FIXME: Assumes vectorcall is in use.
585 return isX86VectorCallAggregateSmallEnough(NumMembers);
586 }
587
Reid Kleckner40ca9132014-05-13 22:05:45 +0000588 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000589
Daniel Dunbar557893d2010-04-21 19:10:51 +0000590 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
591 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000592 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
593
594 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000595
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000596 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000597 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000598
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000599 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000600 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000601 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
602 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000603
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000604 /// \brief Rewrite the function info so that all memory arguments use
605 /// inalloca.
606 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
607
608 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
609 unsigned &StackOffset, ABIArgInfo &Info,
610 QualType Type) const;
611
Rafael Espindola75419dc2012-07-23 23:30:29 +0000612public:
613
Craig Topper4f12f102014-03-12 06:41:41 +0000614 void computeInfo(CGFunctionInfo &FI) const override;
615 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
616 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000617
Chad Rosier651c1832013-03-25 21:00:27 +0000618 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000619 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000620 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000621 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000622};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000623
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000624class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
625public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000626 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000627 bool d, bool p, bool w, unsigned r)
628 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000629
John McCall1fe2a8c2013-06-18 02:46:29 +0000630 static bool isStructReturnInRegABI(
631 const llvm::Triple &Triple, const CodeGenOptions &Opts);
632
Charles Davis4ea31ab2010-02-13 15:54:06 +0000633 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000634 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000635
Craig Topper4f12f102014-03-12 06:41:41 +0000636 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000637 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000638 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000639 return 4;
640 }
641
642 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000643 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000644
Jay Foad7c57be32011-07-11 09:56:20 +0000645 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000646 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000647 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000648 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
649 }
650
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000651 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
652 std::string &Constraints,
653 std::vector<llvm::Type *> &ResultRegTypes,
654 std::vector<llvm::Type *> &ResultTruncRegTypes,
655 std::vector<LValue> &ResultRegDests,
656 std::string &AsmString,
657 unsigned NumOutputs) const override;
658
Craig Topper4f12f102014-03-12 06:41:41 +0000659 llvm::Constant *
660 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000661 unsigned Sig = (0xeb << 0) | // jmp rel8
662 (0x06 << 8) | // .+0x08
663 ('F' << 16) |
664 ('T' << 24);
665 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
666 }
667
Joerg Sonnenberger096feeb2015-02-23 20:23:47 +0000668 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
669 return true;
670 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000671};
672
673}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000674
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000675/// Rewrite input constraint references after adding some output constraints.
676/// In the case where there is one output and one input and we add one output,
677/// we need to replace all operand references greater than or equal to 1:
678/// mov $0, $1
679/// mov eax, $1
680/// The result will be:
681/// mov $0, $2
682/// mov eax, $2
683static void rewriteInputConstraintReferences(unsigned FirstIn,
684 unsigned NumNewOuts,
685 std::string &AsmString) {
686 std::string Buf;
687 llvm::raw_string_ostream OS(Buf);
688 size_t Pos = 0;
689 while (Pos < AsmString.size()) {
690 size_t DollarStart = AsmString.find('$', Pos);
691 if (DollarStart == std::string::npos)
692 DollarStart = AsmString.size();
693 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
694 if (DollarEnd == std::string::npos)
695 DollarEnd = AsmString.size();
696 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
697 Pos = DollarEnd;
698 size_t NumDollars = DollarEnd - DollarStart;
699 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
700 // We have an operand reference.
701 size_t DigitStart = Pos;
702 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
703 if (DigitEnd == std::string::npos)
704 DigitEnd = AsmString.size();
705 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
706 unsigned OperandIndex;
707 if (!OperandStr.getAsInteger(10, OperandIndex)) {
708 if (OperandIndex >= FirstIn)
709 OperandIndex += NumNewOuts;
710 OS << OperandIndex;
711 } else {
712 OS << OperandStr;
713 }
714 Pos = DigitEnd;
715 }
716 }
717 AsmString = std::move(OS.str());
718}
719
720/// Add output constraints for EAX:EDX because they are return registers.
721void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
722 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
723 std::vector<llvm::Type *> &ResultRegTypes,
724 std::vector<llvm::Type *> &ResultTruncRegTypes,
725 std::vector<LValue> &ResultRegDests, std::string &AsmString,
726 unsigned NumOutputs) const {
727 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
728
729 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
730 // larger.
731 if (!Constraints.empty())
732 Constraints += ',';
733 if (RetWidth <= 32) {
734 Constraints += "={eax}";
735 ResultRegTypes.push_back(CGF.Int32Ty);
736 } else {
737 // Use the 'A' constraint for EAX:EDX.
738 Constraints += "=A";
739 ResultRegTypes.push_back(CGF.Int64Ty);
740 }
741
742 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
743 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
744 ResultTruncRegTypes.push_back(CoerceTy);
745
746 // Coerce the integer by bitcasting the return slot pointer.
747 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
748 CoerceTy->getPointerTo()));
749 ResultRegDests.push_back(ReturnSlot);
750
751 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
752}
753
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000754/// shouldReturnTypeInRegister - Determine if the given type should be
755/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000756bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
757 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000758 uint64_t Size = Context.getTypeSize(Ty);
759
760 // Type must be register sized.
761 if (!isRegisterSize(Size))
762 return false;
763
764 if (Ty->isVectorType()) {
765 // 64- and 128- bit vectors inside structures are not returned in
766 // registers.
767 if (Size == 64 || Size == 128)
768 return false;
769
770 return true;
771 }
772
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000773 // If this is a builtin, pointer, enum, complex type, member pointer, or
774 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000775 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000776 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000777 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000778 return true;
779
780 // Arrays are treated like records.
781 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000782 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000783
784 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000785 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000786 if (!RT) return false;
787
Anders Carlsson40446e82010-01-27 03:25:19 +0000788 // FIXME: Traverse bases here too.
789
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000790 // Structure types are passed in register if all fields would be
791 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000792 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000793 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000794 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000795 continue;
796
797 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000798 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000799 return false;
800 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000801 return true;
802}
803
Reid Kleckner661f35b2014-01-18 01:12:41 +0000804ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
805 // If the return value is indirect, then the hidden argument is consuming one
806 // integer register.
807 if (State.FreeRegs) {
808 --State.FreeRegs;
809 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
810 }
811 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
812}
813
Reid Kleckner40ca9132014-05-13 22:05:45 +0000814ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000815 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000816 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000817
Reid Kleckner80944df2014-10-31 22:00:51 +0000818 const Type *Base = nullptr;
819 uint64_t NumElts = 0;
820 if (State.CC == llvm::CallingConv::X86_VectorCall &&
821 isHomogeneousAggregate(RetTy, Base, NumElts)) {
822 // The LLVM struct type for such an aggregate should lower properly.
823 return ABIArgInfo::getDirect();
824 }
825
Chris Lattner458b2aa2010-07-29 02:16:43 +0000826 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000827 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000828 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000829 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000830
831 // 128-bit vectors are a special case; they are returned in
832 // registers and we need to make sure to pick a type the LLVM
833 // backend will like.
834 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000835 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000836 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000837
838 // Always return in register if it fits in a general purpose
839 // register, or if it is 64 bits and has a single element.
840 if ((Size == 8 || Size == 16 || Size == 32) ||
841 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000842 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000843 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000844
Reid Kleckner661f35b2014-01-18 01:12:41 +0000845 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000846 }
847
848 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000849 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000850
John McCalla1dee5302010-08-22 10:59:02 +0000851 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000852 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000853 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000854 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000855 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000856 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000857
David Chisnallde3a0692009-08-17 23:08:21 +0000858 // If specified, structs and unions are always indirect.
859 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000860 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000861
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000862 // Small structures which are register sized are generally returned
863 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000864 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000865 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000866
867 // As a special-case, if the struct is a "single-element" struct, and
868 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000869 // floating-point register. (MSVC does not apply this special case.)
870 // We apply a similar transformation for pointer types to improve the
871 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000872 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000873 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000874 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000875 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
876
877 // FIXME: We should be able to narrow this integer in cases with dead
878 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000879 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000880 }
881
Reid Kleckner661f35b2014-01-18 01:12:41 +0000882 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000883 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000884
Chris Lattner458b2aa2010-07-29 02:16:43 +0000885 // Treat an enum type as its underlying type.
886 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
887 RetTy = EnumTy->getDecl()->getIntegerType();
888
889 return (RetTy->isPromotableIntegerType() ?
890 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000891}
892
Eli Friedman7919bea2012-06-05 19:40:46 +0000893static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
894 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
895}
896
Daniel Dunbared23de32010-09-16 20:42:00 +0000897static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
898 const RecordType *RT = Ty->getAs<RecordType>();
899 if (!RT)
900 return 0;
901 const RecordDecl *RD = RT->getDecl();
902
903 // If this is a C++ record, check the bases first.
904 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000905 for (const auto &I : CXXRD->bases())
906 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000907 return false;
908
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000909 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000910 QualType FT = i->getType();
911
Eli Friedman7919bea2012-06-05 19:40:46 +0000912 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000913 return true;
914
915 if (isRecordWithSSEVectorType(Context, FT))
916 return true;
917 }
918
919 return false;
920}
921
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000922unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
923 unsigned Align) const {
924 // Otherwise, if the alignment is less than or equal to the minimum ABI
925 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000926 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000927 return 0; // Use default alignment.
928
929 // On non-Darwin, the stack type alignment is always 4.
930 if (!IsDarwinVectorABI) {
931 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000932 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000933 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000934
Daniel Dunbared23de32010-09-16 20:42:00 +0000935 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000936 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
937 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000938 return 16;
939
940 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000941}
942
Rafael Espindola703c47f2012-10-19 05:04:37 +0000943ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000944 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000945 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000946 if (State.FreeRegs) {
947 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000948 return ABIArgInfo::getIndirectInReg(0, false);
949 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000950 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000951 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000952
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000953 // Compute the byval alignment.
954 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
955 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
956 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000957 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000958
959 // If the stack alignment is less than the type alignment, realign the
960 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000961 bool Realign = TypeAlign > StackAlign;
962 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000963}
964
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000965X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
966 const Type *T = isSingleElementStruct(Ty, getContext());
967 if (!T)
968 T = Ty.getTypePtr();
969
970 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
971 BuiltinType::Kind K = BT->getKind();
972 if (K == BuiltinType::Float || K == BuiltinType::Double)
973 return Float;
974 }
975 return Integer;
976}
977
Reid Kleckner661f35b2014-01-18 01:12:41 +0000978bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
979 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000980 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000981 Class C = classify(Ty);
982 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000983 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000984
Rafael Espindola077dd592012-10-24 01:58:58 +0000985 unsigned Size = getContext().getTypeSize(Ty);
986 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000987
988 if (SizeInRegs == 0)
989 return false;
990
Reid Kleckner661f35b2014-01-18 01:12:41 +0000991 if (SizeInRegs > State.FreeRegs) {
992 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000993 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000994 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000995
Reid Kleckner661f35b2014-01-18 01:12:41 +0000996 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000997
Reid Kleckner80944df2014-10-31 22:00:51 +0000998 if (State.CC == llvm::CallingConv::X86_FastCall ||
999 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001000 if (Size > 32)
1001 return false;
1002
1003 if (Ty->isIntegralOrEnumerationType())
1004 return true;
1005
1006 if (Ty->isPointerType())
1007 return true;
1008
1009 if (Ty->isReferenceType())
1010 return true;
1011
Reid Kleckner661f35b2014-01-18 01:12:41 +00001012 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001013 NeedsPadding = true;
1014
Rafael Espindola077dd592012-10-24 01:58:58 +00001015 return false;
1016 }
1017
Rafael Espindola703c47f2012-10-19 05:04:37 +00001018 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001019}
1020
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001021ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1022 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001023 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001024
Reid Klecknerb1be6832014-11-15 01:41:41 +00001025 Ty = useFirstFieldIfTransparentUnion(Ty);
1026
Reid Kleckner80944df2014-10-31 22:00:51 +00001027 // Check with the C++ ABI first.
1028 const RecordType *RT = Ty->getAs<RecordType>();
1029 if (RT) {
1030 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1031 if (RAA == CGCXXABI::RAA_Indirect) {
1032 return getIndirectResult(Ty, false, State);
1033 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1034 // The field index doesn't matter, we'll fix it up later.
1035 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1036 }
1037 }
1038
1039 // vectorcall adds the concept of a homogenous vector aggregate, similar
1040 // to other targets.
1041 const Type *Base = nullptr;
1042 uint64_t NumElts = 0;
1043 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1044 isHomogeneousAggregate(Ty, Base, NumElts)) {
1045 if (State.FreeSSERegs >= NumElts) {
1046 State.FreeSSERegs -= NumElts;
1047 if (Ty->isBuiltinType() || Ty->isVectorType())
1048 return ABIArgInfo::getDirect();
1049 return ABIArgInfo::getExpand();
1050 }
1051 return getIndirectResult(Ty, /*ByVal=*/false, State);
1052 }
1053
1054 if (isAggregateTypeForABI(Ty)) {
1055 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001056 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001057 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001058 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001059
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001060 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001061 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001062 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001063 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001064
Eli Friedman9f061a32011-11-18 00:28:11 +00001065 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001066 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001067 return ABIArgInfo::getIgnore();
1068
Rafael Espindolafad28de2012-10-24 01:59:00 +00001069 llvm::LLVMContext &LLVMContext = getVMContext();
1070 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1071 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001072 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001073 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001074 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001075 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1076 return ABIArgInfo::getDirectInReg(Result);
1077 }
Craig Topper8a13c412014-05-21 05:09:00 +00001078 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001079
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001080 // Expand small (<= 128-bit) record types when we know that the stack layout
1081 // of those arguments will match the struct. This is important because the
1082 // LLVM backend isn't smart enough to remove byval, which inhibits many
1083 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001084 if (getContext().getTypeSize(Ty) <= 4*32 &&
1085 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001086 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001087 State.CC == llvm::CallingConv::X86_FastCall ||
1088 State.CC == llvm::CallingConv::X86_VectorCall,
1089 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001090
Reid Kleckner661f35b2014-01-18 01:12:41 +00001091 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001092 }
1093
Chris Lattnerd774ae92010-08-26 20:05:13 +00001094 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001095 // On Darwin, some vectors are passed in memory, we handle this by passing
1096 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001097 if (IsDarwinVectorABI) {
1098 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001099 if ((Size == 8 || Size == 16 || Size == 32) ||
1100 (Size == 64 && VT->getNumElements() == 1))
1101 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1102 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001103 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001104
Chad Rosier651c1832013-03-25 21:00:27 +00001105 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1106 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001107
Chris Lattnerd774ae92010-08-26 20:05:13 +00001108 return ABIArgInfo::getDirect();
1109 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001110
1111
Chris Lattner458b2aa2010-07-29 02:16:43 +00001112 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1113 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001114
Rafael Espindolafad28de2012-10-24 01:59:00 +00001115 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001116 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001117
1118 if (Ty->isPromotableIntegerType()) {
1119 if (InReg)
1120 return ABIArgInfo::getExtendInReg();
1121 return ABIArgInfo::getExtend();
1122 }
1123 if (InReg)
1124 return ABIArgInfo::getDirectInReg();
1125 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001126}
1127
Rafael Espindolaa6472962012-07-24 00:01:07 +00001128void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001129 CCState State(FI.getCallingConvention());
1130 if (State.CC == llvm::CallingConv::X86_FastCall)
1131 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001132 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1133 State.FreeRegs = 2;
1134 State.FreeSSERegs = 6;
1135 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001136 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001137 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001138 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001139
Reid Kleckner677539d2014-07-10 01:58:55 +00001140 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001141 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001142 } else if (FI.getReturnInfo().isIndirect()) {
1143 // The C++ ABI is not aware of register usage, so we have to check if the
1144 // return value was sret and put it in a register ourselves if appropriate.
1145 if (State.FreeRegs) {
1146 --State.FreeRegs; // The sret parameter consumes a register.
1147 FI.getReturnInfo().setInReg(true);
1148 }
1149 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001150
Peter Collingbournef7706832014-12-12 23:41:25 +00001151 // The chain argument effectively gives us another free register.
1152 if (FI.isChainCall())
1153 ++State.FreeRegs;
1154
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001155 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001156 for (auto &I : FI.arguments()) {
1157 I.info = classifyArgumentType(I.type, State);
1158 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001159 }
1160
1161 // If we needed to use inalloca for any argument, do a second pass and rewrite
1162 // all the memory arguments to use inalloca.
1163 if (UsedInAlloca)
1164 rewriteWithInAlloca(FI);
1165}
1166
1167void
1168X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1169 unsigned &StackOffset,
1170 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001171 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1172 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1173 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1174 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1175
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001176 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1177 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001178 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001179 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001180 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001181 unsigned NumBytes = StackOffset - OldOffset;
1182 assert(NumBytes);
1183 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1184 Ty = llvm::ArrayType::get(Ty, NumBytes);
1185 FrameFields.push_back(Ty);
1186 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001187}
1188
Reid Kleckner852361d2014-07-26 00:12:26 +00001189static bool isArgInAlloca(const ABIArgInfo &Info) {
1190 // Leave ignored and inreg arguments alone.
1191 switch (Info.getKind()) {
1192 case ABIArgInfo::InAlloca:
1193 return true;
1194 case ABIArgInfo::Indirect:
1195 assert(Info.getIndirectByVal());
1196 return true;
1197 case ABIArgInfo::Ignore:
1198 return false;
1199 case ABIArgInfo::Direct:
1200 case ABIArgInfo::Extend:
1201 case ABIArgInfo::Expand:
1202 if (Info.getInReg())
1203 return false;
1204 return true;
1205 }
1206 llvm_unreachable("invalid enum");
1207}
1208
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001209void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1210 assert(IsWin32StructABI && "inalloca only supported on win32");
1211
1212 // Build a packed struct type for all of the arguments in memory.
1213 SmallVector<llvm::Type *, 6> FrameFields;
1214
1215 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001216 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1217
1218 // Put 'this' into the struct before 'sret', if necessary.
1219 bool IsThisCall =
1220 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1221 ABIArgInfo &Ret = FI.getReturnInfo();
1222 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1223 isArgInAlloca(I->info)) {
1224 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1225 ++I;
1226 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001227
1228 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001229 if (Ret.isIndirect() && !Ret.getInReg()) {
1230 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1231 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001232 // On Windows, the hidden sret parameter is always returned in eax.
1233 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001234 }
1235
1236 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001237 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001238 ++I;
1239
1240 // Put arguments passed in memory into the struct.
1241 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001242 if (isArgInAlloca(I->info))
1243 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001244 }
1245
1246 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1247 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001248}
1249
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001250llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1251 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001252 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001253
1254 CGBuilderTy &Builder = CGF.Builder;
1255 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1256 "ap");
1257 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001258
1259 // Compute if the address needs to be aligned
1260 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1261 Align = getTypeStackAlignInBytes(Ty, Align);
1262 Align = std::max(Align, 4U);
1263 if (Align > 4) {
1264 // addr = (addr + align - 1) & -align;
1265 llvm::Value *Offset =
1266 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1267 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1268 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1269 CGF.Int32Ty);
1270 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1271 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1272 Addr->getType(),
1273 "ap.cur.aligned");
1274 }
1275
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001276 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001277 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1279
1280 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001281 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001282 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001283 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001284 "ap.next");
1285 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1286
1287 return AddrTyped;
1288}
1289
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001290bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1291 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1292 assert(Triple.getArch() == llvm::Triple::x86);
1293
1294 switch (Opts.getStructReturnConvention()) {
1295 case CodeGenOptions::SRCK_Default:
1296 break;
1297 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1298 return false;
1299 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1300 return true;
1301 }
1302
1303 if (Triple.isOSDarwin())
1304 return true;
1305
1306 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001307 case llvm::Triple::DragonFly:
1308 case llvm::Triple::FreeBSD:
1309 case llvm::Triple::OpenBSD:
1310 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001311 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001312 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001313 default:
1314 return false;
1315 }
1316}
1317
Charles Davis4ea31ab2010-02-13 15:54:06 +00001318void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1319 llvm::GlobalValue *GV,
1320 CodeGen::CodeGenModule &CGM) const {
1321 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1322 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1323 // Get the LLVM function.
1324 llvm::Function *Fn = cast<llvm::Function>(GV);
1325
1326 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001327 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001328 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001329 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1330 llvm::AttributeSet::get(CGM.getLLVMContext(),
1331 llvm::AttributeSet::FunctionIndex,
1332 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001333 }
1334 }
1335}
1336
John McCallbeec5a02010-03-06 00:35:14 +00001337bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1338 CodeGen::CodeGenFunction &CGF,
1339 llvm::Value *Address) const {
1340 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001341
Chris Lattnerece04092012-02-07 00:39:47 +00001342 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001343
John McCallbeec5a02010-03-06 00:35:14 +00001344 // 0-7 are the eight integer registers; the order is different
1345 // on Darwin (for EH), but the range is the same.
1346 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001347 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001348
John McCallc8e01702013-04-16 22:48:15 +00001349 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001350 // 12-16 are st(0..4). Not sure why we stop at 4.
1351 // These have size 16, which is sizeof(long double) on
1352 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001353 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001354 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001355
John McCallbeec5a02010-03-06 00:35:14 +00001356 } else {
1357 // 9 is %eflags, which doesn't get a size on Darwin for some
1358 // reason.
1359 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1360
1361 // 11-16 are st(0..5). Not sure why we stop at 5.
1362 // These have size 12, which is sizeof(long double) on
1363 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001364 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001365 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1366 }
John McCallbeec5a02010-03-06 00:35:14 +00001367
1368 return false;
1369}
1370
Chris Lattner0cf24192010-06-28 20:05:43 +00001371//===----------------------------------------------------------------------===//
1372// X86-64 ABI Implementation
1373//===----------------------------------------------------------------------===//
1374
1375
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001376namespace {
1377/// X86_64ABIInfo - The X86_64 ABI information.
1378class X86_64ABIInfo : public ABIInfo {
1379 enum Class {
1380 Integer = 0,
1381 SSE,
1382 SSEUp,
1383 X87,
1384 X87Up,
1385 ComplexX87,
1386 NoClass,
1387 Memory
1388 };
1389
1390 /// merge - Implement the X86_64 ABI merging algorithm.
1391 ///
1392 /// Merge an accumulating classification \arg Accum with a field
1393 /// classification \arg Field.
1394 ///
1395 /// \param Accum - The accumulating classification. This should
1396 /// always be either NoClass or the result of a previous merge
1397 /// call. In addition, this should never be Memory (the caller
1398 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001399 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001401 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1402 ///
1403 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1404 /// final MEMORY or SSE classes when necessary.
1405 ///
1406 /// \param AggregateSize - The size of the current aggregate in
1407 /// the classification process.
1408 ///
1409 /// \param Lo - The classification for the parts of the type
1410 /// residing in the low word of the containing object.
1411 ///
1412 /// \param Hi - The classification for the parts of the type
1413 /// residing in the higher words of the containing object.
1414 ///
1415 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1416
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001417 /// classify - Determine the x86_64 register classes in which the
1418 /// given type T should be passed.
1419 ///
1420 /// \param Lo - The classification for the parts of the type
1421 /// residing in the low word of the containing object.
1422 ///
1423 /// \param Hi - The classification for the parts of the type
1424 /// residing in the high word of the containing object.
1425 ///
1426 /// \param OffsetBase - The bit offset of this type in the
1427 /// containing object. Some parameters are classified different
1428 /// depending on whether they straddle an eightbyte boundary.
1429 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001430 /// \param isNamedArg - Whether the argument in question is a "named"
1431 /// argument, as used in AMD64-ABI 3.5.7.
1432 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001433 /// If a word is unused its result will be NoClass; if a type should
1434 /// be passed in Memory then at least the classification of \arg Lo
1435 /// will be Memory.
1436 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001437 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001438 ///
1439 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1440 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001441 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1442 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001443
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001444 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001445 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1446 unsigned IROffset, QualType SourceTy,
1447 unsigned SourceOffset) const;
1448 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1449 unsigned IROffset, QualType SourceTy,
1450 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001451
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001452 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001453 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001454 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001455
1456 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001457 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001458 ///
1459 /// \param freeIntRegs - The number of free integer registers remaining
1460 /// available.
1461 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001462
Chris Lattner458b2aa2010-07-29 02:16:43 +00001463 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001464
Bill Wendling5cd41c42010-10-18 03:41:31 +00001465 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001466 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001467 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001468 unsigned &neededSSE,
1469 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001470
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001471 bool IsIllegalVectorType(QualType Ty) const;
1472
John McCalle0fda732011-04-21 01:20:55 +00001473 /// The 0.98 ABI revision clarified a lot of ambiguities,
1474 /// unfortunately in ways that were not always consistent with
1475 /// certain previous compilers. In particular, platforms which
1476 /// required strict binary compatibility with older versions of GCC
1477 /// may need to exempt themselves.
1478 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001479 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001480 }
1481
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001482 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001483 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1484 // 64-bit hardware.
1485 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001486
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001487public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001488 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001489 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001490 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001491 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001492
John McCalla729c622012-02-17 03:33:10 +00001493 bool isPassedUsingAVXType(QualType type) const {
1494 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001495 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001496 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1497 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001498 if (info.isDirect()) {
1499 llvm::Type *ty = info.getCoerceToType();
1500 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1501 return (vectorTy->getBitWidth() > 128);
1502 }
1503 return false;
1504 }
1505
Craig Topper4f12f102014-03-12 06:41:41 +00001506 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001507
Craig Topper4f12f102014-03-12 06:41:41 +00001508 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1509 CodeGenFunction &CGF) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001510
1511 bool has64BitPointers() const {
1512 return Has64BitPointers;
1513 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001514};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001515
Chris Lattner04dc9572010-08-31 16:44:54 +00001516/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001517class WinX86_64ABIInfo : public ABIInfo {
1518
Reid Kleckner80944df2014-10-31 22:00:51 +00001519 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1520 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001521
Chris Lattner04dc9572010-08-31 16:44:54 +00001522public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001523 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1524
Craig Topper4f12f102014-03-12 06:41:41 +00001525 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001526
Craig Topper4f12f102014-03-12 06:41:41 +00001527 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1528 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001529
1530 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1531 // FIXME: Assumes vectorcall is in use.
1532 return isX86VectorTypeForVectorCall(getContext(), Ty);
1533 }
1534
1535 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1536 uint64_t NumMembers) const override {
1537 // FIXME: Assumes vectorcall is in use.
1538 return isX86VectorCallAggregateSmallEnough(NumMembers);
1539 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001540};
1541
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001542class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001543 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001544public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001545 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001546 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001547
John McCalla729c622012-02-17 03:33:10 +00001548 const X86_64ABIInfo &getABIInfo() const {
1549 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1550 }
1551
Craig Topper4f12f102014-03-12 06:41:41 +00001552 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001553 return 7;
1554 }
1555
1556 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001557 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001558 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001559
John McCall943fae92010-05-27 06:19:26 +00001560 // 0-15 are the 16 integer registers.
1561 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001562 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001563 return false;
1564 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001565
Jay Foad7c57be32011-07-11 09:56:20 +00001566 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001567 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001568 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001569 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1570 }
1571
John McCalla729c622012-02-17 03:33:10 +00001572 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001573 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001574 // The default CC on x86-64 sets %al to the number of SSA
1575 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001576 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001577 // that when AVX types are involved: the ABI explicitly states it is
1578 // undefined, and it doesn't work in practice because of how the ABI
1579 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001580 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001581 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001582 for (CallArgList::const_iterator
1583 it = args.begin(), ie = args.end(); it != ie; ++it) {
1584 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1585 HasAVXType = true;
1586 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001587 }
1588 }
John McCalla729c622012-02-17 03:33:10 +00001589
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001590 if (!HasAVXType)
1591 return true;
1592 }
John McCallcbc038a2011-09-21 08:08:30 +00001593
John McCalla729c622012-02-17 03:33:10 +00001594 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001595 }
1596
Craig Topper4f12f102014-03-12 06:41:41 +00001597 llvm::Constant *
1598 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001599 unsigned Sig;
1600 if (getABIInfo().has64BitPointers())
1601 Sig = (0xeb << 0) | // jmp rel8
1602 (0x0a << 8) | // .+0x0c
1603 ('F' << 16) |
1604 ('T' << 24);
1605 else
1606 Sig = (0xeb << 0) | // jmp rel8
1607 (0x06 << 8) | // .+0x08
1608 ('F' << 16) |
1609 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001610 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1611 }
1612
Alexander Musman09184fe2014-09-30 05:29:28 +00001613 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1614 return HasAVX ? 32 : 16;
1615 }
Joerg Sonnenberger096feeb2015-02-23 20:23:47 +00001616
1617 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
1618 return true;
1619 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001620};
1621
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001622class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1623public:
1624 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1625 : X86_64TargetCodeGenInfo(CGT, HasAVX) {}
1626
1627 void getDependentLibraryOption(llvm::StringRef Lib,
1628 llvm::SmallString<24> &Opt) const {
1629 Opt = "\01";
1630 Opt += Lib;
1631 }
1632};
1633
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001634static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001635 // If the argument does not end in .lib, automatically add the suffix.
1636 // If the argument contains a space, enclose it in quotes.
1637 // This matches the behavior of MSVC.
1638 bool Quote = (Lib.find(" ") != StringRef::npos);
1639 std::string ArgStr = Quote ? "\"" : "";
1640 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001641 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001642 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001643 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001644 return ArgStr;
1645}
1646
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001647class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1648public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001649 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1650 bool d, bool p, bool w, unsigned RegParms)
1651 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001652
Hans Wennborg77dc2362015-01-20 19:45:50 +00001653 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1654 CodeGen::CodeGenModule &CGM) const override;
1655
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001656 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001657 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001658 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001659 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001660 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001661
1662 void getDetectMismatchOption(llvm::StringRef Name,
1663 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001664 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001665 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001666 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001667};
1668
Hans Wennborg77dc2362015-01-20 19:45:50 +00001669static void addStackProbeSizeTargetAttribute(const Decl *D,
1670 llvm::GlobalValue *GV,
1671 CodeGen::CodeGenModule &CGM) {
1672 if (isa<FunctionDecl>(D)) {
1673 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1674 llvm::Function *Fn = cast<llvm::Function>(GV);
1675
1676 Fn->addFnAttr("stack-probe-size", llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
1677 }
1678 }
1679}
1680
1681void WinX86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1682 llvm::GlobalValue *GV,
1683 CodeGen::CodeGenModule &CGM) const {
1684 X86_32TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1685
1686 addStackProbeSizeTargetAttribute(D, GV, CGM);
1687}
1688
Chris Lattner04dc9572010-08-31 16:44:54 +00001689class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001690 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001691public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001692 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1693 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001694
Hans Wennborg77dc2362015-01-20 19:45:50 +00001695 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1696 CodeGen::CodeGenModule &CGM) const override;
1697
Craig Topper4f12f102014-03-12 06:41:41 +00001698 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001699 return 7;
1700 }
1701
1702 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001703 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001704 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001705
Chris Lattner04dc9572010-08-31 16:44:54 +00001706 // 0-15 are the 16 integer registers.
1707 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001708 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001709 return false;
1710 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001711
1712 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001713 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001714 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001715 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001716 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001717
1718 void getDetectMismatchOption(llvm::StringRef Name,
1719 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001720 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001721 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001722 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001723
1724 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1725 return HasAVX ? 32 : 16;
1726 }
Reid Kleckner533bd172015-03-04 19:24:16 +00001727
1728 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
1729 return true;
1730 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001731};
1732
Hans Wennborg77dc2362015-01-20 19:45:50 +00001733void WinX86_64TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1734 llvm::GlobalValue *GV,
1735 CodeGen::CodeGenModule &CGM) const {
1736 TargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
1737
1738 addStackProbeSizeTargetAttribute(D, GV, CGM);
1739}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001740}
1741
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001742void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1743 Class &Hi) const {
1744 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1745 //
1746 // (a) If one of the classes is Memory, the whole argument is passed in
1747 // memory.
1748 //
1749 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1750 // memory.
1751 //
1752 // (c) If the size of the aggregate exceeds two eightbytes and the first
1753 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1754 // argument is passed in memory. NOTE: This is necessary to keep the
1755 // ABI working for processors that don't support the __m256 type.
1756 //
1757 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1758 //
1759 // Some of these are enforced by the merging logic. Others can arise
1760 // only with unions; for example:
1761 // union { _Complex double; unsigned; }
1762 //
1763 // Note that clauses (b) and (c) were added in 0.98.
1764 //
1765 if (Hi == Memory)
1766 Lo = Memory;
1767 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1768 Lo = Memory;
1769 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1770 Lo = Memory;
1771 if (Hi == SSEUp && Lo != SSE)
1772 Hi = SSE;
1773}
1774
Chris Lattnerd776fb12010-06-28 21:43:59 +00001775X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001776 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1777 // classified recursively so that always two fields are
1778 // considered. The resulting class is calculated according to
1779 // the classes of the fields in the eightbyte:
1780 //
1781 // (a) If both classes are equal, this is the resulting class.
1782 //
1783 // (b) If one of the classes is NO_CLASS, the resulting class is
1784 // the other class.
1785 //
1786 // (c) If one of the classes is MEMORY, the result is the MEMORY
1787 // class.
1788 //
1789 // (d) If one of the classes is INTEGER, the result is the
1790 // INTEGER.
1791 //
1792 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1793 // MEMORY is used as class.
1794 //
1795 // (f) Otherwise class SSE is used.
1796
1797 // Accum should never be memory (we should have returned) or
1798 // ComplexX87 (because this cannot be passed in a structure).
1799 assert((Accum != Memory && Accum != ComplexX87) &&
1800 "Invalid accumulated classification during merge.");
1801 if (Accum == Field || Field == NoClass)
1802 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001803 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001804 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001805 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001806 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001807 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001808 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001809 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1810 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001811 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001812 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001813}
1814
Chris Lattner5c740f12010-06-30 19:14:05 +00001815void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001816 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001817 // FIXME: This code can be simplified by introducing a simple value class for
1818 // Class pairs with appropriate constructor methods for the various
1819 // situations.
1820
1821 // FIXME: Some of the split computations are wrong; unaligned vectors
1822 // shouldn't be passed in registers for example, so there is no chance they
1823 // can straddle an eightbyte. Verify & simplify.
1824
1825 Lo = Hi = NoClass;
1826
1827 Class &Current = OffsetBase < 64 ? Lo : Hi;
1828 Current = Memory;
1829
John McCall9dd450b2009-09-21 23:43:11 +00001830 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001831 BuiltinType::Kind k = BT->getKind();
1832
1833 if (k == BuiltinType::Void) {
1834 Current = NoClass;
1835 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1836 Lo = Integer;
1837 Hi = Integer;
1838 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1839 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001840 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1841 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001842 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001843 Current = SSE;
1844 } else if (k == BuiltinType::LongDouble) {
1845 Lo = X87;
1846 Hi = X87Up;
1847 }
1848 // FIXME: _Decimal32 and _Decimal64 are SSE.
1849 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001850 return;
1851 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001852
Chris Lattnerd776fb12010-06-28 21:43:59 +00001853 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001854 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001855 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001856 return;
1857 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001858
Chris Lattnerd776fb12010-06-28 21:43:59 +00001859 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001860 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001861 return;
1862 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001863
Chris Lattnerd776fb12010-06-28 21:43:59 +00001864 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001865 if (Ty->isMemberFunctionPointerType()) {
1866 if (Has64BitPointers) {
1867 // If Has64BitPointers, this is an {i64, i64}, so classify both
1868 // Lo and Hi now.
1869 Lo = Hi = Integer;
1870 } else {
1871 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1872 // straddles an eightbyte boundary, Hi should be classified as well.
1873 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1874 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1875 if (EB_FuncPtr != EB_ThisAdj) {
1876 Lo = Hi = Integer;
1877 } else {
1878 Current = Integer;
1879 }
1880 }
1881 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001882 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001883 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001884 return;
1885 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001886
Chris Lattnerd776fb12010-06-28 21:43:59 +00001887 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001888 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001889 if (Size == 32) {
1890 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1891 // float> as integer.
1892 Current = Integer;
1893
1894 // If this type crosses an eightbyte boundary, it should be
1895 // split.
1896 uint64_t EB_Real = (OffsetBase) / 64;
1897 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1898 if (EB_Real != EB_Imag)
1899 Hi = Lo;
1900 } else if (Size == 64) {
1901 // gcc passes <1 x double> in memory. :(
1902 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1903 return;
1904
1905 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001906 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001907 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1908 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1909 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001910 Current = Integer;
1911 else
1912 Current = SSE;
1913
1914 // If this type crosses an eightbyte boundary, it should be
1915 // split.
1916 if (OffsetBase && OffsetBase != 64)
1917 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001918 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001919 // Arguments of 256-bits are split into four eightbyte chunks. The
1920 // least significant one belongs to class SSE and all the others to class
1921 // SSEUP. The original Lo and Hi design considers that types can't be
1922 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1923 // This design isn't correct for 256-bits, but since there're no cases
1924 // where the upper parts would need to be inspected, avoid adding
1925 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001926 //
1927 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1928 // registers if they are "named", i.e. not part of the "..." of a
1929 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001930 Lo = SSE;
1931 Hi = SSEUp;
1932 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001933 return;
1934 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001935
Chris Lattnerd776fb12010-06-28 21:43:59 +00001936 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001937 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001938
Chris Lattner2b037972010-07-29 02:01:43 +00001939 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001940 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001941 if (Size <= 64)
1942 Current = Integer;
1943 else if (Size <= 128)
1944 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001945 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001946 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001947 else if (ET == getContext().DoubleTy ||
1948 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001949 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001950 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001951 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001952 Current = ComplexX87;
1953
1954 // If this complex type crosses an eightbyte boundary then it
1955 // should be split.
1956 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001957 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001958 if (Hi == NoClass && EB_Real != EB_Imag)
1959 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001960
Chris Lattnerd776fb12010-06-28 21:43:59 +00001961 return;
1962 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001963
Chris Lattner2b037972010-07-29 02:01:43 +00001964 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001965 // Arrays are treated like structures.
1966
Chris Lattner2b037972010-07-29 02:01:43 +00001967 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001968
1969 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001970 // than four eightbytes, ..., it has class MEMORY.
1971 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001972 return;
1973
1974 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1975 // fields, it has class MEMORY.
1976 //
1977 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001978 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001979 return;
1980
1981 // Otherwise implement simplified merge. We could be smarter about
1982 // this, but it isn't worth it and would be harder to verify.
1983 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001984 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001985 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001986
1987 // The only case a 256-bit wide vector could be used is when the array
1988 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1989 // to work for sizes wider than 128, early check and fallback to memory.
1990 if (Size > 128 && EltSize != 256)
1991 return;
1992
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001993 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1994 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001995 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001996 Lo = merge(Lo, FieldLo);
1997 Hi = merge(Hi, FieldHi);
1998 if (Lo == Memory || Hi == Memory)
1999 break;
2000 }
2001
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002002 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002003 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002004 return;
2005 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002006
Chris Lattnerd776fb12010-06-28 21:43:59 +00002007 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002008 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002009
2010 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002011 // than four eightbytes, ..., it has class MEMORY.
2012 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002013 return;
2014
Anders Carlsson20759ad2009-09-16 15:53:40 +00002015 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2016 // copy constructor or a non-trivial destructor, it is passed by invisible
2017 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002018 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002019 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002020
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002021 const RecordDecl *RD = RT->getDecl();
2022
2023 // Assume variable sized types are passed in memory.
2024 if (RD->hasFlexibleArrayMember())
2025 return;
2026
Chris Lattner2b037972010-07-29 02:01:43 +00002027 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002028
2029 // Reset Lo class, this will be recomputed.
2030 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002031
2032 // If this is a C++ record, classify the bases first.
2033 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002034 for (const auto &I : CXXRD->bases()) {
2035 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002036 "Unexpected base class!");
2037 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002038 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002039
2040 // Classify this field.
2041 //
2042 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2043 // single eightbyte, each is classified separately. Each eightbyte gets
2044 // initialized to class NO_CLASS.
2045 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002046 uint64_t Offset =
2047 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002048 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002049 Lo = merge(Lo, FieldLo);
2050 Hi = merge(Hi, FieldHi);
2051 if (Lo == Memory || Hi == Memory)
2052 break;
2053 }
2054 }
2055
2056 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002057 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002058 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002059 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002060 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2061 bool BitField = i->isBitField();
2062
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002063 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2064 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002065 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002066 // The only case a 256-bit wide vector could be used is when the struct
2067 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2068 // to work for sizes wider than 128, early check and fallback to memory.
2069 //
2070 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2071 Lo = Memory;
2072 return;
2073 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002074 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002075 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076 Lo = Memory;
2077 return;
2078 }
2079
2080 // Classify this field.
2081 //
2082 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2083 // exceeds a single eightbyte, each is classified
2084 // separately. Each eightbyte gets initialized to class
2085 // NO_CLASS.
2086 Class FieldLo, FieldHi;
2087
2088 // Bit-fields require special handling, they do not force the
2089 // structure to be passed in memory even if unaligned, and
2090 // therefore they can straddle an eightbyte.
2091 if (BitField) {
2092 // Ignore padding bit-fields.
2093 if (i->isUnnamedBitfield())
2094 continue;
2095
2096 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002097 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002098
2099 uint64_t EB_Lo = Offset / 64;
2100 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002101
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002102 if (EB_Lo) {
2103 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2104 FieldLo = NoClass;
2105 FieldHi = Integer;
2106 } else {
2107 FieldLo = Integer;
2108 FieldHi = EB_Hi ? Integer : NoClass;
2109 }
2110 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002111 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002112 Lo = merge(Lo, FieldLo);
2113 Hi = merge(Hi, FieldHi);
2114 if (Lo == Memory || Hi == Memory)
2115 break;
2116 }
2117
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002118 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002119 }
2120}
2121
Chris Lattner22a931e2010-06-29 06:01:59 +00002122ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002123 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2124 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002125 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002126 // Treat an enum type as its underlying type.
2127 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2128 Ty = EnumTy->getDecl()->getIntegerType();
2129
2130 return (Ty->isPromotableIntegerType() ?
2131 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2132 }
2133
2134 return ABIArgInfo::getIndirect(0);
2135}
2136
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002137bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2138 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2139 uint64_t Size = getContext().getTypeSize(VecTy);
2140 unsigned LargestVector = HasAVX ? 256 : 128;
2141 if (Size <= 64 || Size > LargestVector)
2142 return true;
2143 }
2144
2145 return false;
2146}
2147
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002148ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2149 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002150 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2151 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002152 //
2153 // This assumption is optimistic, as there could be free registers available
2154 // when we need to pass this argument in memory, and LLVM could try to pass
2155 // the argument in the free register. This does not seem to happen currently,
2156 // but this code would be much safer if we could mark the argument with
2157 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002158 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002159 // Treat an enum type as its underlying type.
2160 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2161 Ty = EnumTy->getDecl()->getIntegerType();
2162
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002163 return (Ty->isPromotableIntegerType() ?
2164 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002165 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002166
Mark Lacey3825e832013-10-06 01:33:34 +00002167 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002168 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002169
Chris Lattner44c2b902011-05-22 23:21:23 +00002170 // Compute the byval alignment. We specify the alignment of the byval in all
2171 // cases so that the mid-level optimizer knows the alignment of the byval.
2172 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002173
2174 // Attempt to avoid passing indirect results using byval when possible. This
2175 // is important for good codegen.
2176 //
2177 // We do this by coercing the value into a scalar type which the backend can
2178 // handle naturally (i.e., without using byval).
2179 //
2180 // For simplicity, we currently only do this when we have exhausted all of the
2181 // free integer registers. Doing this when there are free integer registers
2182 // would require more care, as we would have to ensure that the coerced value
2183 // did not claim the unused register. That would require either reording the
2184 // arguments to the function (so that any subsequent inreg values came first),
2185 // or only doing this optimization when there were no following arguments that
2186 // might be inreg.
2187 //
2188 // We currently expect it to be rare (particularly in well written code) for
2189 // arguments to be passed on the stack when there are still free integer
2190 // registers available (this would typically imply large structs being passed
2191 // by value), so this seems like a fair tradeoff for now.
2192 //
2193 // We can revisit this if the backend grows support for 'onstack' parameter
2194 // attributes. See PR12193.
2195 if (freeIntRegs == 0) {
2196 uint64_t Size = getContext().getTypeSize(Ty);
2197
2198 // If this type fits in an eightbyte, coerce it into the matching integral
2199 // type, which will end up on the stack (with alignment 8).
2200 if (Align == 8 && Size <= 64)
2201 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2202 Size));
2203 }
2204
Chris Lattner44c2b902011-05-22 23:21:23 +00002205 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002206}
2207
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002208/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2209/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002210llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002211 // Wrapper structs/arrays that only contain vectors are passed just like
2212 // vectors; strip them off if present.
2213 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2214 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002215
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002216 llvm::Type *IRType = CGT.ConvertType(Ty);
Benjamin Kramer83b1bf32015-03-02 16:09:24 +00002217 assert(isa<llvm::VectorType>(IRType) &&
2218 "Trying to return a non-vector type in a vector register!");
2219 return IRType;
Chris Lattner4200fe42010-07-29 04:56:46 +00002220}
2221
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002222/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2223/// is known to either be off the end of the specified type or being in
2224/// alignment padding. The user type specified is known to be at most 128 bits
2225/// in size, and have passed through X86_64ABIInfo::classify with a successful
2226/// classification that put one of the two halves in the INTEGER class.
2227///
2228/// It is conservatively correct to return false.
2229static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2230 unsigned EndBit, ASTContext &Context) {
2231 // If the bytes being queried are off the end of the type, there is no user
2232 // data hiding here. This handles analysis of builtins, vectors and other
2233 // types that don't contain interesting padding.
2234 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2235 if (TySize <= StartBit)
2236 return true;
2237
Chris Lattner98076a22010-07-29 07:43:55 +00002238 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2239 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2240 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2241
2242 // Check each element to see if the element overlaps with the queried range.
2243 for (unsigned i = 0; i != NumElts; ++i) {
2244 // If the element is after the span we care about, then we're done..
2245 unsigned EltOffset = i*EltSize;
2246 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002247
Chris Lattner98076a22010-07-29 07:43:55 +00002248 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2249 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2250 EndBit-EltOffset, Context))
2251 return false;
2252 }
2253 // If it overlaps no elements, then it is safe to process as padding.
2254 return true;
2255 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002256
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002257 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2258 const RecordDecl *RD = RT->getDecl();
2259 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002260
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002261 // If this is a C++ record, check the bases first.
2262 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002263 for (const auto &I : CXXRD->bases()) {
2264 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002265 "Unexpected base class!");
2266 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002267 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002268
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002269 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002270 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002271 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002272
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002273 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002274 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002275 EndBit-BaseOffset, Context))
2276 return false;
2277 }
2278 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002279
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002280 // Verify that no field has data that overlaps the region of interest. Yes
2281 // this could be sped up a lot by being smarter about queried fields,
2282 // however we're only looking at structs up to 16 bytes, so we don't care
2283 // much.
2284 unsigned idx = 0;
2285 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2286 i != e; ++i, ++idx) {
2287 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002288
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002289 // If we found a field after the region we care about, then we're done.
2290 if (FieldOffset >= EndBit) break;
2291
2292 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2293 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2294 Context))
2295 return false;
2296 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002297
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002298 // If nothing in this record overlapped the area of interest, then we're
2299 // clean.
2300 return true;
2301 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002302
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002303 return false;
2304}
2305
Chris Lattnere556a712010-07-29 18:39:32 +00002306/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2307/// float member at the specified offset. For example, {int,{float}} has a
2308/// float at offset 4. It is conservatively correct for this routine to return
2309/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002310static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002311 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002312 // Base case if we find a float.
2313 if (IROffset == 0 && IRType->isFloatTy())
2314 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002315
Chris Lattnere556a712010-07-29 18:39:32 +00002316 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002317 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002318 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2319 unsigned Elt = SL->getElementContainingOffset(IROffset);
2320 IROffset -= SL->getElementOffset(Elt);
2321 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2322 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002323
Chris Lattnere556a712010-07-29 18:39:32 +00002324 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002325 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2326 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002327 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2328 IROffset -= IROffset/EltSize*EltSize;
2329 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2330 }
2331
2332 return false;
2333}
2334
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002335
2336/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2337/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002338llvm::Type *X86_64ABIInfo::
2339GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002340 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002341 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002342 // pass as float if the last 4 bytes is just padding. This happens for
2343 // structs that contain 3 floats.
2344 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2345 SourceOffset*8+64, getContext()))
2346 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002347
Chris Lattnere556a712010-07-29 18:39:32 +00002348 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2349 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2350 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002351 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2352 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002353 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002354
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002355 return llvm::Type::getDoubleTy(getVMContext());
2356}
2357
2358
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002359/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2360/// an 8-byte GPR. This means that we either have a scalar or we are talking
2361/// about the high or low part of an up-to-16-byte struct. This routine picks
2362/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002363/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2364/// etc).
2365///
2366/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2367/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2368/// the 8-byte value references. PrefType may be null.
2369///
Alp Toker9907f082014-07-09 14:06:35 +00002370/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002371/// an offset into this that we're processing (which is always either 0 or 8).
2372///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002373llvm::Type *X86_64ABIInfo::
2374GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002375 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002376 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2377 // returning an 8-byte unit starting with it. See if we can safely use it.
2378 if (IROffset == 0) {
2379 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002380 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2381 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002382 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002383
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002384 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2385 // goodness in the source type is just tail padding. This is allowed to
2386 // kick in for struct {double,int} on the int, but not on
2387 // struct{double,int,int} because we wouldn't return the second int. We
2388 // have to do this analysis on the source type because we can't depend on
2389 // unions being lowered a specific way etc.
2390 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002391 IRType->isIntegerTy(32) ||
2392 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2393 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2394 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002395
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002396 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2397 SourceOffset*8+64, getContext()))
2398 return IRType;
2399 }
2400 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002401
Chris Lattner2192fe52011-07-18 04:24:23 +00002402 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002403 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002404 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002405 if (IROffset < SL->getSizeInBytes()) {
2406 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2407 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002408
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002409 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2410 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002411 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002412 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002413
Chris Lattner2192fe52011-07-18 04:24:23 +00002414 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002415 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002416 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002417 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002418 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2419 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002420 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002421
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002422 // Okay, we don't have any better idea of what to pass, so we pass this in an
2423 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002424 unsigned TySizeInBytes =
2425 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002426
Chris Lattner3f763422010-07-29 17:34:39 +00002427 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002428
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002429 // It is always safe to classify this as an integer type up to i64 that
2430 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002431 return llvm::IntegerType::get(getVMContext(),
2432 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002433}
2434
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002435
2436/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2437/// be used as elements of a two register pair to pass or return, return a
2438/// first class aggregate to represent them. For example, if the low part of
2439/// a by-value argument should be passed as i32* and the high part as float,
2440/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002441static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002442GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002443 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002444 // In order to correctly satisfy the ABI, we need to the high part to start
2445 // at offset 8. If the high and low parts we inferred are both 4-byte types
2446 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2447 // the second element at offset 8. Check for this:
2448 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2449 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002450 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002451 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002452
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002453 // To handle this, we have to increase the size of the low part so that the
2454 // second element will start at an 8 byte offset. We can't increase the size
2455 // of the second element because it might make us access off the end of the
2456 // struct.
2457 if (HiStart != 8) {
2458 // There are only two sorts of types the ABI generation code can produce for
2459 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2460 // Promote these to a larger type.
2461 if (Lo->isFloatTy())
2462 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2463 else {
2464 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2465 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2466 }
2467 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002468
Reid Kleckneree7cf842014-12-01 22:02:27 +00002469 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002470
2471
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002472 // Verify that the second element is at an 8-byte offset.
2473 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2474 "Invalid x86-64 argument pair!");
2475 return Result;
2476}
2477
Chris Lattner31faff52010-07-28 23:06:14 +00002478ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002479classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002480 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2481 // classification algorithm.
2482 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002483 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002484
2485 // Check some invariants.
2486 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002487 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2488
Craig Topper8a13c412014-05-21 05:09:00 +00002489 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002490 switch (Lo) {
2491 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002492 if (Hi == NoClass)
2493 return ABIArgInfo::getIgnore();
2494 // If the low part is just padding, it takes no register, leave ResType
2495 // null.
2496 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2497 "Unknown missing lo part");
2498 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002499
2500 case SSEUp:
2501 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002502 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002503
2504 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2505 // hidden argument.
2506 case Memory:
2507 return getIndirectReturnResult(RetTy);
2508
2509 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2510 // available register of the sequence %rax, %rdx is used.
2511 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002512 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002513
Chris Lattner1f3a0632010-07-29 21:42:50 +00002514 // If we have a sign or zero extended integer, make sure to return Extend
2515 // so that the parameter gets the right LLVM IR attributes.
2516 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2517 // Treat an enum type as its underlying type.
2518 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2519 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002520
Chris Lattner1f3a0632010-07-29 21:42:50 +00002521 if (RetTy->isIntegralOrEnumerationType() &&
2522 RetTy->isPromotableIntegerType())
2523 return ABIArgInfo::getExtend();
2524 }
Chris Lattner31faff52010-07-28 23:06:14 +00002525 break;
2526
2527 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2528 // available SSE register of the sequence %xmm0, %xmm1 is used.
2529 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002530 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002531 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002532
2533 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2534 // returned on the X87 stack in %st0 as 80-bit x87 number.
2535 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002536 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002537 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002538
2539 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2540 // part of the value is returned in %st0 and the imaginary part in
2541 // %st1.
2542 case ComplexX87:
2543 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002544 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002545 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002546 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002547 break;
2548 }
2549
Craig Topper8a13c412014-05-21 05:09:00 +00002550 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002551 switch (Hi) {
2552 // Memory was handled previously and X87 should
2553 // never occur as a hi class.
2554 case Memory:
2555 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002556 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002557
2558 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002559 case NoClass:
2560 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002561
Chris Lattner52b3c132010-09-01 00:20:33 +00002562 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002563 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002564 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2565 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002566 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002567 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002568 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002569 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2570 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002571 break;
2572
2573 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002574 // is passed in the next available eightbyte chunk if the last used
2575 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002576 //
Chris Lattner57540c52011-04-15 05:22:18 +00002577 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002578 case SSEUp:
2579 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002580 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002581 break;
2582
2583 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2584 // returned together with the previous X87 value in %st0.
2585 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002586 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002587 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002588 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002589 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002590 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002591 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002592 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2593 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002594 }
Chris Lattner31faff52010-07-28 23:06:14 +00002595 break;
2596 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002597
Chris Lattner52b3c132010-09-01 00:20:33 +00002598 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002599 // known to pass in the high eightbyte of the result. We do this by forming a
2600 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002601 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002602 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002603
Chris Lattner1f3a0632010-07-29 21:42:50 +00002604 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002605}
2606
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002607ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002608 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2609 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002610 const
2611{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002612 Ty = useFirstFieldIfTransparentUnion(Ty);
2613
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002614 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002615 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002616
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002617 // Check some invariants.
2618 // FIXME: Enforce these by construction.
2619 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2621
2622 neededInt = 0;
2623 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002624 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625 switch (Lo) {
2626 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002627 if (Hi == NoClass)
2628 return ABIArgInfo::getIgnore();
2629 // If the low part is just padding, it takes no register, leave ResType
2630 // null.
2631 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2632 "Unknown missing lo part");
2633 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002634
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002635 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2636 // on the stack.
2637 case Memory:
2638
2639 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2640 // COMPLEX_X87, it is passed in memory.
2641 case X87:
2642 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002643 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002644 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002645 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002646
2647 case SSEUp:
2648 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002649 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002650
2651 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2652 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2653 // and %r9 is used.
2654 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002655 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002656
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002657 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002658 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002659
2660 // If we have a sign or zero extended integer, make sure to return Extend
2661 // so that the parameter gets the right LLVM IR attributes.
2662 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2663 // Treat an enum type as its underlying type.
2664 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2665 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002666
Chris Lattner1f3a0632010-07-29 21:42:50 +00002667 if (Ty->isIntegralOrEnumerationType() &&
2668 Ty->isPromotableIntegerType())
2669 return ABIArgInfo::getExtend();
2670 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002671
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002672 break;
2673
2674 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2675 // available SSE register is used, the registers are taken in the
2676 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002677 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002678 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002679 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002680 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002681 break;
2682 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002683 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002684
Craig Topper8a13c412014-05-21 05:09:00 +00002685 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002686 switch (Hi) {
2687 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002688 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002689 // which is passed in memory.
2690 case Memory:
2691 case X87:
2692 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002693 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002694
2695 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002696
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002697 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002699 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002700 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002701
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002702 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2703 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002704 break;
2705
2706 // X87Up generally doesn't occur here (long double is passed in
2707 // memory), except in situations involving unions.
2708 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002709 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002710 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002711
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002712 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2713 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002714
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002715 ++neededSSE;
2716 break;
2717
2718 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2719 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002720 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002721 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002722 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002723 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002724 break;
2725 }
2726
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002727 // If a high part was specified, merge it together with the low part. It is
2728 // known to pass in the high eightbyte of the result. We do this by forming a
2729 // first class struct aggregate with the high and low part: {low, high}
2730 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002731 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002732
Chris Lattner1f3a0632010-07-29 21:42:50 +00002733 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002734}
2735
Chris Lattner22326a12010-07-29 02:31:05 +00002736void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002737
Reid Kleckner40ca9132014-05-13 22:05:45 +00002738 if (!getCXXABI().classifyReturnType(FI))
2739 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002740
2741 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002742 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002743
2744 // If the return value is indirect, then the hidden argument is consuming one
2745 // integer register.
2746 if (FI.getReturnInfo().isIndirect())
2747 --freeIntRegs;
2748
Peter Collingbournef7706832014-12-12 23:41:25 +00002749 // The chain argument effectively gives us another free register.
2750 if (FI.isChainCall())
2751 ++freeIntRegs;
2752
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002753 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002754 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2755 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002756 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002757 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002758 it != ie; ++it, ++ArgNo) {
2759 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002760
Bill Wendling9987c0e2010-10-18 23:51:38 +00002761 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002762 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002763 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002764
2765 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2766 // eightbyte of an argument, the whole argument is passed on the
2767 // stack. If registers have already been assigned for some
2768 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002769 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002770 freeIntRegs -= neededInt;
2771 freeSSERegs -= neededSSE;
2772 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002773 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002774 }
2775 }
2776}
2777
2778static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2779 QualType Ty,
2780 CodeGenFunction &CGF) {
2781 llvm::Value *overflow_arg_area_p =
2782 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2783 llvm::Value *overflow_arg_area =
2784 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2785
2786 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2787 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002788 // It isn't stated explicitly in the standard, but in practice we use
2789 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002790 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2791 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002792 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002793 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002794 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002795 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2796 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002797 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002798 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002799 overflow_arg_area =
2800 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2801 overflow_arg_area->getType(),
2802 "overflow_arg_area.align");
2803 }
2804
2805 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002806 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002807 llvm::Value *Res =
2808 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002809 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002810
2811 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2812 // l->overflow_arg_area + sizeof(type).
2813 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2814 // an 8 byte boundary.
2815
2816 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002817 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002818 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002819 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2820 "overflow_arg_area.next");
2821 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2822
2823 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2824 return Res;
2825}
2826
2827llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2828 CodeGenFunction &CGF) const {
2829 // Assume that va_list type is correct; should be pointer to LLVM type:
2830 // struct {
2831 // i32 gp_offset;
2832 // i32 fp_offset;
2833 // i8* overflow_arg_area;
2834 // i8* reg_save_area;
2835 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002836 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002837
Chris Lattner9723d6c2010-03-11 18:19:55 +00002838 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002839 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2840 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841
2842 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2843 // in the registers. If not go to step 7.
2844 if (!neededInt && !neededSSE)
2845 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2846
2847 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2848 // general purpose registers needed to pass type and num_fp to hold
2849 // the number of floating point registers needed.
2850
2851 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2852 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2853 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2854 //
2855 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2856 // register save space).
2857
Craig Topper8a13c412014-05-21 05:09:00 +00002858 llvm::Value *InRegs = nullptr;
2859 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2860 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002861 if (neededInt) {
2862 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2863 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002864 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2865 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002866 }
2867
2868 if (neededSSE) {
2869 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2870 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2871 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002872 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2873 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002874 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2875 }
2876
2877 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2878 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2879 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2880 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2881
2882 // Emit code to load the value if it was passed in registers.
2883
2884 CGF.EmitBlock(InRegBlock);
2885
2886 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2887 // an offset of l->gp_offset and/or l->fp_offset. This may require
2888 // copying to a temporary location in case the parameter is passed
2889 // in different register classes or requires an alignment greater
2890 // than 8 for general purpose registers and 16 for XMM registers.
2891 //
2892 // FIXME: This really results in shameful code when we end up needing to
2893 // collect arguments from different places; often what should result in a
2894 // simple assembling of a structure from scattered addresses has many more
2895 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002896 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002897 llvm::Value *RegAddr =
2898 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2899 "reg_save_area");
2900 if (neededInt && neededSSE) {
2901 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002902 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002903 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002904 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2905 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002906 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002907 llvm::Type *TyLo = ST->getElementType(0);
2908 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002909 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002910 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002911 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2912 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002913 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2914 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002915 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2916 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002917 llvm::Value *V =
2918 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2919 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2920 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2921 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2922
Owen Anderson170229f2009-07-14 23:10:40 +00002923 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002924 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002925 } else if (neededInt) {
2926 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2927 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002928 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002929
2930 // Copy to a temporary if necessary to ensure the appropriate alignment.
2931 std::pair<CharUnits, CharUnits> SizeAlign =
2932 CGF.getContext().getTypeInfoInChars(Ty);
2933 uint64_t TySize = SizeAlign.first.getQuantity();
2934 unsigned TyAlign = SizeAlign.second.getQuantity();
2935 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002936 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2937 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2938 RegAddr = Tmp;
2939 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002940 } else if (neededSSE == 1) {
2941 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2942 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2943 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002944 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002945 assert(neededSSE == 2 && "Invalid number of needed registers!");
2946 // SSE registers are spaced 16 bytes apart in the register save
2947 // area, we need to collect the two eightbytes together.
2948 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002949 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002950 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002951 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002952 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002953 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002954 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2955 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002956 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2957 DblPtrTy));
2958 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2959 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2960 DblPtrTy));
2961 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2962 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2963 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002964 }
2965
2966 // AMD64-ABI 3.5.7p5: Step 5. Set:
2967 // l->gp_offset = l->gp_offset + num_gp * 8
2968 // l->fp_offset = l->fp_offset + num_fp * 16.
2969 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002970 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002971 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2972 gp_offset_p);
2973 }
2974 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002975 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002976 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2977 fp_offset_p);
2978 }
2979 CGF.EmitBranch(ContBlock);
2980
2981 // Emit code to load the value if it was passed in memory.
2982
2983 CGF.EmitBlock(InMemBlock);
2984 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2985
2986 // Return the appropriate result.
2987
2988 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002989 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002990 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002991 ResAddr->addIncoming(RegAddr, InRegBlock);
2992 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002993 return ResAddr;
2994}
2995
Reid Kleckner80944df2014-10-31 22:00:51 +00002996ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
2997 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002998
2999 if (Ty->isVoidType())
3000 return ABIArgInfo::getIgnore();
3001
3002 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3003 Ty = EnumTy->getDecl()->getIntegerType();
3004
Reid Kleckner80944df2014-10-31 22:00:51 +00003005 TypeInfo Info = getContext().getTypeInfo(Ty);
3006 uint64_t Width = Info.Width;
3007 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003008
Reid Kleckner9005f412014-05-02 00:51:20 +00003009 const RecordType *RT = Ty->getAs<RecordType>();
3010 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003011 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003012 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003013 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3014 }
3015
3016 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003017 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3018
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003019 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003020 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003021 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003022 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003023 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003024
Reid Kleckner80944df2014-10-31 22:00:51 +00003025 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3026 // other targets.
3027 const Type *Base = nullptr;
3028 uint64_t NumElts = 0;
3029 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3030 if (FreeSSERegs >= NumElts) {
3031 FreeSSERegs -= NumElts;
3032 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3033 return ABIArgInfo::getDirect();
3034 return ABIArgInfo::getExpand();
3035 }
3036 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3037 }
3038
3039
Reid Klecknerec87fec2014-05-02 01:17:12 +00003040 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003041 // If the member pointer is represented by an LLVM int or ptr, pass it
3042 // directly.
3043 llvm::Type *LLTy = CGT.ConvertType(Ty);
3044 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3045 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003046 }
3047
Michael Kuperstein4f818702015-02-24 09:35:58 +00003048 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003049 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3050 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003051 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00003052 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003053
Reid Kleckner9005f412014-05-02 00:51:20 +00003054 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003055 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003056 }
3057
Julien Lerouge10dcff82014-08-27 00:36:55 +00003058 // Bool type is always extended to the ABI, other builtin types are not
3059 // extended.
3060 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3061 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003062 return ABIArgInfo::getExtend();
3063
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003064 return ABIArgInfo::getDirect();
3065}
3066
3067void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003068 bool IsVectorCall =
3069 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003070
Reid Kleckner80944df2014-10-31 22:00:51 +00003071 // We can use up to 4 SSE return registers with vectorcall.
3072 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3073 if (!getCXXABI().classifyReturnType(FI))
3074 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3075
3076 // We can use up to 6 SSE register parameters with vectorcall.
3077 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003078 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003079 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003080}
3081
Chris Lattner04dc9572010-08-31 16:44:54 +00003082llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3083 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003084 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003085
Chris Lattner04dc9572010-08-31 16:44:54 +00003086 CGBuilderTy &Builder = CGF.Builder;
3087 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3088 "ap");
3089 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3090 llvm::Type *PTy =
3091 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3092 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3093
3094 uint64_t Offset =
3095 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3096 llvm::Value *NextAddr =
3097 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3098 "ap.next");
3099 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3100
3101 return AddrTyped;
3102}
Chris Lattner0cf24192010-06-28 20:05:43 +00003103
John McCallea8d8bb2010-03-11 00:10:12 +00003104// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003105namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003106/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3107class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003108public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003109 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3110
3111 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3112 CodeGenFunction &CGF) const override;
3113};
3114
3115class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3116public:
3117 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003118
Craig Topper4f12f102014-03-12 06:41:41 +00003119 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003120 // This is recovered from gcc output.
3121 return 1; // r1 is the dedicated stack pointer
3122 }
3123
3124 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003125 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003126
3127 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3128 return 16; // Natural alignment for Altivec vectors.
3129 }
Joerg Sonnenberger096feeb2015-02-23 20:23:47 +00003130
3131 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
3132 return true;
3133 }
John McCallea8d8bb2010-03-11 00:10:12 +00003134};
3135
3136}
3137
Roman Divacky8a12d842014-11-03 18:32:54 +00003138llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3139 QualType Ty,
3140 CodeGenFunction &CGF) const {
3141 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3142 // TODO: Implement this. For now ignore.
3143 (void)CTy;
3144 return nullptr;
3145 }
3146
3147 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3148 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3149 llvm::Type *CharPtr = CGF.Int8PtrTy;
3150 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3151
3152 CGBuilderTy &Builder = CGF.Builder;
3153 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3154 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3155 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3156 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3157 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3158 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3159 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3160 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3161 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3162 // Align GPR when TY is i64.
3163 if (isI64) {
3164 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3165 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3166 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3167 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3168 }
3169 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3170 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3171 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3172 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3173 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3174
3175 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3176 Builder.getInt8(8), "cond");
3177
3178 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3179 Builder.getInt8(isInt ? 4 : 8));
3180
3181 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3182
3183 if (Ty->isFloatingType())
3184 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3185
3186 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3187 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3188 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3189
3190 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3191
3192 CGF.EmitBlock(UsingRegs);
3193
3194 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3195 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3196 // Increase the GPR/FPR indexes.
3197 if (isInt) {
3198 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3199 Builder.CreateStore(GPR, GPRPtr);
3200 } else {
3201 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3202 Builder.CreateStore(FPR, FPRPtr);
3203 }
3204 CGF.EmitBranch(Cont);
3205
3206 CGF.EmitBlock(UsingOverflow);
3207
3208 // Increase the overflow area.
3209 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3210 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3211 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3212 CGF.EmitBranch(Cont);
3213
3214 CGF.EmitBlock(Cont);
3215
3216 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3217 Result->addIncoming(Result1, UsingRegs);
3218 Result->addIncoming(Result2, UsingOverflow);
3219
3220 if (Ty->isAggregateType()) {
3221 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3222 return Builder.CreateLoad(AGGPtr, false, "aggr");
3223 }
3224
3225 return Result;
3226}
3227
John McCallea8d8bb2010-03-11 00:10:12 +00003228bool
3229PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3230 llvm::Value *Address) const {
3231 // This is calculated from the LLVM and GCC tables and verified
3232 // against gcc output. AFAIK all ABIs use the same encoding.
3233
3234 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003235
Chris Lattnerece04092012-02-07 00:39:47 +00003236 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003237 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3238 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3239 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3240
3241 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003242 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003243
3244 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003245 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003246
3247 // 64-76 are various 4-byte special-purpose registers:
3248 // 64: mq
3249 // 65: lr
3250 // 66: ctr
3251 // 67: ap
3252 // 68-75 cr0-7
3253 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003254 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003255
3256 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003257 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003258
3259 // 109: vrsave
3260 // 110: vscr
3261 // 111: spe_acc
3262 // 112: spefscr
3263 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003264 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003265
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003266 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003267}
3268
Roman Divackyd966e722012-05-09 18:22:46 +00003269// PowerPC-64
3270
3271namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003272/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3273class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003274public:
3275 enum ABIKind {
3276 ELFv1 = 0,
3277 ELFv2
3278 };
3279
3280private:
3281 static const unsigned GPRBits = 64;
3282 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003283
3284public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003285 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3286 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003287
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003288 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003289 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003290
3291 ABIArgInfo classifyReturnType(QualType RetTy) const;
3292 ABIArgInfo classifyArgumentType(QualType Ty) const;
3293
Reid Klecknere9f6a712014-10-31 17:10:41 +00003294 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3295 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3296 uint64_t Members) const override;
3297
Bill Schmidt84d37792012-10-12 19:26:17 +00003298 // TODO: We can add more logic to computeInfo to improve performance.
3299 // Example: For aggregate arguments that fit in a register, we could
3300 // use getDirectInReg (as is done below for structs containing a single
3301 // floating-point value) to avoid pushing them to memory on function
3302 // entry. This would require changing the logic in PPCISelLowering
3303 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003304 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003305 if (!getCXXABI().classifyReturnType(FI))
3306 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003307 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003308 // We rely on the default argument classification for the most part.
3309 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003310 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003311 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003312 if (T) {
3313 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003314 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3315 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003316 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003317 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003318 continue;
3319 }
3320 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003321 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003322 }
3323 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003324
Craig Topper4f12f102014-03-12 06:41:41 +00003325 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3326 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003327};
3328
3329class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3330public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003331 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3332 PPC64_SVR4_ABIInfo::ABIKind Kind)
3333 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003334
Craig Topper4f12f102014-03-12 06:41:41 +00003335 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003336 // This is recovered from gcc output.
3337 return 1; // r1 is the dedicated stack pointer
3338 }
3339
3340 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003341 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003342
3343 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3344 return 16; // Natural alignment for Altivec and VSX vectors.
3345 }
Joerg Sonnenberger096feeb2015-02-23 20:23:47 +00003346
3347 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
3348 return true;
3349 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003350};
3351
Roman Divackyd966e722012-05-09 18:22:46 +00003352class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3353public:
3354 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3355
Craig Topper4f12f102014-03-12 06:41:41 +00003356 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003357 // This is recovered from gcc output.
3358 return 1; // r1 is the dedicated stack pointer
3359 }
3360
3361 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003362 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003363
3364 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3365 return 16; // Natural alignment for Altivec vectors.
3366 }
Joerg Sonnenberger096feeb2015-02-23 20:23:47 +00003367
3368 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
3369 return true;
3370 }
Roman Divackyd966e722012-05-09 18:22:46 +00003371};
3372
3373}
3374
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003375// Return true if the ABI requires Ty to be passed sign- or zero-
3376// extended to 64 bits.
3377bool
3378PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3379 // Treat an enum type as its underlying type.
3380 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3381 Ty = EnumTy->getDecl()->getIntegerType();
3382
3383 // Promotable integer types are required to be promoted by the ABI.
3384 if (Ty->isPromotableIntegerType())
3385 return true;
3386
3387 // In addition to the usual promotable integer types, we also need to
3388 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3389 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3390 switch (BT->getKind()) {
3391 case BuiltinType::Int:
3392 case BuiltinType::UInt:
3393 return true;
3394 default:
3395 break;
3396 }
3397
3398 return false;
3399}
3400
Ulrich Weigand581badc2014-07-10 17:20:07 +00003401/// isAlignedParamType - Determine whether a type requires 16-byte
3402/// alignment in the parameter area.
3403bool
3404PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3405 // Complex types are passed just like their elements.
3406 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3407 Ty = CTy->getElementType();
3408
3409 // Only vector types of size 16 bytes need alignment (larger types are
3410 // passed via reference, smaller types are not aligned).
3411 if (Ty->isVectorType())
3412 return getContext().getTypeSize(Ty) == 128;
3413
3414 // For single-element float/vector structs, we consider the whole type
3415 // to have the same alignment requirements as its single element.
3416 const Type *AlignAsType = nullptr;
3417 const Type *EltType = isSingleElementStruct(Ty, getContext());
3418 if (EltType) {
3419 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3420 if ((EltType->isVectorType() &&
3421 getContext().getTypeSize(EltType) == 128) ||
3422 (BT && BT->isFloatingPoint()))
3423 AlignAsType = EltType;
3424 }
3425
Ulrich Weigandb7122372014-07-21 00:48:09 +00003426 // Likewise for ELFv2 homogeneous aggregates.
3427 const Type *Base = nullptr;
3428 uint64_t Members = 0;
3429 if (!AlignAsType && Kind == ELFv2 &&
3430 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3431 AlignAsType = Base;
3432
Ulrich Weigand581badc2014-07-10 17:20:07 +00003433 // With special case aggregates, only vector base types need alignment.
3434 if (AlignAsType)
3435 return AlignAsType->isVectorType();
3436
3437 // Otherwise, we only need alignment for any aggregate type that
3438 // has an alignment requirement of >= 16 bytes.
3439 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3440 return true;
3441
3442 return false;
3443}
3444
Ulrich Weigandb7122372014-07-21 00:48:09 +00003445/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3446/// aggregate. Base is set to the base element type, and Members is set
3447/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003448bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3449 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003450 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3451 uint64_t NElements = AT->getSize().getZExtValue();
3452 if (NElements == 0)
3453 return false;
3454 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3455 return false;
3456 Members *= NElements;
3457 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3458 const RecordDecl *RD = RT->getDecl();
3459 if (RD->hasFlexibleArrayMember())
3460 return false;
3461
3462 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003463
3464 // If this is a C++ record, check the bases first.
3465 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3466 for (const auto &I : CXXRD->bases()) {
3467 // Ignore empty records.
3468 if (isEmptyRecord(getContext(), I.getType(), true))
3469 continue;
3470
3471 uint64_t FldMembers;
3472 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3473 return false;
3474
3475 Members += FldMembers;
3476 }
3477 }
3478
Ulrich Weigandb7122372014-07-21 00:48:09 +00003479 for (const auto *FD : RD->fields()) {
3480 // Ignore (non-zero arrays of) empty records.
3481 QualType FT = FD->getType();
3482 while (const ConstantArrayType *AT =
3483 getContext().getAsConstantArrayType(FT)) {
3484 if (AT->getSize().getZExtValue() == 0)
3485 return false;
3486 FT = AT->getElementType();
3487 }
3488 if (isEmptyRecord(getContext(), FT, true))
3489 continue;
3490
3491 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3492 if (getContext().getLangOpts().CPlusPlus &&
3493 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3494 continue;
3495
3496 uint64_t FldMembers;
3497 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3498 return false;
3499
3500 Members = (RD->isUnion() ?
3501 std::max(Members, FldMembers) : Members + FldMembers);
3502 }
3503
3504 if (!Base)
3505 return false;
3506
3507 // Ensure there is no padding.
3508 if (getContext().getTypeSize(Base) * Members !=
3509 getContext().getTypeSize(Ty))
3510 return false;
3511 } else {
3512 Members = 1;
3513 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3514 Members = 2;
3515 Ty = CT->getElementType();
3516 }
3517
Reid Klecknere9f6a712014-10-31 17:10:41 +00003518 // Most ABIs only support float, double, and some vector type widths.
3519 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003520 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003521
3522 // The base type must be the same for all members. Types that
3523 // agree in both total size and mode (float vs. vector) are
3524 // treated as being equivalent here.
3525 const Type *TyPtr = Ty.getTypePtr();
3526 if (!Base)
3527 Base = TyPtr;
3528
3529 if (Base->isVectorType() != TyPtr->isVectorType() ||
3530 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3531 return false;
3532 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003533 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3534}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003535
Reid Klecknere9f6a712014-10-31 17:10:41 +00003536bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3537 // Homogeneous aggregates for ELFv2 must have base types of float,
3538 // double, long double, or 128-bit vectors.
3539 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3540 if (BT->getKind() == BuiltinType::Float ||
3541 BT->getKind() == BuiltinType::Double ||
3542 BT->getKind() == BuiltinType::LongDouble)
3543 return true;
3544 }
3545 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3546 if (getContext().getTypeSize(VT) == 128)
3547 return true;
3548 }
3549 return false;
3550}
3551
3552bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3553 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003554 // Vector types require one register, floating point types require one
3555 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003556 uint32_t NumRegs =
3557 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003558
3559 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003560 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003561}
3562
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003563ABIArgInfo
3564PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003565 Ty = useFirstFieldIfTransparentUnion(Ty);
3566
Bill Schmidt90b22c92012-11-27 02:46:43 +00003567 if (Ty->isAnyComplexType())
3568 return ABIArgInfo::getDirect();
3569
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003570 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3571 // or via reference (larger than 16 bytes).
3572 if (Ty->isVectorType()) {
3573 uint64_t Size = getContext().getTypeSize(Ty);
3574 if (Size > 128)
3575 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3576 else if (Size < 128) {
3577 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3578 return ABIArgInfo::getDirect(CoerceTy);
3579 }
3580 }
3581
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003582 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003583 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003584 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003585
Ulrich Weigand581badc2014-07-10 17:20:07 +00003586 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3587 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003588
3589 // ELFv2 homogeneous aggregates are passed as array types.
3590 const Type *Base = nullptr;
3591 uint64_t Members = 0;
3592 if (Kind == ELFv2 &&
3593 isHomogeneousAggregate(Ty, Base, Members)) {
3594 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3595 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3596 return ABIArgInfo::getDirect(CoerceTy);
3597 }
3598
Ulrich Weigand601957f2014-07-21 00:56:36 +00003599 // If an aggregate may end up fully in registers, we do not
3600 // use the ByVal method, but pass the aggregate as array.
3601 // This is usually beneficial since we avoid forcing the
3602 // back-end to store the argument to memory.
3603 uint64_t Bits = getContext().getTypeSize(Ty);
3604 if (Bits > 0 && Bits <= 8 * GPRBits) {
3605 llvm::Type *CoerceTy;
3606
3607 // Types up to 8 bytes are passed as integer type (which will be
3608 // properly aligned in the argument save area doubleword).
3609 if (Bits <= GPRBits)
3610 CoerceTy = llvm::IntegerType::get(getVMContext(),
3611 llvm::RoundUpToAlignment(Bits, 8));
3612 // Larger types are passed as arrays, with the base type selected
3613 // according to the required alignment in the save area.
3614 else {
3615 uint64_t RegBits = ABIAlign * 8;
3616 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3617 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3618 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3619 }
3620
3621 return ABIArgInfo::getDirect(CoerceTy);
3622 }
3623
Ulrich Weigandb7122372014-07-21 00:48:09 +00003624 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003625 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3626 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003627 }
3628
3629 return (isPromotableTypeForABI(Ty) ?
3630 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3631}
3632
3633ABIArgInfo
3634PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3635 if (RetTy->isVoidType())
3636 return ABIArgInfo::getIgnore();
3637
Bill Schmidta3d121c2012-12-17 04:20:17 +00003638 if (RetTy->isAnyComplexType())
3639 return ABIArgInfo::getDirect();
3640
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003641 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3642 // or via reference (larger than 16 bytes).
3643 if (RetTy->isVectorType()) {
3644 uint64_t Size = getContext().getTypeSize(RetTy);
3645 if (Size > 128)
3646 return ABIArgInfo::getIndirect(0);
3647 else if (Size < 128) {
3648 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3649 return ABIArgInfo::getDirect(CoerceTy);
3650 }
3651 }
3652
Ulrich Weigandb7122372014-07-21 00:48:09 +00003653 if (isAggregateTypeForABI(RetTy)) {
3654 // ELFv2 homogeneous aggregates are returned as array types.
3655 const Type *Base = nullptr;
3656 uint64_t Members = 0;
3657 if (Kind == ELFv2 &&
3658 isHomogeneousAggregate(RetTy, Base, Members)) {
3659 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3660 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3661 return ABIArgInfo::getDirect(CoerceTy);
3662 }
3663
3664 // ELFv2 small aggregates are returned in up to two registers.
3665 uint64_t Bits = getContext().getTypeSize(RetTy);
3666 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3667 if (Bits == 0)
3668 return ABIArgInfo::getIgnore();
3669
3670 llvm::Type *CoerceTy;
3671 if (Bits > GPRBits) {
3672 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003673 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003674 } else
3675 CoerceTy = llvm::IntegerType::get(getVMContext(),
3676 llvm::RoundUpToAlignment(Bits, 8));
3677 return ABIArgInfo::getDirect(CoerceTy);
3678 }
3679
3680 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003681 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003682 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003683
3684 return (isPromotableTypeForABI(RetTy) ?
3685 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3686}
3687
Bill Schmidt25cb3492012-10-03 19:18:57 +00003688// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3689llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3690 QualType Ty,
3691 CodeGenFunction &CGF) const {
3692 llvm::Type *BP = CGF.Int8PtrTy;
3693 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3694
3695 CGBuilderTy &Builder = CGF.Builder;
3696 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3697 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3698
Ulrich Weigand581badc2014-07-10 17:20:07 +00003699 // Handle types that require 16-byte alignment in the parameter save area.
3700 if (isAlignedParamType(Ty)) {
3701 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3702 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3703 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3704 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3705 }
3706
Bill Schmidt924c4782013-01-14 17:45:36 +00003707 // Update the va_list pointer. The pointer should be bumped by the
3708 // size of the object. We can trust getTypeSize() except for a complex
3709 // type whose base type is smaller than a doubleword. For these, the
3710 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003711 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003712 QualType BaseTy;
3713 unsigned CplxBaseSize = 0;
3714
3715 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3716 BaseTy = CTy->getElementType();
3717 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3718 if (CplxBaseSize < 8)
3719 SizeInBytes = 16;
3720 }
3721
Bill Schmidt25cb3492012-10-03 19:18:57 +00003722 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3723 llvm::Value *NextAddr =
3724 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3725 "ap.next");
3726 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3727
Bill Schmidt924c4782013-01-14 17:45:36 +00003728 // If we have a complex type and the base type is smaller than 8 bytes,
3729 // the ABI calls for the real and imaginary parts to be right-adjusted
3730 // in separate doublewords. However, Clang expects us to produce a
3731 // pointer to a structure with the two parts packed tightly. So generate
3732 // loads of the real and imaginary parts relative to the va_list pointer,
3733 // and store them to a temporary structure.
3734 if (CplxBaseSize && CplxBaseSize < 8) {
3735 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3736 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003737 if (CGF.CGM.getDataLayout().isBigEndian()) {
3738 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3739 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3740 } else {
3741 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3742 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003743 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3744 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3745 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3746 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3747 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3748 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3749 "vacplx");
3750 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3751 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3752 Builder.CreateStore(Real, RealPtr, false);
3753 Builder.CreateStore(Imag, ImagPtr, false);
3754 return Ptr;
3755 }
3756
Bill Schmidt25cb3492012-10-03 19:18:57 +00003757 // If the argument is smaller than 8 bytes, it is right-adjusted in
3758 // its doubleword slot. Adjust the pointer to pick it up from the
3759 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003760 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003761 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3762 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3763 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3764 }
3765
3766 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3767 return Builder.CreateBitCast(Addr, PTy);
3768}
3769
3770static bool
3771PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3772 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003773 // This is calculated from the LLVM and GCC tables and verified
3774 // against gcc output. AFAIK all ABIs use the same encoding.
3775
3776 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3777
3778 llvm::IntegerType *i8 = CGF.Int8Ty;
3779 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3780 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3781 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3782
3783 // 0-31: r0-31, the 8-byte general-purpose registers
3784 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3785
3786 // 32-63: fp0-31, the 8-byte floating-point registers
3787 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3788
3789 // 64-76 are various 4-byte special-purpose registers:
3790 // 64: mq
3791 // 65: lr
3792 // 66: ctr
3793 // 67: ap
3794 // 68-75 cr0-7
3795 // 76: xer
3796 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3797
3798 // 77-108: v0-31, the 16-byte vector registers
3799 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3800
3801 // 109: vrsave
3802 // 110: vscr
3803 // 111: spe_acc
3804 // 112: spefscr
3805 // 113: sfp
3806 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3807
3808 return false;
3809}
John McCallea8d8bb2010-03-11 00:10:12 +00003810
Bill Schmidt25cb3492012-10-03 19:18:57 +00003811bool
3812PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3813 CodeGen::CodeGenFunction &CGF,
3814 llvm::Value *Address) const {
3815
3816 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3817}
3818
3819bool
3820PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3821 llvm::Value *Address) const {
3822
3823 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3824}
3825
Chris Lattner0cf24192010-06-28 20:05:43 +00003826//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003827// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003828//===----------------------------------------------------------------------===//
3829
3830namespace {
3831
Tim Northover573cbee2014-05-24 12:52:07 +00003832class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003833public:
3834 enum ABIKind {
3835 AAPCS = 0,
3836 DarwinPCS
3837 };
3838
3839private:
3840 ABIKind Kind;
3841
3842public:
Tim Northover573cbee2014-05-24 12:52:07 +00003843 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003844
3845private:
3846 ABIKind getABIKind() const { return Kind; }
3847 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3848
3849 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003850 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003851 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3852 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3853 uint64_t Members) const override;
3854
Tim Northovera2ee4332014-03-29 15:09:45 +00003855 bool isIllegalVectorType(QualType Ty) const;
3856
David Blaikie1cbb9712014-11-14 19:09:44 +00003857 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003858 if (!getCXXABI().classifyReturnType(FI))
3859 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003860
Tim Northoverb047bfa2014-11-27 21:02:49 +00003861 for (auto &it : FI.arguments())
3862 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003863 }
3864
3865 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3866 CodeGenFunction &CGF) const;
3867
3868 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3869 CodeGenFunction &CGF) const;
3870
3871 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003872 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003873 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3874 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3875 }
3876};
3877
Tim Northover573cbee2014-05-24 12:52:07 +00003878class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003879public:
Tim Northover573cbee2014-05-24 12:52:07 +00003880 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3881 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003882
3883 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3884 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3885 }
3886
3887 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3888
3889 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3890};
3891}
3892
Tim Northoverb047bfa2014-11-27 21:02:49 +00003893ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003894 Ty = useFirstFieldIfTransparentUnion(Ty);
3895
Tim Northovera2ee4332014-03-29 15:09:45 +00003896 // Handle illegal vector types here.
3897 if (isIllegalVectorType(Ty)) {
3898 uint64_t Size = getContext().getTypeSize(Ty);
3899 if (Size <= 32) {
3900 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003901 return ABIArgInfo::getDirect(ResType);
3902 }
3903 if (Size == 64) {
3904 llvm::Type *ResType =
3905 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003906 return ABIArgInfo::getDirect(ResType);
3907 }
3908 if (Size == 128) {
3909 llvm::Type *ResType =
3910 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003911 return ABIArgInfo::getDirect(ResType);
3912 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003913 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3914 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003915
3916 if (!isAggregateTypeForABI(Ty)) {
3917 // Treat an enum type as its underlying type.
3918 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3919 Ty = EnumTy->getDecl()->getIntegerType();
3920
Tim Northovera2ee4332014-03-29 15:09:45 +00003921 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3922 ? ABIArgInfo::getExtend()
3923 : ABIArgInfo::getDirect());
3924 }
3925
3926 // Structures with either a non-trivial destructor or a non-trivial
3927 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003928 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003929 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00003930 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003931 }
3932
3933 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3934 // elsewhere for GNU compatibility.
3935 if (isEmptyRecord(getContext(), Ty, true)) {
3936 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3937 return ABIArgInfo::getIgnore();
3938
Tim Northovera2ee4332014-03-29 15:09:45 +00003939 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3940 }
3941
3942 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003943 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003944 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003945 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00003946 return ABIArgInfo::getDirect(
3947 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00003948 }
3949
3950 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3951 uint64_t Size = getContext().getTypeSize(Ty);
3952 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003953 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00003954 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00003955
Tim Northovera2ee4332014-03-29 15:09:45 +00003956 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3957 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003958 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003959 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3960 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3961 }
3962 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3963 }
3964
Tim Northovera2ee4332014-03-29 15:09:45 +00003965 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3966}
3967
Tim Northover573cbee2014-05-24 12:52:07 +00003968ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003969 if (RetTy->isVoidType())
3970 return ABIArgInfo::getIgnore();
3971
3972 // Large vector types should be returned via memory.
3973 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3974 return ABIArgInfo::getIndirect(0);
3975
3976 if (!isAggregateTypeForABI(RetTy)) {
3977 // Treat an enum type as its underlying type.
3978 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3979 RetTy = EnumTy->getDecl()->getIntegerType();
3980
Tim Northover4dab6982014-04-18 13:46:08 +00003981 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3982 ? ABIArgInfo::getExtend()
3983 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003984 }
3985
Tim Northovera2ee4332014-03-29 15:09:45 +00003986 if (isEmptyRecord(getContext(), RetTy, true))
3987 return ABIArgInfo::getIgnore();
3988
Craig Topper8a13c412014-05-21 05:09:00 +00003989 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003990 uint64_t Members = 0;
3991 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00003992 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3993 return ABIArgInfo::getDirect();
3994
3995 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3996 uint64_t Size = getContext().getTypeSize(RetTy);
3997 if (Size <= 128) {
3998 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3999 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4000 }
4001
4002 return ABIArgInfo::getIndirect(0);
4003}
4004
Tim Northover573cbee2014-05-24 12:52:07 +00004005/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4006bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004007 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4008 // Check whether VT is legal.
4009 unsigned NumElements = VT->getNumElements();
4010 uint64_t Size = getContext().getTypeSize(VT);
4011 // NumElements should be power of 2 between 1 and 16.
4012 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4013 return true;
4014 return Size != 64 && (Size != 128 || NumElements == 1);
4015 }
4016 return false;
4017}
4018
Reid Klecknere9f6a712014-10-31 17:10:41 +00004019bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4020 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4021 // point type or a short-vector type. This is the same as the 32-bit ABI,
4022 // but with the difference that any floating-point type is allowed,
4023 // including __fp16.
4024 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4025 if (BT->isFloatingPoint())
4026 return true;
4027 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4028 unsigned VecSize = getContext().getTypeSize(VT);
4029 if (VecSize == 64 || VecSize == 128)
4030 return true;
4031 }
4032 return false;
4033}
4034
4035bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4036 uint64_t Members) const {
4037 return Members <= 4;
4038}
4039
Tim Northoverb047bfa2014-11-27 21:02:49 +00004040llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4041 QualType Ty,
4042 CodeGenFunction &CGF) const {
4043 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004044 bool IsIndirect = AI.isIndirect();
4045
Tim Northoverb047bfa2014-11-27 21:02:49 +00004046 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4047 if (IsIndirect)
4048 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4049 else if (AI.getCoerceToType())
4050 BaseTy = AI.getCoerceToType();
4051
4052 unsigned NumRegs = 1;
4053 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4054 BaseTy = ArrTy->getElementType();
4055 NumRegs = ArrTy->getNumElements();
4056 }
4057 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4058
Tim Northovera2ee4332014-03-29 15:09:45 +00004059 // The AArch64 va_list type and handling is specified in the Procedure Call
4060 // Standard, section B.4:
4061 //
4062 // struct {
4063 // void *__stack;
4064 // void *__gr_top;
4065 // void *__vr_top;
4066 // int __gr_offs;
4067 // int __vr_offs;
4068 // };
4069
4070 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4071 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4072 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4073 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4074 auto &Ctx = CGF.getContext();
4075
Craig Topper8a13c412014-05-21 05:09:00 +00004076 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004077 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004078 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4079 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004080 // 3 is the field number of __gr_offs
4081 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4082 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4083 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004084 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004085 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004086 // 4 is the field number of __vr_offs.
4087 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4088 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4089 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004090 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004091 }
4092
4093 //=======================================
4094 // Find out where argument was passed
4095 //=======================================
4096
4097 // If reg_offs >= 0 we're already using the stack for this type of
4098 // argument. We don't want to keep updating reg_offs (in case it overflows,
4099 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4100 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004101 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004102 UsingStack = CGF.Builder.CreateICmpSGE(
4103 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4104
4105 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4106
4107 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004108 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004109 CGF.EmitBlock(MaybeRegBlock);
4110
4111 // Integer arguments may need to correct register alignment (for example a
4112 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4113 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004114 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004115 int Align = Ctx.getTypeAlign(Ty) / 8;
4116
4117 reg_offs = CGF.Builder.CreateAdd(
4118 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4119 "align_regoffs");
4120 reg_offs = CGF.Builder.CreateAnd(
4121 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4122 "aligned_regoffs");
4123 }
4124
4125 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004126 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004127 NewOffset = CGF.Builder.CreateAdd(
4128 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4129 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4130
4131 // Now we're in a position to decide whether this argument really was in
4132 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004133 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004134 InRegs = CGF.Builder.CreateICmpSLE(
4135 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4136
4137 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4138
4139 //=======================================
4140 // Argument was in registers
4141 //=======================================
4142
4143 // Now we emit the code for if the argument was originally passed in
4144 // registers. First start the appropriate block:
4145 CGF.EmitBlock(InRegBlock);
4146
Craig Topper8a13c412014-05-21 05:09:00 +00004147 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004148 reg_top_p =
4149 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4150 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4151 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004152 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004153 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4154
4155 if (IsIndirect) {
4156 // If it's been passed indirectly (actually a struct), whatever we find from
4157 // stored registers or on the stack will actually be a struct **.
4158 MemTy = llvm::PointerType::getUnqual(MemTy);
4159 }
4160
Craig Topper8a13c412014-05-21 05:09:00 +00004161 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004162 uint64_t NumMembers = 0;
4163 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004164 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004165 // Homogeneous aggregates passed in registers will have their elements split
4166 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4167 // qN+1, ...). We reload and store into a temporary local variable
4168 // contiguously.
4169 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4170 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4171 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4172 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4173 int Offset = 0;
4174
4175 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4176 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4177 for (unsigned i = 0; i < NumMembers; ++i) {
4178 llvm::Value *BaseOffset =
4179 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4180 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4181 LoadAddr = CGF.Builder.CreateBitCast(
4182 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4183 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4184
4185 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4186 CGF.Builder.CreateStore(Elem, StoreAddr);
4187 }
4188
4189 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4190 } else {
4191 // Otherwise the object is contiguous in memory
4192 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004193 if (CGF.CGM.getDataLayout().isBigEndian() &&
4194 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004195 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4196 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4197 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4198
4199 BaseAddr = CGF.Builder.CreateAdd(
4200 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4201
4202 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4203 }
4204
4205 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4206 }
4207
4208 CGF.EmitBranch(ContBlock);
4209
4210 //=======================================
4211 // Argument was on the stack
4212 //=======================================
4213 CGF.EmitBlock(OnStackBlock);
4214
Craig Topper8a13c412014-05-21 05:09:00 +00004215 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004216 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4217 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4218
4219 // Again, stack arguments may need realigmnent. In this case both integer and
4220 // floating-point ones might be affected.
4221 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4222 int Align = Ctx.getTypeAlign(Ty) / 8;
4223
4224 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4225
4226 OnStackAddr = CGF.Builder.CreateAdd(
4227 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4228 "align_stack");
4229 OnStackAddr = CGF.Builder.CreateAnd(
4230 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4231 "align_stack");
4232
4233 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4234 }
4235
4236 uint64_t StackSize;
4237 if (IsIndirect)
4238 StackSize = 8;
4239 else
4240 StackSize = Ctx.getTypeSize(Ty) / 8;
4241
4242 // All stack slots are 8 bytes
4243 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4244
4245 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4246 llvm::Value *NewStack =
4247 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4248
4249 // Write the new value of __stack for the next call to va_arg
4250 CGF.Builder.CreateStore(NewStack, stack_p);
4251
4252 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4253 Ctx.getTypeSize(Ty) < 64) {
4254 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4255 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4256
4257 OnStackAddr = CGF.Builder.CreateAdd(
4258 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4259
4260 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4261 }
4262
4263 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4264
4265 CGF.EmitBranch(ContBlock);
4266
4267 //=======================================
4268 // Tidy up
4269 //=======================================
4270 CGF.EmitBlock(ContBlock);
4271
4272 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4273 ResAddr->addIncoming(RegAddr, InRegBlock);
4274 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4275
4276 if (IsIndirect)
4277 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4278
4279 return ResAddr;
4280}
4281
Tim Northover573cbee2014-05-24 12:52:07 +00004282llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004283 CodeGenFunction &CGF) const {
4284 // We do not support va_arg for aggregates or illegal vector types.
4285 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4286 // other cases.
4287 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004288 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004289
4290 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4291 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4292
Craig Topper8a13c412014-05-21 05:09:00 +00004293 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004294 uint64_t Members = 0;
4295 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004296
4297 bool isIndirect = false;
4298 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4299 // be passed indirectly.
4300 if (Size > 16 && !isHA) {
4301 isIndirect = true;
4302 Size = 8;
4303 Align = 8;
4304 }
4305
4306 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4307 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4308
4309 CGBuilderTy &Builder = CGF.Builder;
4310 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4311 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4312
4313 if (isEmptyRecord(getContext(), Ty, true)) {
4314 // These are ignored for parameter passing purposes.
4315 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4316 return Builder.CreateBitCast(Addr, PTy);
4317 }
4318
4319 const uint64_t MinABIAlign = 8;
4320 if (Align > MinABIAlign) {
4321 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4322 Addr = Builder.CreateGEP(Addr, Offset);
4323 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4324 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4325 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4326 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4327 }
4328
4329 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4330 llvm::Value *NextAddr = Builder.CreateGEP(
4331 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4332 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4333
4334 if (isIndirect)
4335 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4336 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4337 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4338
4339 return AddrTyped;
4340}
4341
4342//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004343// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004344//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004345
4346namespace {
4347
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004348class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004349public:
4350 enum ABIKind {
4351 APCS = 0,
4352 AAPCS = 1,
4353 AAPCS_VFP
4354 };
4355
4356private:
4357 ABIKind Kind;
4358
4359public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004360 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004361 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004362 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004363
John McCall3480ef22011-08-30 01:42:09 +00004364 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004365 switch (getTarget().getTriple().getEnvironment()) {
4366 case llvm::Triple::Android:
4367 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004368 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004369 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004370 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004371 return true;
4372 default:
4373 return false;
4374 }
John McCall3480ef22011-08-30 01:42:09 +00004375 }
4376
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004377 bool isEABIHF() const {
4378 switch (getTarget().getTriple().getEnvironment()) {
4379 case llvm::Triple::EABIHF:
4380 case llvm::Triple::GNUEABIHF:
4381 return true;
4382 default:
4383 return false;
4384 }
4385 }
4386
Daniel Dunbar020daa92009-09-12 01:00:39 +00004387 ABIKind getABIKind() const { return Kind; }
4388
Tim Northovera484bc02013-10-01 14:34:25 +00004389private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004390 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004391 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004392 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004393
Reid Klecknere9f6a712014-10-31 17:10:41 +00004394 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4395 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4396 uint64_t Members) const override;
4397
Craig Topper4f12f102014-03-12 06:41:41 +00004398 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004399
Craig Topper4f12f102014-03-12 06:41:41 +00004400 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4401 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004402
4403 llvm::CallingConv::ID getLLVMDefaultCC() const;
4404 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004405 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004406};
4407
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004408class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4409public:
Chris Lattner2b037972010-07-29 02:01:43 +00004410 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4411 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004412
John McCall3480ef22011-08-30 01:42:09 +00004413 const ARMABIInfo &getABIInfo() const {
4414 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4415 }
4416
Craig Topper4f12f102014-03-12 06:41:41 +00004417 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004418 return 13;
4419 }
Roman Divackyc1617352011-05-18 19:36:54 +00004420
Craig Topper4f12f102014-03-12 06:41:41 +00004421 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004422 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4423 }
4424
Roman Divackyc1617352011-05-18 19:36:54 +00004425 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004426 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004427 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004428
4429 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004430 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004431 return false;
4432 }
John McCall3480ef22011-08-30 01:42:09 +00004433
Craig Topper4f12f102014-03-12 06:41:41 +00004434 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004435 if (getABIInfo().isEABI()) return 88;
4436 return TargetCodeGenInfo::getSizeOfUnwindException();
4437 }
Tim Northovera484bc02013-10-01 14:34:25 +00004438
4439 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004440 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004441 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4442 if (!FD)
4443 return;
4444
4445 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4446 if (!Attr)
4447 return;
4448
4449 const char *Kind;
4450 switch (Attr->getInterrupt()) {
4451 case ARMInterruptAttr::Generic: Kind = ""; break;
4452 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4453 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4454 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4455 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4456 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4457 }
4458
4459 llvm::Function *Fn = cast<llvm::Function>(GV);
4460
4461 Fn->addFnAttr("interrupt", Kind);
4462
4463 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4464 return;
4465
4466 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4467 // however this is not necessarily true on taking any interrupt. Instruct
4468 // the backend to perform a realignment as part of the function prologue.
4469 llvm::AttrBuilder B;
4470 B.addStackAlignmentAttr(8);
4471 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4472 llvm::AttributeSet::get(CGM.getLLVMContext(),
4473 llvm::AttributeSet::FunctionIndex,
4474 B));
4475 }
Joerg Sonnenberger096feeb2015-02-23 20:23:47 +00004476
4477 bool hasSjLjLowering(CodeGen::CodeGenFunction &CGF) const override {
4478 return false;
4479 // FIXME: backend implementation too restricted, even on Darwin.
4480 // return CGF.getTarget().getTriple().isOSDarwin();
4481 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004482};
4483
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004484class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4485 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4486 CodeGen::CodeGenModule &CGM) const;
4487
4488public:
4489 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4490 : ARMTargetCodeGenInfo(CGT, K) {}
4491
4492 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4493 CodeGen::CodeGenModule &CGM) const override;
4494};
4495
4496void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4497 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4498 if (!isa<FunctionDecl>(D))
4499 return;
4500 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4501 return;
4502
4503 llvm::Function *F = cast<llvm::Function>(GV);
4504 F->addFnAttr("stack-probe-size",
4505 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4506}
4507
4508void WindowsARMTargetCodeGenInfo::SetTargetAttributes(
4509 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4510 ARMTargetCodeGenInfo::SetTargetAttributes(D, GV, CGM);
4511 addStackProbeSizeTargetAttribute(D, GV, CGM);
4512}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004513}
4514
Chris Lattner22326a12010-07-29 02:31:05 +00004515void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004516 if (!getCXXABI().classifyReturnType(FI))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004517 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004518
Tim Northoverbc784d12015-02-24 17:22:40 +00004519 for (auto &I : FI.arguments())
4520 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004521
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004522 // Always honor user-specified calling convention.
4523 if (FI.getCallingConvention() != llvm::CallingConv::C)
4524 return;
4525
John McCall882987f2013-02-28 19:01:20 +00004526 llvm::CallingConv::ID cc = getRuntimeCC();
4527 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004528 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004529}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004530
John McCall882987f2013-02-28 19:01:20 +00004531/// Return the default calling convention that LLVM will use.
4532llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4533 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004534 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004535 return llvm::CallingConv::ARM_AAPCS_VFP;
4536 else if (isEABI())
4537 return llvm::CallingConv::ARM_AAPCS;
4538 else
4539 return llvm::CallingConv::ARM_APCS;
4540}
4541
4542/// Return the calling convention that our ABI would like us to use
4543/// as the C calling convention.
4544llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004545 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004546 case APCS: return llvm::CallingConv::ARM_APCS;
4547 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4548 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004549 }
John McCall882987f2013-02-28 19:01:20 +00004550 llvm_unreachable("bad ABI kind");
4551}
4552
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004553void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004554 assert(getRuntimeCC() == llvm::CallingConv::C);
4555
4556 // Don't muddy up the IR with a ton of explicit annotations if
4557 // they'd just match what LLVM will infer from the triple.
4558 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4559 if (abiCC != getLLVMDefaultCC())
4560 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004561
4562 BuiltinCC = (getABIKind() == APCS ?
4563 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004564}
4565
Tim Northoverbc784d12015-02-24 17:22:40 +00004566ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4567 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004568 // 6.1.2.1 The following argument types are VFP CPRCs:
4569 // A single-precision floating-point type (including promoted
4570 // half-precision types); A double-precision floating-point type;
4571 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4572 // with a Base Type of a single- or double-precision floating-point type,
4573 // 64-bit containerized vectors or 128-bit containerized vectors with one
4574 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004575 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004576
Reid Klecknerb1be6832014-11-15 01:41:41 +00004577 Ty = useFirstFieldIfTransparentUnion(Ty);
4578
Manman Renfef9e312012-10-16 19:18:39 +00004579 // Handle illegal vector types here.
4580 if (isIllegalVectorType(Ty)) {
4581 uint64_t Size = getContext().getTypeSize(Ty);
4582 if (Size <= 32) {
4583 llvm::Type *ResType =
4584 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004585 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004586 }
4587 if (Size == 64) {
4588 llvm::Type *ResType = llvm::VectorType::get(
4589 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004590 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004591 }
4592 if (Size == 128) {
4593 llvm::Type *ResType = llvm::VectorType::get(
4594 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004595 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004596 }
4597 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4598 }
4599
John McCalla1dee5302010-08-22 10:59:02 +00004600 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004601 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004602 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004603 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004604 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004605
Tim Northover5a1558e2014-11-07 22:30:50 +00004606 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4607 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004608 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004609
Oliver Stannard405bded2014-02-11 09:25:50 +00004610 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northover1060eae2013-06-21 22:49:34 +00004611 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004612 }
Tim Northover1060eae2013-06-21 22:49:34 +00004613
Daniel Dunbar09d33622009-09-14 21:54:03 +00004614 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004615 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004616 return ABIArgInfo::getIgnore();
4617
Tim Northover5a1558e2014-11-07 22:30:50 +00004618 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004619 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4620 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004621 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004622 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004623 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004624 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004625 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004626 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004627 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004628 }
4629
Manman Ren6c30e132012-08-13 21:23:55 +00004630 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004631 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4632 // most 8-byte. We realign the indirect argument if type alignment is bigger
4633 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004634 uint64_t ABIAlign = 4;
4635 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4636 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004637 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004638 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004639
Manman Ren8cd99812012-11-06 04:58:01 +00004640 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northoverd157e192015-03-09 21:40:42 +00004641 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004642 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004643 }
4644
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004645 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004646 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004647 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004648 // FIXME: Try to match the types of the arguments more accurately where
4649 // we can.
4650 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004651 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4652 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004653 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004654 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4655 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004656 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004657
Tim Northover5a1558e2014-11-07 22:30:50 +00004658 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004659}
4660
Chris Lattner458b2aa2010-07-29 02:16:43 +00004661static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004662 llvm::LLVMContext &VMContext) {
4663 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4664 // is called integer-like if its size is less than or equal to one word, and
4665 // the offset of each of its addressable sub-fields is zero.
4666
4667 uint64_t Size = Context.getTypeSize(Ty);
4668
4669 // Check that the type fits in a word.
4670 if (Size > 32)
4671 return false;
4672
4673 // FIXME: Handle vector types!
4674 if (Ty->isVectorType())
4675 return false;
4676
Daniel Dunbard53bac72009-09-14 02:20:34 +00004677 // Float types are never treated as "integer like".
4678 if (Ty->isRealFloatingType())
4679 return false;
4680
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004681 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004682 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004683 return true;
4684
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004685 // Small complex integer types are "integer like".
4686 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4687 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004688
4689 // Single element and zero sized arrays should be allowed, by the definition
4690 // above, but they are not.
4691
4692 // Otherwise, it must be a record type.
4693 const RecordType *RT = Ty->getAs<RecordType>();
4694 if (!RT) return false;
4695
4696 // Ignore records with flexible arrays.
4697 const RecordDecl *RD = RT->getDecl();
4698 if (RD->hasFlexibleArrayMember())
4699 return false;
4700
4701 // Check that all sub-fields are at offset 0, and are themselves "integer
4702 // like".
4703 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4704
4705 bool HadField = false;
4706 unsigned idx = 0;
4707 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4708 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004709 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004710
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004711 // Bit-fields are not addressable, we only need to verify they are "integer
4712 // like". We still have to disallow a subsequent non-bitfield, for example:
4713 // struct { int : 0; int x }
4714 // is non-integer like according to gcc.
4715 if (FD->isBitField()) {
4716 if (!RD->isUnion())
4717 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004718
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004719 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4720 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004721
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004722 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004723 }
4724
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004725 // Check if this field is at offset 0.
4726 if (Layout.getFieldOffset(idx) != 0)
4727 return false;
4728
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004729 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4730 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004731
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004732 // Only allow at most one field in a structure. This doesn't match the
4733 // wording above, but follows gcc in situations with a field following an
4734 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004735 if (!RD->isUnion()) {
4736 if (HadField)
4737 return false;
4738
4739 HadField = true;
4740 }
4741 }
4742
4743 return true;
4744}
4745
Oliver Stannard405bded2014-02-11 09:25:50 +00004746ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4747 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004748 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004749
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004750 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004751 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004752
Daniel Dunbar19964db2010-09-23 01:54:32 +00004753 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004754 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
Daniel Dunbar19964db2010-09-23 01:54:32 +00004755 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004756 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004757
John McCalla1dee5302010-08-22 10:59:02 +00004758 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004759 // Treat an enum type as its underlying type.
4760 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4761 RetTy = EnumTy->getDecl()->getIntegerType();
4762
Tim Northover5a1558e2014-11-07 22:30:50 +00004763 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4764 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004765 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004766
4767 // Are we following APCS?
4768 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004769 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004770 return ABIArgInfo::getIgnore();
4771
Daniel Dunbareedf1512010-02-01 23:31:19 +00004772 // Complex types are all returned as packed integers.
4773 //
4774 // FIXME: Consider using 2 x vector types if the back end handles them
4775 // correctly.
4776 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004777 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4778 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004779
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004780 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004781 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004782 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004783 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004784 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004785 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004786 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004787 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4788 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004789 }
4790
4791 // Otherwise return in memory.
4792 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004793 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004794
4795 // Otherwise this is an AAPCS variant.
4796
Chris Lattner458b2aa2010-07-29 02:16:43 +00004797 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004798 return ABIArgInfo::getIgnore();
4799
Bob Wilson1d9269a2011-11-02 04:51:36 +00004800 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004801 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004802 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004803 uint64_t Members;
4804 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004805 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004806 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004807 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004808 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004809 }
4810
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004811 // Aggregates <= 4 bytes are returned in r0; other aggregates
4812 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004813 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004814 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004815 if (getDataLayout().isBigEndian())
4816 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004817 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004818
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004819 // Return in the smallest viable integer type.
4820 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004821 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004822 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004823 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4824 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004825 }
4826
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004827 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004828}
4829
Manman Renfef9e312012-10-16 19:18:39 +00004830/// isIllegalVector - check whether Ty is an illegal vector type.
4831bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4832 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4833 // Check whether VT is legal.
4834 unsigned NumElements = VT->getNumElements();
4835 uint64_t Size = getContext().getTypeSize(VT);
4836 // NumElements should be power of 2.
4837 if ((NumElements & (NumElements - 1)) != 0)
4838 return true;
4839 // Size should be greater than 32 bits.
4840 return Size <= 32;
4841 }
4842 return false;
4843}
4844
Reid Klecknere9f6a712014-10-31 17:10:41 +00004845bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4846 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4847 // double, or 64-bit or 128-bit vectors.
4848 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4849 if (BT->getKind() == BuiltinType::Float ||
4850 BT->getKind() == BuiltinType::Double ||
4851 BT->getKind() == BuiltinType::LongDouble)
4852 return true;
4853 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4854 unsigned VecSize = getContext().getTypeSize(VT);
4855 if (VecSize == 64 || VecSize == 128)
4856 return true;
4857 }
4858 return false;
4859}
4860
4861bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4862 uint64_t Members) const {
4863 return Members <= 4;
4864}
4865
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004866llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004867 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004868 llvm::Type *BP = CGF.Int8PtrTy;
4869 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004870
4871 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004872 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004873 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004874
Tim Northover1711cc92013-06-21 23:05:33 +00004875 if (isEmptyRecord(getContext(), Ty, true)) {
4876 // These are ignored for parameter passing purposes.
4877 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4878 return Builder.CreateBitCast(Addr, PTy);
4879 }
4880
Manman Rencca54d02012-10-16 19:01:37 +00004881 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004882 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004883 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004884
4885 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4886 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004887 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4888 getABIKind() == ARMABIInfo::AAPCS)
4889 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4890 else
4891 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004892 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4893 if (isIllegalVectorType(Ty) && Size > 16) {
4894 IsIndirect = true;
4895 Size = 4;
4896 TyAlign = 4;
4897 }
Manman Rencca54d02012-10-16 19:01:37 +00004898
4899 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004900 if (TyAlign > 4) {
4901 assert((TyAlign & (TyAlign - 1)) == 0 &&
4902 "Alignment is not power of 2!");
4903 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4904 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4905 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004906 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004907 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004908
4909 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004910 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004911 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004912 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004913 "ap.next");
4914 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4915
Manman Renfef9e312012-10-16 19:18:39 +00004916 if (IsIndirect)
4917 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004918 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004919 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4920 // may not be correctly aligned for the vector type. We create an aligned
4921 // temporary space and copy the content over from ap.cur to the temporary
4922 // space. This is necessary if the natural alignment of the type is greater
4923 // than the ABI alignment.
4924 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4925 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4926 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4927 "var.align");
4928 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4929 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4930 Builder.CreateMemCpy(Dst, Src,
4931 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4932 TyAlign, false);
4933 Addr = AlignedTemp; //The content is in aligned location.
4934 }
4935 llvm::Type *PTy =
4936 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4937 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4938
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004939 return AddrTyped;
4940}
4941
Chris Lattner0cf24192010-06-28 20:05:43 +00004942//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004943// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004944//===----------------------------------------------------------------------===//
4945
4946namespace {
4947
Justin Holewinski83e96682012-05-24 17:43:12 +00004948class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004949public:
Justin Holewinski36837432013-03-30 14:38:24 +00004950 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004951
4952 ABIArgInfo classifyReturnType(QualType RetTy) const;
4953 ABIArgInfo classifyArgumentType(QualType Ty) const;
4954
Craig Topper4f12f102014-03-12 06:41:41 +00004955 void computeInfo(CGFunctionInfo &FI) const override;
4956 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4957 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004958};
4959
Justin Holewinski83e96682012-05-24 17:43:12 +00004960class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004961public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004962 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4963 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004964
4965 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4966 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004967private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00004968 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4969 // resulting MDNode to the nvvm.annotations MDNode.
4970 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004971};
4972
Justin Holewinski83e96682012-05-24 17:43:12 +00004973ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004974 if (RetTy->isVoidType())
4975 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004976
4977 // note: this is different from default ABI
4978 if (!RetTy->isScalarType())
4979 return ABIArgInfo::getDirect();
4980
4981 // Treat an enum type as its underlying type.
4982 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4983 RetTy = EnumTy->getDecl()->getIntegerType();
4984
4985 return (RetTy->isPromotableIntegerType() ?
4986 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004987}
4988
Justin Holewinski83e96682012-05-24 17:43:12 +00004989ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004990 // Treat an enum type as its underlying type.
4991 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4992 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004993
Eli Bendersky95338a02014-10-29 13:43:21 +00004994 // Return aggregates type as indirect by value
4995 if (isAggregateTypeForABI(Ty))
4996 return ABIArgInfo::getIndirect(0, /* byval */ true);
4997
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004998 return (Ty->isPromotableIntegerType() ?
4999 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005000}
5001
Justin Holewinski83e96682012-05-24 17:43:12 +00005002void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005003 if (!getCXXABI().classifyReturnType(FI))
5004 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005005 for (auto &I : FI.arguments())
5006 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005007
5008 // Always honor user-specified calling convention.
5009 if (FI.getCallingConvention() != llvm::CallingConv::C)
5010 return;
5011
John McCall882987f2013-02-28 19:01:20 +00005012 FI.setEffectiveCallingConvention(getRuntimeCC());
5013}
5014
Justin Holewinski83e96682012-05-24 17:43:12 +00005015llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5016 CodeGenFunction &CFG) const {
5017 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005018}
5019
Justin Holewinski83e96682012-05-24 17:43:12 +00005020void NVPTXTargetCodeGenInfo::
5021SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5022 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005023 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5024 if (!FD) return;
5025
5026 llvm::Function *F = cast<llvm::Function>(GV);
5027
5028 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005029 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005030 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005031 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005032 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005033 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005034 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5035 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005036 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005037 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005038 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005039 }
Justin Holewinski38031972011-10-05 17:58:44 +00005040
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005041 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005042 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005043 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005044 // __global__ functions cannot be called from the device, we do not
5045 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005046 if (FD->hasAttr<CUDAGlobalAttr>()) {
5047 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5048 addNVVMMetadata(F, "kernel", 1);
5049 }
5050 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5051 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5052 addNVVMMetadata(F, "maxntidx",
5053 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5054 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5055 // zero value from getMinBlocks either means it was not specified in
5056 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5057 // don't have to add a PTX directive.
5058 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5059 if (MinCTASM > 0) {
5060 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5061 addNVVMMetadata(F, "minctasm", MinCTASM);
5062 }
5063 }
Justin Holewinski38031972011-10-05 17:58:44 +00005064 }
5065}
5066
Eli Benderskye06a2c42014-04-15 16:57:05 +00005067void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5068 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005069 llvm::Module *M = F->getParent();
5070 llvm::LLVMContext &Ctx = M->getContext();
5071
5072 // Get "nvvm.annotations" metadata node
5073 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5074
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005075 llvm::Metadata *MDVals[] = {
5076 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5077 llvm::ConstantAsMetadata::get(
5078 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005079 // Append metadata to nvvm.annotations
5080 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5081}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005082}
5083
5084//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005085// SystemZ ABI Implementation
5086//===----------------------------------------------------------------------===//
5087
5088namespace {
5089
5090class SystemZABIInfo : public ABIInfo {
5091public:
5092 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5093
5094 bool isPromotableIntegerType(QualType Ty) const;
5095 bool isCompoundType(QualType Ty) const;
5096 bool isFPArgumentType(QualType Ty) const;
5097
5098 ABIArgInfo classifyReturnType(QualType RetTy) const;
5099 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5100
Craig Topper4f12f102014-03-12 06:41:41 +00005101 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005102 if (!getCXXABI().classifyReturnType(FI))
5103 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005104 for (auto &I : FI.arguments())
5105 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005106 }
5107
Craig Topper4f12f102014-03-12 06:41:41 +00005108 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5109 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005110};
5111
5112class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5113public:
5114 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5115 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5116};
5117
5118}
5119
5120bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5121 // Treat an enum type as its underlying type.
5122 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5123 Ty = EnumTy->getDecl()->getIntegerType();
5124
5125 // Promotable integer types are required to be promoted by the ABI.
5126 if (Ty->isPromotableIntegerType())
5127 return true;
5128
5129 // 32-bit values must also be promoted.
5130 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5131 switch (BT->getKind()) {
5132 case BuiltinType::Int:
5133 case BuiltinType::UInt:
5134 return true;
5135 default:
5136 return false;
5137 }
5138 return false;
5139}
5140
5141bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5142 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5143}
5144
5145bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5146 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5147 switch (BT->getKind()) {
5148 case BuiltinType::Float:
5149 case BuiltinType::Double:
5150 return true;
5151 default:
5152 return false;
5153 }
5154
5155 if (const RecordType *RT = Ty->getAsStructureType()) {
5156 const RecordDecl *RD = RT->getDecl();
5157 bool Found = false;
5158
5159 // If this is a C++ record, check the bases first.
5160 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005161 for (const auto &I : CXXRD->bases()) {
5162 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005163
5164 // Empty bases don't affect things either way.
5165 if (isEmptyRecord(getContext(), Base, true))
5166 continue;
5167
5168 if (Found)
5169 return false;
5170 Found = isFPArgumentType(Base);
5171 if (!Found)
5172 return false;
5173 }
5174
5175 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005176 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005177 // Empty bitfields don't affect things either way.
5178 // Unlike isSingleElementStruct(), empty structure and array fields
5179 // do count. So do anonymous bitfields that aren't zero-sized.
5180 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5181 return true;
5182
5183 // Unlike isSingleElementStruct(), arrays do not count.
5184 // Nested isFPArgumentType structures still do though.
5185 if (Found)
5186 return false;
5187 Found = isFPArgumentType(FD->getType());
5188 if (!Found)
5189 return false;
5190 }
5191
5192 // Unlike isSingleElementStruct(), trailing padding is allowed.
5193 // An 8-byte aligned struct s { float f; } is passed as a double.
5194 return Found;
5195 }
5196
5197 return false;
5198}
5199
5200llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5201 CodeGenFunction &CGF) const {
5202 // Assume that va_list type is correct; should be pointer to LLVM type:
5203 // struct {
5204 // i64 __gpr;
5205 // i64 __fpr;
5206 // i8 *__overflow_arg_area;
5207 // i8 *__reg_save_area;
5208 // };
5209
5210 // Every argument occupies 8 bytes and is passed by preference in either
5211 // GPRs or FPRs.
5212 Ty = CGF.getContext().getCanonicalType(Ty);
5213 ABIArgInfo AI = classifyArgumentType(Ty);
5214 bool InFPRs = isFPArgumentType(Ty);
5215
5216 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5217 bool IsIndirect = AI.isIndirect();
5218 unsigned UnpaddedBitSize;
5219 if (IsIndirect) {
5220 APTy = llvm::PointerType::getUnqual(APTy);
5221 UnpaddedBitSize = 64;
5222 } else
5223 UnpaddedBitSize = getContext().getTypeSize(Ty);
5224 unsigned PaddedBitSize = 64;
5225 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5226
5227 unsigned PaddedSize = PaddedBitSize / 8;
5228 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5229
5230 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5231 if (InFPRs) {
5232 MaxRegs = 4; // Maximum of 4 FPR arguments
5233 RegCountField = 1; // __fpr
5234 RegSaveIndex = 16; // save offset for f0
5235 RegPadding = 0; // floats are passed in the high bits of an FPR
5236 } else {
5237 MaxRegs = 5; // Maximum of 5 GPR arguments
5238 RegCountField = 0; // __gpr
5239 RegSaveIndex = 2; // save offset for r2
5240 RegPadding = Padding; // values are passed in the low bits of a GPR
5241 }
5242
5243 llvm::Value *RegCountPtr =
5244 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5245 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5246 llvm::Type *IndexTy = RegCount->getType();
5247 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5248 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005249 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005250
5251 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5252 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5253 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5254 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5255
5256 // Emit code to load the value if it was passed in registers.
5257 CGF.EmitBlock(InRegBlock);
5258
5259 // Work out the address of an argument register.
5260 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5261 llvm::Value *ScaledRegCount =
5262 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5263 llvm::Value *RegBase =
5264 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5265 llvm::Value *RegOffset =
5266 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5267 llvm::Value *RegSaveAreaPtr =
5268 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5269 llvm::Value *RegSaveArea =
5270 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5271 llvm::Value *RawRegAddr =
5272 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5273 llvm::Value *RegAddr =
5274 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5275
5276 // Update the register count
5277 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5278 llvm::Value *NewRegCount =
5279 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5280 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5281 CGF.EmitBranch(ContBlock);
5282
5283 // Emit code to load the value if it was passed in memory.
5284 CGF.EmitBlock(InMemBlock);
5285
5286 // Work out the address of a stack argument.
5287 llvm::Value *OverflowArgAreaPtr =
5288 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5289 llvm::Value *OverflowArgArea =
5290 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5291 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5292 llvm::Value *RawMemAddr =
5293 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5294 llvm::Value *MemAddr =
5295 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5296
5297 // Update overflow_arg_area_ptr pointer
5298 llvm::Value *NewOverflowArgArea =
5299 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5300 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5301 CGF.EmitBranch(ContBlock);
5302
5303 // Return the appropriate result.
5304 CGF.EmitBlock(ContBlock);
5305 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5306 ResAddr->addIncoming(RegAddr, InRegBlock);
5307 ResAddr->addIncoming(MemAddr, InMemBlock);
5308
5309 if (IsIndirect)
5310 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5311
5312 return ResAddr;
5313}
5314
Ulrich Weigand47445072013-05-06 16:26:41 +00005315ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5316 if (RetTy->isVoidType())
5317 return ABIArgInfo::getIgnore();
5318 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5319 return ABIArgInfo::getIndirect(0);
5320 return (isPromotableIntegerType(RetTy) ?
5321 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5322}
5323
5324ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5325 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005326 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005327 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5328
5329 // Integers and enums are extended to full register width.
5330 if (isPromotableIntegerType(Ty))
5331 return ABIArgInfo::getExtend();
5332
5333 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5334 uint64_t Size = getContext().getTypeSize(Ty);
5335 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005336 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005337
5338 // Handle small structures.
5339 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5340 // Structures with flexible arrays have variable length, so really
5341 // fail the size test above.
5342 const RecordDecl *RD = RT->getDecl();
5343 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005344 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005345
5346 // The structure is passed as an unextended integer, a float, or a double.
5347 llvm::Type *PassTy;
5348 if (isFPArgumentType(Ty)) {
5349 assert(Size == 32 || Size == 64);
5350 if (Size == 32)
5351 PassTy = llvm::Type::getFloatTy(getVMContext());
5352 else
5353 PassTy = llvm::Type::getDoubleTy(getVMContext());
5354 } else
5355 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5356 return ABIArgInfo::getDirect(PassTy);
5357 }
5358
5359 // Non-structure compounds are passed indirectly.
5360 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005361 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005362
Craig Topper8a13c412014-05-21 05:09:00 +00005363 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005364}
5365
5366//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005367// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005368//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005369
5370namespace {
5371
5372class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5373public:
Chris Lattner2b037972010-07-29 02:01:43 +00005374 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5375 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005376 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005377 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005378};
5379
5380}
5381
5382void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5383 llvm::GlobalValue *GV,
5384 CodeGen::CodeGenModule &M) const {
5385 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5386 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5387 // Handle 'interrupt' attribute:
5388 llvm::Function *F = cast<llvm::Function>(GV);
5389
5390 // Step 1: Set ISR calling convention.
5391 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5392
5393 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005394 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005395
5396 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005397 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005398 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5399 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005400 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005401 }
5402}
5403
Chris Lattner0cf24192010-06-28 20:05:43 +00005404//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005405// MIPS ABI Implementation. This works for both little-endian and
5406// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005407//===----------------------------------------------------------------------===//
5408
John McCall943fae92010-05-27 06:19:26 +00005409namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005410class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005411 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005412 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5413 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005414 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005415 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005416 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005417 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005418public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005419 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005420 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005421 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005422
5423 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005424 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005425 void computeInfo(CGFunctionInfo &FI) const override;
5426 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5427 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005428};
5429
John McCall943fae92010-05-27 06:19:26 +00005430class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005431 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005432public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005433 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5434 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005435 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005436
Craig Topper4f12f102014-03-12 06:41:41 +00005437 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005438 return 29;
5439 }
5440
Reed Kotler373feca2013-01-16 17:10:28 +00005441 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005442 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005443 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5444 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005445 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005446 if (FD->hasAttr<Mips16Attr>()) {
5447 Fn->addFnAttr("mips16");
5448 }
5449 else if (FD->hasAttr<NoMips16Attr>()) {
5450 Fn->addFnAttr("nomips16");
5451 }
Reed Kotler373feca2013-01-16 17:10:28 +00005452 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005453
John McCall943fae92010-05-27 06:19:26 +00005454 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005455 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005456
Craig Topper4f12f102014-03-12 06:41:41 +00005457 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005458 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005459 }
John McCall943fae92010-05-27 06:19:26 +00005460};
5461}
5462
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005463void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005464 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005465 llvm::IntegerType *IntTy =
5466 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005467
5468 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5469 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5470 ArgList.push_back(IntTy);
5471
5472 // If necessary, add one more integer type to ArgList.
5473 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5474
5475 if (R)
5476 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005477}
5478
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005479// In N32/64, an aligned double precision floating point field is passed in
5480// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005481llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005482 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5483
5484 if (IsO32) {
5485 CoerceToIntArgs(TySize, ArgList);
5486 return llvm::StructType::get(getVMContext(), ArgList);
5487 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005488
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005489 if (Ty->isComplexType())
5490 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005491
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005492 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005493
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005494 // Unions/vectors are passed in integer registers.
5495 if (!RT || !RT->isStructureOrClassType()) {
5496 CoerceToIntArgs(TySize, ArgList);
5497 return llvm::StructType::get(getVMContext(), ArgList);
5498 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005499
5500 const RecordDecl *RD = RT->getDecl();
5501 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005502 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005503
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005504 uint64_t LastOffset = 0;
5505 unsigned idx = 0;
5506 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5507
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005508 // Iterate over fields in the struct/class and check if there are any aligned
5509 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005510 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5511 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005512 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005513 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5514
5515 if (!BT || BT->getKind() != BuiltinType::Double)
5516 continue;
5517
5518 uint64_t Offset = Layout.getFieldOffset(idx);
5519 if (Offset % 64) // Ignore doubles that are not aligned.
5520 continue;
5521
5522 // Add ((Offset - LastOffset) / 64) args of type i64.
5523 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5524 ArgList.push_back(I64);
5525
5526 // Add double type.
5527 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5528 LastOffset = Offset + 64;
5529 }
5530
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005531 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5532 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005533
5534 return llvm::StructType::get(getVMContext(), ArgList);
5535}
5536
Akira Hatanakaddd66342013-10-29 18:41:15 +00005537llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5538 uint64_t Offset) const {
5539 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005540 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005541
Akira Hatanakaddd66342013-10-29 18:41:15 +00005542 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005543}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005544
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005545ABIArgInfo
5546MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005547 Ty = useFirstFieldIfTransparentUnion(Ty);
5548
Akira Hatanaka1632af62012-01-09 19:31:25 +00005549 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005550 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005551 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005552
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005553 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5554 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005555 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5556 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005557
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005558 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005559 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005560 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005561 return ABIArgInfo::getIgnore();
5562
Mark Lacey3825e832013-10-06 01:33:34 +00005563 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005564 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005565 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005566 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005567
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005568 // If we have reached here, aggregates are passed directly by coercing to
5569 // another structure type. Padding is inserted if the offset of the
5570 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005571 ABIArgInfo ArgInfo =
5572 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5573 getPaddingType(OrigOffset, CurrOffset));
5574 ArgInfo.setInReg(true);
5575 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005576 }
5577
5578 // Treat an enum type as its underlying type.
5579 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5580 Ty = EnumTy->getDecl()->getIntegerType();
5581
Daniel Sanders5b445b32014-10-24 14:42:42 +00005582 // All integral types are promoted to the GPR width.
5583 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005584 return ABIArgInfo::getExtend();
5585
Akira Hatanakaddd66342013-10-29 18:41:15 +00005586 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005587 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005588}
5589
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005590llvm::Type*
5591MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005592 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005593 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005594
Akira Hatanakab6f74432012-02-09 18:49:26 +00005595 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005596 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005597 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5598 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005599
Akira Hatanakab6f74432012-02-09 18:49:26 +00005600 // N32/64 returns struct/classes in floating point registers if the
5601 // following conditions are met:
5602 // 1. The size of the struct/class is no larger than 128-bit.
5603 // 2. The struct/class has one or two fields all of which are floating
5604 // point types.
5605 // 3. The offset of the first field is zero (this follows what gcc does).
5606 //
5607 // Any other composite results are returned in integer registers.
5608 //
5609 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5610 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5611 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005612 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005613
Akira Hatanakab6f74432012-02-09 18:49:26 +00005614 if (!BT || !BT->isFloatingPoint())
5615 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005616
David Blaikie2d7c57e2012-04-30 02:36:29 +00005617 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005618 }
5619
5620 if (b == e)
5621 return llvm::StructType::get(getVMContext(), RTList,
5622 RD->hasAttr<PackedAttr>());
5623
5624 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005625 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005626 }
5627
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005628 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005629 return llvm::StructType::get(getVMContext(), RTList);
5630}
5631
Akira Hatanakab579fe52011-06-02 00:09:17 +00005632ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005633 uint64_t Size = getContext().getTypeSize(RetTy);
5634
Daniel Sandersed39f582014-09-04 13:28:14 +00005635 if (RetTy->isVoidType())
5636 return ABIArgInfo::getIgnore();
5637
5638 // O32 doesn't treat zero-sized structs differently from other structs.
5639 // However, N32/N64 ignores zero sized return values.
5640 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005641 return ABIArgInfo::getIgnore();
5642
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005643 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005644 if (Size <= 128) {
5645 if (RetTy->isAnyComplexType())
5646 return ABIArgInfo::getDirect();
5647
Daniel Sanderse5018b62014-09-04 15:05:39 +00005648 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005649 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005650 if (!IsO32 ||
5651 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5652 ABIArgInfo ArgInfo =
5653 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5654 ArgInfo.setInReg(true);
5655 return ArgInfo;
5656 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005657 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005658
5659 return ABIArgInfo::getIndirect(0);
5660 }
5661
5662 // Treat an enum type as its underlying type.
5663 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5664 RetTy = EnumTy->getDecl()->getIntegerType();
5665
5666 return (RetTy->isPromotableIntegerType() ?
5667 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5668}
5669
5670void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005671 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005672 if (!getCXXABI().classifyReturnType(FI))
5673 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005674
5675 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005676 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005677
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005678 for (auto &I : FI.arguments())
5679 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005680}
5681
5682llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5683 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005684 llvm::Type *BP = CGF.Int8PtrTy;
5685 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005686
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005687 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
5688 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00005689 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00005690 unsigned PtrWidth = getTarget().getPointerWidth(0);
5691 if ((Ty->isIntegerType() &&
5692 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) ||
5693 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
Daniel Sanders59229dc2014-11-19 10:01:35 +00005694 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5695 Ty->isSignedIntegerType());
5696 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005697
5698 CGBuilderTy &Builder = CGF.Builder;
5699 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5700 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005701 int64_t TypeAlign =
5702 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005703 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5704 llvm::Value *AddrTyped;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005705 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5706
5707 if (TypeAlign > MinABIStackAlignInBytes) {
5708 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5709 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5710 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5711 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5712 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5713 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5714 }
5715 else
5716 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5717
5718 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5719 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005720 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5721 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005722 llvm::Value *NextAddr =
5723 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5724 "ap.next");
5725 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5726
5727 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005728}
5729
John McCall943fae92010-05-27 06:19:26 +00005730bool
5731MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5732 llvm::Value *Address) const {
5733 // This information comes from gcc's implementation, which seems to
5734 // as canonical as it gets.
5735
John McCall943fae92010-05-27 06:19:26 +00005736 // Everything on MIPS is 4 bytes. Double-precision FP registers
5737 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005738 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005739
5740 // 0-31 are the general purpose registers, $0 - $31.
5741 // 32-63 are the floating-point registers, $f0 - $f31.
5742 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5743 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005744 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005745
5746 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5747 // They are one bit wide and ignored here.
5748
5749 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5750 // (coprocessor 1 is the FP unit)
5751 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5752 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5753 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005754 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005755 return false;
5756}
5757
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005758//===----------------------------------------------------------------------===//
5759// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5760// Currently subclassed only to implement custom OpenCL C function attribute
5761// handling.
5762//===----------------------------------------------------------------------===//
5763
5764namespace {
5765
5766class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5767public:
5768 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5769 : DefaultTargetCodeGenInfo(CGT) {}
5770
Craig Topper4f12f102014-03-12 06:41:41 +00005771 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5772 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005773};
5774
5775void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5776 llvm::GlobalValue *GV,
5777 CodeGen::CodeGenModule &M) const {
5778 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5779 if (!FD) return;
5780
5781 llvm::Function *F = cast<llvm::Function>(GV);
5782
David Blaikiebbafb8a2012-03-11 07:00:24 +00005783 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005784 if (FD->hasAttr<OpenCLKernelAttr>()) {
5785 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005786 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005787 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5788 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005789 // Convert the reqd_work_group_size() attributes to metadata.
5790 llvm::LLVMContext &Context = F->getContext();
5791 llvm::NamedMDNode *OpenCLMetadata =
5792 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5793
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005794 SmallVector<llvm::Metadata *, 5> Operands;
5795 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005796
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005797 Operands.push_back(
5798 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5799 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5800 Operands.push_back(
5801 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5802 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5803 Operands.push_back(
5804 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5805 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005806
5807 // Add a boolean constant operand for "required" (true) or "hint" (false)
5808 // for implementing the work_group_size_hint attr later. Currently
5809 // always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005810 Operands.push_back(
5811 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005812 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5813 }
5814 }
5815 }
5816}
5817
5818}
John McCall943fae92010-05-27 06:19:26 +00005819
Tony Linthicum76329bf2011-12-12 21:14:55 +00005820//===----------------------------------------------------------------------===//
5821// Hexagon ABI Implementation
5822//===----------------------------------------------------------------------===//
5823
5824namespace {
5825
5826class HexagonABIInfo : public ABIInfo {
5827
5828
5829public:
5830 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5831
5832private:
5833
5834 ABIArgInfo classifyReturnType(QualType RetTy) const;
5835 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5836
Craig Topper4f12f102014-03-12 06:41:41 +00005837 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005838
Craig Topper4f12f102014-03-12 06:41:41 +00005839 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5840 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005841};
5842
5843class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5844public:
5845 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5846 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5847
Craig Topper4f12f102014-03-12 06:41:41 +00005848 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005849 return 29;
5850 }
5851};
5852
5853}
5854
5855void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005856 if (!getCXXABI().classifyReturnType(FI))
5857 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005858 for (auto &I : FI.arguments())
5859 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005860}
5861
5862ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5863 if (!isAggregateTypeForABI(Ty)) {
5864 // Treat an enum type as its underlying type.
5865 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5866 Ty = EnumTy->getDecl()->getIntegerType();
5867
5868 return (Ty->isPromotableIntegerType() ?
5869 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5870 }
5871
5872 // Ignore empty records.
5873 if (isEmptyRecord(getContext(), Ty, true))
5874 return ABIArgInfo::getIgnore();
5875
Mark Lacey3825e832013-10-06 01:33:34 +00005876 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005877 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005878
5879 uint64_t Size = getContext().getTypeSize(Ty);
5880 if (Size > 64)
5881 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5882 // Pass in the smallest viable integer type.
5883 else if (Size > 32)
5884 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5885 else if (Size > 16)
5886 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5887 else if (Size > 8)
5888 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5889 else
5890 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5891}
5892
5893ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5894 if (RetTy->isVoidType())
5895 return ABIArgInfo::getIgnore();
5896
5897 // Large vector types should be returned via memory.
5898 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5899 return ABIArgInfo::getIndirect(0);
5900
5901 if (!isAggregateTypeForABI(RetTy)) {
5902 // Treat an enum type as its underlying type.
5903 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5904 RetTy = EnumTy->getDecl()->getIntegerType();
5905
5906 return (RetTy->isPromotableIntegerType() ?
5907 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5908 }
5909
Tony Linthicum76329bf2011-12-12 21:14:55 +00005910 if (isEmptyRecord(getContext(), RetTy, true))
5911 return ABIArgInfo::getIgnore();
5912
5913 // Aggregates <= 8 bytes are returned in r0; other aggregates
5914 // are returned indirectly.
5915 uint64_t Size = getContext().getTypeSize(RetTy);
5916 if (Size <= 64) {
5917 // Return in the smallest viable integer type.
5918 if (Size <= 8)
5919 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5920 if (Size <= 16)
5921 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5922 if (Size <= 32)
5923 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5924 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5925 }
5926
5927 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5928}
5929
5930llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005931 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005932 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005933 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005934
5935 CGBuilderTy &Builder = CGF.Builder;
5936 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5937 "ap");
5938 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5939 llvm::Type *PTy =
5940 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5941 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5942
5943 uint64_t Offset =
5944 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5945 llvm::Value *NextAddr =
5946 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5947 "ap.next");
5948 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5949
5950 return AddrTyped;
5951}
5952
Matt Arsenault43fae6c2014-12-04 20:38:18 +00005953//===----------------------------------------------------------------------===//
5954// AMDGPU ABI Implementation
5955//===----------------------------------------------------------------------===//
5956
5957namespace {
5958
5959class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
5960public:
5961 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
5962 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
5963 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5964 CodeGen::CodeGenModule &M) const override;
5965};
5966
5967}
5968
5969void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
5970 const Decl *D,
5971 llvm::GlobalValue *GV,
5972 CodeGen::CodeGenModule &M) const {
5973 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5974 if (!FD)
5975 return;
5976
5977 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
5978 llvm::Function *F = cast<llvm::Function>(GV);
5979 uint32_t NumVGPR = Attr->getNumVGPR();
5980 if (NumVGPR != 0)
5981 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
5982 }
5983
5984 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
5985 llvm::Function *F = cast<llvm::Function>(GV);
5986 unsigned NumSGPR = Attr->getNumSGPR();
5987 if (NumSGPR != 0)
5988 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
5989 }
5990}
5991
Tony Linthicum76329bf2011-12-12 21:14:55 +00005992
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005993//===----------------------------------------------------------------------===//
5994// SPARC v9 ABI Implementation.
5995// Based on the SPARC Compliance Definition version 2.4.1.
5996//
5997// Function arguments a mapped to a nominal "parameter array" and promoted to
5998// registers depending on their type. Each argument occupies 8 or 16 bytes in
5999// the array, structs larger than 16 bytes are passed indirectly.
6000//
6001// One case requires special care:
6002//
6003// struct mixed {
6004// int i;
6005// float f;
6006// };
6007//
6008// When a struct mixed is passed by value, it only occupies 8 bytes in the
6009// parameter array, but the int is passed in an integer register, and the float
6010// is passed in a floating point register. This is represented as two arguments
6011// with the LLVM IR inreg attribute:
6012//
6013// declare void f(i32 inreg %i, float inreg %f)
6014//
6015// The code generator will only allocate 4 bytes from the parameter array for
6016// the inreg arguments. All other arguments are allocated a multiple of 8
6017// bytes.
6018//
6019namespace {
6020class SparcV9ABIInfo : public ABIInfo {
6021public:
6022 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6023
6024private:
6025 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006026 void computeInfo(CGFunctionInfo &FI) const override;
6027 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6028 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006029
6030 // Coercion type builder for structs passed in registers. The coercion type
6031 // serves two purposes:
6032 //
6033 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6034 // in registers.
6035 // 2. Expose aligned floating point elements as first-level elements, so the
6036 // code generator knows to pass them in floating point registers.
6037 //
6038 // We also compute the InReg flag which indicates that the struct contains
6039 // aligned 32-bit floats.
6040 //
6041 struct CoerceBuilder {
6042 llvm::LLVMContext &Context;
6043 const llvm::DataLayout &DL;
6044 SmallVector<llvm::Type*, 8> Elems;
6045 uint64_t Size;
6046 bool InReg;
6047
6048 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6049 : Context(c), DL(dl), Size(0), InReg(false) {}
6050
6051 // Pad Elems with integers until Size is ToSize.
6052 void pad(uint64_t ToSize) {
6053 assert(ToSize >= Size && "Cannot remove elements");
6054 if (ToSize == Size)
6055 return;
6056
6057 // Finish the current 64-bit word.
6058 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6059 if (Aligned > Size && Aligned <= ToSize) {
6060 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6061 Size = Aligned;
6062 }
6063
6064 // Add whole 64-bit words.
6065 while (Size + 64 <= ToSize) {
6066 Elems.push_back(llvm::Type::getInt64Ty(Context));
6067 Size += 64;
6068 }
6069
6070 // Final in-word padding.
6071 if (Size < ToSize) {
6072 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6073 Size = ToSize;
6074 }
6075 }
6076
6077 // Add a floating point element at Offset.
6078 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6079 // Unaligned floats are treated as integers.
6080 if (Offset % Bits)
6081 return;
6082 // The InReg flag is only required if there are any floats < 64 bits.
6083 if (Bits < 64)
6084 InReg = true;
6085 pad(Offset);
6086 Elems.push_back(Ty);
6087 Size = Offset + Bits;
6088 }
6089
6090 // Add a struct type to the coercion type, starting at Offset (in bits).
6091 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6092 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6093 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6094 llvm::Type *ElemTy = StrTy->getElementType(i);
6095 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6096 switch (ElemTy->getTypeID()) {
6097 case llvm::Type::StructTyID:
6098 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6099 break;
6100 case llvm::Type::FloatTyID:
6101 addFloat(ElemOffset, ElemTy, 32);
6102 break;
6103 case llvm::Type::DoubleTyID:
6104 addFloat(ElemOffset, ElemTy, 64);
6105 break;
6106 case llvm::Type::FP128TyID:
6107 addFloat(ElemOffset, ElemTy, 128);
6108 break;
6109 case llvm::Type::PointerTyID:
6110 if (ElemOffset % 64 == 0) {
6111 pad(ElemOffset);
6112 Elems.push_back(ElemTy);
6113 Size += 64;
6114 }
6115 break;
6116 default:
6117 break;
6118 }
6119 }
6120 }
6121
6122 // Check if Ty is a usable substitute for the coercion type.
6123 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006124 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006125 }
6126
6127 // Get the coercion type as a literal struct type.
6128 llvm::Type *getType() const {
6129 if (Elems.size() == 1)
6130 return Elems.front();
6131 else
6132 return llvm::StructType::get(Context, Elems);
6133 }
6134 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006135};
6136} // end anonymous namespace
6137
6138ABIArgInfo
6139SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6140 if (Ty->isVoidType())
6141 return ABIArgInfo::getIgnore();
6142
6143 uint64_t Size = getContext().getTypeSize(Ty);
6144
6145 // Anything too big to fit in registers is passed with an explicit indirect
6146 // pointer / sret pointer.
6147 if (Size > SizeLimit)
6148 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6149
6150 // Treat an enum type as its underlying type.
6151 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6152 Ty = EnumTy->getDecl()->getIntegerType();
6153
6154 // Integer types smaller than a register are extended.
6155 if (Size < 64 && Ty->isIntegerType())
6156 return ABIArgInfo::getExtend();
6157
6158 // Other non-aggregates go in registers.
6159 if (!isAggregateTypeForABI(Ty))
6160 return ABIArgInfo::getDirect();
6161
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006162 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6163 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6164 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6165 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6166
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006167 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006168 // Build a coercion type from the LLVM struct type.
6169 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6170 if (!StrTy)
6171 return ABIArgInfo::getDirect();
6172
6173 CoerceBuilder CB(getVMContext(), getDataLayout());
6174 CB.addStruct(0, StrTy);
6175 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6176
6177 // Try to use the original type for coercion.
6178 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6179
6180 if (CB.InReg)
6181 return ABIArgInfo::getDirectInReg(CoerceTy);
6182 else
6183 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006184}
6185
6186llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6187 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006188 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6189 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6190 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6191 AI.setCoerceToType(ArgTy);
6192
6193 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6194 CGBuilderTy &Builder = CGF.Builder;
6195 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6196 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6197 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6198 llvm::Value *ArgAddr;
6199 unsigned Stride;
6200
6201 switch (AI.getKind()) {
6202 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006203 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006204 llvm_unreachable("Unsupported ABI kind for va_arg");
6205
6206 case ABIArgInfo::Extend:
6207 Stride = 8;
6208 ArgAddr = Builder
6209 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6210 "extend");
6211 break;
6212
6213 case ABIArgInfo::Direct:
6214 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6215 ArgAddr = Addr;
6216 break;
6217
6218 case ABIArgInfo::Indirect:
6219 Stride = 8;
6220 ArgAddr = Builder.CreateBitCast(Addr,
6221 llvm::PointerType::getUnqual(ArgPtrTy),
6222 "indirect");
6223 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6224 break;
6225
6226 case ABIArgInfo::Ignore:
6227 return llvm::UndefValue::get(ArgPtrTy);
6228 }
6229
6230 // Update VAList.
6231 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6232 Builder.CreateStore(Addr, VAListAddrAsBPP);
6233
6234 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006235}
6236
6237void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6238 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006239 for (auto &I : FI.arguments())
6240 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006241}
6242
6243namespace {
6244class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6245public:
6246 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6247 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006248
Craig Topper4f12f102014-03-12 06:41:41 +00006249 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006250 return 14;
6251 }
6252
6253 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006254 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006255};
6256} // end anonymous namespace
6257
Roman Divackyf02c9942014-02-24 18:46:27 +00006258bool
6259SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6260 llvm::Value *Address) const {
6261 // This is calculated from the LLVM and GCC tables and verified
6262 // against gcc output. AFAIK all ABIs use the same encoding.
6263
6264 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6265
6266 llvm::IntegerType *i8 = CGF.Int8Ty;
6267 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6268 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6269
6270 // 0-31: the 8-byte general-purpose registers
6271 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6272
6273 // 32-63: f0-31, the 4-byte floating-point registers
6274 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6275
6276 // Y = 64
6277 // PSR = 65
6278 // WIM = 66
6279 // TBR = 67
6280 // PC = 68
6281 // NPC = 69
6282 // FSR = 70
6283 // CSR = 71
6284 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6285
6286 // 72-87: d0-15, the 8-byte floating-point registers
6287 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6288
6289 return false;
6290}
6291
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006292
Robert Lytton0e076492013-08-13 09:43:10 +00006293//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006294// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006295//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006296
Robert Lytton0e076492013-08-13 09:43:10 +00006297namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006298
6299/// A SmallStringEnc instance is used to build up the TypeString by passing
6300/// it by reference between functions that append to it.
6301typedef llvm::SmallString<128> SmallStringEnc;
6302
6303/// TypeStringCache caches the meta encodings of Types.
6304///
6305/// The reason for caching TypeStrings is two fold:
6306/// 1. To cache a type's encoding for later uses;
6307/// 2. As a means to break recursive member type inclusion.
6308///
6309/// A cache Entry can have a Status of:
6310/// NonRecursive: The type encoding is not recursive;
6311/// Recursive: The type encoding is recursive;
6312/// Incomplete: An incomplete TypeString;
6313/// IncompleteUsed: An incomplete TypeString that has been used in a
6314/// Recursive type encoding.
6315///
6316/// A NonRecursive entry will have all of its sub-members expanded as fully
6317/// as possible. Whilst it may contain types which are recursive, the type
6318/// itself is not recursive and thus its encoding may be safely used whenever
6319/// the type is encountered.
6320///
6321/// A Recursive entry will have all of its sub-members expanded as fully as
6322/// possible. The type itself is recursive and it may contain other types which
6323/// are recursive. The Recursive encoding must not be used during the expansion
6324/// of a recursive type's recursive branch. For simplicity the code uses
6325/// IncompleteCount to reject all usage of Recursive encodings for member types.
6326///
6327/// An Incomplete entry is always a RecordType and only encodes its
6328/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6329/// are placed into the cache during type expansion as a means to identify and
6330/// handle recursive inclusion of types as sub-members. If there is recursion
6331/// the entry becomes IncompleteUsed.
6332///
6333/// During the expansion of a RecordType's members:
6334///
6335/// If the cache contains a NonRecursive encoding for the member type, the
6336/// cached encoding is used;
6337///
6338/// If the cache contains a Recursive encoding for the member type, the
6339/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6340///
6341/// If the member is a RecordType, an Incomplete encoding is placed into the
6342/// cache to break potential recursive inclusion of itself as a sub-member;
6343///
6344/// Once a member RecordType has been expanded, its temporary incomplete
6345/// entry is removed from the cache. If a Recursive encoding was swapped out
6346/// it is swapped back in;
6347///
6348/// If an incomplete entry is used to expand a sub-member, the incomplete
6349/// entry is marked as IncompleteUsed. The cache keeps count of how many
6350/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6351///
6352/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6353/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6354/// Else the member is part of a recursive type and thus the recursion has
6355/// been exited too soon for the encoding to be correct for the member.
6356///
6357class TypeStringCache {
6358 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6359 struct Entry {
6360 std::string Str; // The encoded TypeString for the type.
6361 enum Status State; // Information about the encoding in 'Str'.
6362 std::string Swapped; // A temporary place holder for a Recursive encoding
6363 // during the expansion of RecordType's members.
6364 };
6365 std::map<const IdentifierInfo *, struct Entry> Map;
6366 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6367 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6368public:
Robert Lyttond263f142014-05-06 09:38:54 +00006369 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006370 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6371 bool removeIncomplete(const IdentifierInfo *ID);
6372 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6373 bool IsRecursive);
6374 StringRef lookupStr(const IdentifierInfo *ID);
6375};
6376
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006377/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006378/// FieldEncoding is a helper for this ordering process.
6379class FieldEncoding {
6380 bool HasName;
6381 std::string Enc;
6382public:
6383 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6384 StringRef str() {return Enc.c_str();};
6385 bool operator<(const FieldEncoding &rhs) const {
6386 if (HasName != rhs.HasName) return HasName;
6387 return Enc < rhs.Enc;
6388 }
6389};
6390
Robert Lytton7d1db152013-08-19 09:46:39 +00006391class XCoreABIInfo : public DefaultABIInfo {
6392public:
6393 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006394 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6395 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006396};
6397
Robert Lyttond21e2d72014-03-03 13:45:29 +00006398class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006399 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006400public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006401 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006402 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006403 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6404 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006405};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006406
Robert Lytton2d196952013-10-11 10:29:34 +00006407} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006408
Robert Lytton7d1db152013-08-19 09:46:39 +00006409llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6410 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006411 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006412
Robert Lytton2d196952013-10-11 10:29:34 +00006413 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006414 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6415 CGF.Int8PtrPtrTy);
6416 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006417
Robert Lytton2d196952013-10-11 10:29:34 +00006418 // Handle the argument.
6419 ABIArgInfo AI = classifyArgumentType(Ty);
6420 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6421 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6422 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006423 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006424 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006425 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006426 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006427 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006428 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006429 llvm_unreachable("Unsupported ABI kind for va_arg");
6430 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006431 Val = llvm::UndefValue::get(ArgPtrTy);
6432 ArgSize = 0;
6433 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006434 case ABIArgInfo::Extend:
6435 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006436 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6437 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6438 if (ArgSize < 4)
6439 ArgSize = 4;
6440 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006441 case ABIArgInfo::Indirect:
6442 llvm::Value *ArgAddr;
6443 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6444 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006445 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6446 ArgSize = 4;
6447 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006448 }
Robert Lytton2d196952013-10-11 10:29:34 +00006449
6450 // Increment the VAList.
6451 if (ArgSize) {
6452 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6453 Builder.CreateStore(APN, VAListAddrAsBPP);
6454 }
6455 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006456}
Robert Lytton0e076492013-08-13 09:43:10 +00006457
Robert Lytton844aeeb2014-05-02 09:33:20 +00006458/// During the expansion of a RecordType, an incomplete TypeString is placed
6459/// into the cache as a means to identify and break recursion.
6460/// If there is a Recursive encoding in the cache, it is swapped out and will
6461/// be reinserted by removeIncomplete().
6462/// All other types of encoding should have been used rather than arriving here.
6463void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6464 std::string StubEnc) {
6465 if (!ID)
6466 return;
6467 Entry &E = Map[ID];
6468 assert( (E.Str.empty() || E.State == Recursive) &&
6469 "Incorrectly use of addIncomplete");
6470 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6471 E.Swapped.swap(E.Str); // swap out the Recursive
6472 E.Str.swap(StubEnc);
6473 E.State = Incomplete;
6474 ++IncompleteCount;
6475}
6476
6477/// Once the RecordType has been expanded, the temporary incomplete TypeString
6478/// must be removed from the cache.
6479/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6480/// Returns true if the RecordType was defined recursively.
6481bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6482 if (!ID)
6483 return false;
6484 auto I = Map.find(ID);
6485 assert(I != Map.end() && "Entry not present");
6486 Entry &E = I->second;
6487 assert( (E.State == Incomplete ||
6488 E.State == IncompleteUsed) &&
6489 "Entry must be an incomplete type");
6490 bool IsRecursive = false;
6491 if (E.State == IncompleteUsed) {
6492 // We made use of our Incomplete encoding, thus we are recursive.
6493 IsRecursive = true;
6494 --IncompleteUsedCount;
6495 }
6496 if (E.Swapped.empty())
6497 Map.erase(I);
6498 else {
6499 // Swap the Recursive back.
6500 E.Swapped.swap(E.Str);
6501 E.Swapped.clear();
6502 E.State = Recursive;
6503 }
6504 --IncompleteCount;
6505 return IsRecursive;
6506}
6507
6508/// Add the encoded TypeString to the cache only if it is NonRecursive or
6509/// Recursive (viz: all sub-members were expanded as fully as possible).
6510void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6511 bool IsRecursive) {
6512 if (!ID || IncompleteUsedCount)
6513 return; // No key or it is is an incomplete sub-type so don't add.
6514 Entry &E = Map[ID];
6515 if (IsRecursive && !E.Str.empty()) {
6516 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6517 "This is not the same Recursive entry");
6518 // The parent container was not recursive after all, so we could have used
6519 // this Recursive sub-member entry after all, but we assumed the worse when
6520 // we started viz: IncompleteCount!=0.
6521 return;
6522 }
6523 assert(E.Str.empty() && "Entry already present");
6524 E.Str = Str.str();
6525 E.State = IsRecursive? Recursive : NonRecursive;
6526}
6527
6528/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6529/// are recursively expanding a type (IncompleteCount != 0) and the cached
6530/// encoding is Recursive, return an empty StringRef.
6531StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6532 if (!ID)
6533 return StringRef(); // We have no key.
6534 auto I = Map.find(ID);
6535 if (I == Map.end())
6536 return StringRef(); // We have no encoding.
6537 Entry &E = I->second;
6538 if (E.State == Recursive && IncompleteCount)
6539 return StringRef(); // We don't use Recursive encodings for member types.
6540
6541 if (E.State == Incomplete) {
6542 // The incomplete type is being used to break out of recursion.
6543 E.State = IncompleteUsed;
6544 ++IncompleteUsedCount;
6545 }
6546 return E.Str.c_str();
6547}
6548
6549/// The XCore ABI includes a type information section that communicates symbol
6550/// type information to the linker. The linker uses this information to verify
6551/// safety/correctness of things such as array bound and pointers et al.
6552/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6553/// This type information (TypeString) is emitted into meta data for all global
6554/// symbols: definitions, declarations, functions & variables.
6555///
6556/// The TypeString carries type, qualifier, name, size & value details.
6557/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6558/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6559/// The output is tested by test/CodeGen/xcore-stringtype.c.
6560///
6561static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6562 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6563
6564/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6565void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6566 CodeGen::CodeGenModule &CGM) const {
6567 SmallStringEnc Enc;
6568 if (getTypeString(Enc, D, CGM, TSC)) {
6569 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006570 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6571 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006572 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6573 llvm::NamedMDNode *MD =
6574 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6575 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6576 }
6577}
6578
6579static bool appendType(SmallStringEnc &Enc, QualType QType,
6580 const CodeGen::CodeGenModule &CGM,
6581 TypeStringCache &TSC);
6582
6583/// Helper function for appendRecordType().
6584/// Builds a SmallVector containing the encoded field types in declaration order.
6585static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6586 const RecordDecl *RD,
6587 const CodeGen::CodeGenModule &CGM,
6588 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006589 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006590 SmallStringEnc Enc;
6591 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006592 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006593 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006594 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006595 Enc += "b(";
6596 llvm::raw_svector_ostream OS(Enc);
6597 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006598 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006599 OS.flush();
6600 Enc += ':';
6601 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006602 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006603 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006604 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006605 Enc += ')';
6606 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006607 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006608 }
6609 return true;
6610}
6611
6612/// Appends structure and union types to Enc and adds encoding to cache.
6613/// Recursively calls appendType (via extractFieldType) for each field.
6614/// Union types have their fields ordered according to the ABI.
6615static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6616 const CodeGen::CodeGenModule &CGM,
6617 TypeStringCache &TSC, const IdentifierInfo *ID) {
6618 // Append the cached TypeString if we have one.
6619 StringRef TypeString = TSC.lookupStr(ID);
6620 if (!TypeString.empty()) {
6621 Enc += TypeString;
6622 return true;
6623 }
6624
6625 // Start to emit an incomplete TypeString.
6626 size_t Start = Enc.size();
6627 Enc += (RT->isUnionType()? 'u' : 's');
6628 Enc += '(';
6629 if (ID)
6630 Enc += ID->getName();
6631 Enc += "){";
6632
6633 // We collect all encoded fields and order as necessary.
6634 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006635 const RecordDecl *RD = RT->getDecl()->getDefinition();
6636 if (RD && !RD->field_empty()) {
6637 // An incomplete TypeString stub is placed in the cache for this RecordType
6638 // so that recursive calls to this RecordType will use it whilst building a
6639 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006640 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006641 std::string StubEnc(Enc.substr(Start).str());
6642 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6643 TSC.addIncomplete(ID, std::move(StubEnc));
6644 if (!extractFieldType(FE, RD, CGM, TSC)) {
6645 (void) TSC.removeIncomplete(ID);
6646 return false;
6647 }
6648 IsRecursive = TSC.removeIncomplete(ID);
6649 // The ABI requires unions to be sorted but not structures.
6650 // See FieldEncoding::operator< for sort algorithm.
6651 if (RT->isUnionType())
6652 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006653 // We can now complete the TypeString.
6654 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006655 for (unsigned I = 0; I != E; ++I) {
6656 if (I)
6657 Enc += ',';
6658 Enc += FE[I].str();
6659 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006660 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006661 Enc += '}';
6662 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6663 return true;
6664}
6665
6666/// Appends enum types to Enc and adds the encoding to the cache.
6667static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6668 TypeStringCache &TSC,
6669 const IdentifierInfo *ID) {
6670 // Append the cached TypeString if we have one.
6671 StringRef TypeString = TSC.lookupStr(ID);
6672 if (!TypeString.empty()) {
6673 Enc += TypeString;
6674 return true;
6675 }
6676
6677 size_t Start = Enc.size();
6678 Enc += "e(";
6679 if (ID)
6680 Enc += ID->getName();
6681 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006682
6683 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006684 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006685 SmallVector<FieldEncoding, 16> FE;
6686 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6687 ++I) {
6688 SmallStringEnc EnumEnc;
6689 EnumEnc += "m(";
6690 EnumEnc += I->getName();
6691 EnumEnc += "){";
6692 I->getInitVal().toString(EnumEnc);
6693 EnumEnc += '}';
6694 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6695 }
6696 std::sort(FE.begin(), FE.end());
6697 unsigned E = FE.size();
6698 for (unsigned I = 0; I != E; ++I) {
6699 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006700 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006701 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006702 }
6703 }
6704 Enc += '}';
6705 TSC.addIfComplete(ID, Enc.substr(Start), false);
6706 return true;
6707}
6708
6709/// Appends type's qualifier to Enc.
6710/// This is done prior to appending the type's encoding.
6711static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6712 // Qualifiers are emitted in alphabetical order.
6713 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6714 int Lookup = 0;
6715 if (QT.isConstQualified())
6716 Lookup += 1<<0;
6717 if (QT.isRestrictQualified())
6718 Lookup += 1<<1;
6719 if (QT.isVolatileQualified())
6720 Lookup += 1<<2;
6721 Enc += Table[Lookup];
6722}
6723
6724/// Appends built-in types to Enc.
6725static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6726 const char *EncType;
6727 switch (BT->getKind()) {
6728 case BuiltinType::Void:
6729 EncType = "0";
6730 break;
6731 case BuiltinType::Bool:
6732 EncType = "b";
6733 break;
6734 case BuiltinType::Char_U:
6735 EncType = "uc";
6736 break;
6737 case BuiltinType::UChar:
6738 EncType = "uc";
6739 break;
6740 case BuiltinType::SChar:
6741 EncType = "sc";
6742 break;
6743 case BuiltinType::UShort:
6744 EncType = "us";
6745 break;
6746 case BuiltinType::Short:
6747 EncType = "ss";
6748 break;
6749 case BuiltinType::UInt:
6750 EncType = "ui";
6751 break;
6752 case BuiltinType::Int:
6753 EncType = "si";
6754 break;
6755 case BuiltinType::ULong:
6756 EncType = "ul";
6757 break;
6758 case BuiltinType::Long:
6759 EncType = "sl";
6760 break;
6761 case BuiltinType::ULongLong:
6762 EncType = "ull";
6763 break;
6764 case BuiltinType::LongLong:
6765 EncType = "sll";
6766 break;
6767 case BuiltinType::Float:
6768 EncType = "ft";
6769 break;
6770 case BuiltinType::Double:
6771 EncType = "d";
6772 break;
6773 case BuiltinType::LongDouble:
6774 EncType = "ld";
6775 break;
6776 default:
6777 return false;
6778 }
6779 Enc += EncType;
6780 return true;
6781}
6782
6783/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6784static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6785 const CodeGen::CodeGenModule &CGM,
6786 TypeStringCache &TSC) {
6787 Enc += "p(";
6788 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6789 return false;
6790 Enc += ')';
6791 return true;
6792}
6793
6794/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006795static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6796 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006797 const CodeGen::CodeGenModule &CGM,
6798 TypeStringCache &TSC, StringRef NoSizeEnc) {
6799 if (AT->getSizeModifier() != ArrayType::Normal)
6800 return false;
6801 Enc += "a(";
6802 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6803 CAT->getSize().toStringUnsigned(Enc);
6804 else
6805 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6806 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006807 // The Qualifiers should be attached to the type rather than the array.
6808 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006809 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6810 return false;
6811 Enc += ')';
6812 return true;
6813}
6814
6815/// Appends a function encoding to Enc, calling appendType for the return type
6816/// and the arguments.
6817static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6818 const CodeGen::CodeGenModule &CGM,
6819 TypeStringCache &TSC) {
6820 Enc += "f{";
6821 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6822 return false;
6823 Enc += "}(";
6824 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6825 // N.B. we are only interested in the adjusted param types.
6826 auto I = FPT->param_type_begin();
6827 auto E = FPT->param_type_end();
6828 if (I != E) {
6829 do {
6830 if (!appendType(Enc, *I, CGM, TSC))
6831 return false;
6832 ++I;
6833 if (I != E)
6834 Enc += ',';
6835 } while (I != E);
6836 if (FPT->isVariadic())
6837 Enc += ",va";
6838 } else {
6839 if (FPT->isVariadic())
6840 Enc += "va";
6841 else
6842 Enc += '0';
6843 }
6844 }
6845 Enc += ')';
6846 return true;
6847}
6848
6849/// Handles the type's qualifier before dispatching a call to handle specific
6850/// type encodings.
6851static bool appendType(SmallStringEnc &Enc, QualType QType,
6852 const CodeGen::CodeGenModule &CGM,
6853 TypeStringCache &TSC) {
6854
6855 QualType QT = QType.getCanonicalType();
6856
Robert Lytton6adb20f2014-06-05 09:06:21 +00006857 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6858 // The Qualifiers should be attached to the type rather than the array.
6859 // Thus we don't call appendQualifier() here.
6860 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6861
Robert Lytton844aeeb2014-05-02 09:33:20 +00006862 appendQualifier(Enc, QT);
6863
6864 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6865 return appendBuiltinType(Enc, BT);
6866
Robert Lytton844aeeb2014-05-02 09:33:20 +00006867 if (const PointerType *PT = QT->getAs<PointerType>())
6868 return appendPointerType(Enc, PT, CGM, TSC);
6869
6870 if (const EnumType *ET = QT->getAs<EnumType>())
6871 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6872
6873 if (const RecordType *RT = QT->getAsStructureType())
6874 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6875
6876 if (const RecordType *RT = QT->getAsUnionType())
6877 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6878
6879 if (const FunctionType *FT = QT->getAs<FunctionType>())
6880 return appendFunctionType(Enc, FT, CGM, TSC);
6881
6882 return false;
6883}
6884
6885static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6886 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6887 if (!D)
6888 return false;
6889
6890 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6891 if (FD->getLanguageLinkage() != CLanguageLinkage)
6892 return false;
6893 return appendType(Enc, FD->getType(), CGM, TSC);
6894 }
6895
6896 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6897 if (VD->getLanguageLinkage() != CLanguageLinkage)
6898 return false;
6899 QualType QT = VD->getType().getCanonicalType();
6900 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6901 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006902 // The Qualifiers should be attached to the type rather than the array.
6903 // Thus we don't call appendQualifier() here.
6904 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00006905 }
6906 return appendType(Enc, QT, CGM, TSC);
6907 }
6908 return false;
6909}
6910
6911
Robert Lytton0e076492013-08-13 09:43:10 +00006912//===----------------------------------------------------------------------===//
6913// Driver code
6914//===----------------------------------------------------------------------===//
6915
Rafael Espindola9f834732014-09-19 01:54:22 +00006916const llvm::Triple &CodeGenModule::getTriple() const {
6917 return getTarget().getTriple();
6918}
6919
6920bool CodeGenModule::supportsCOMDAT() const {
6921 return !getTriple().isOSBinFormatMachO();
6922}
6923
Chris Lattner2b037972010-07-29 02:01:43 +00006924const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006925 if (TheTargetCodeGenInfo)
6926 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006927
John McCallc8e01702013-04-16 22:48:15 +00006928 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00006929 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00006930 default:
Chris Lattner2b037972010-07-29 02:01:43 +00006931 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00006932
Derek Schuff09338a22012-09-06 17:37:28 +00006933 case llvm::Triple::le32:
6934 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00006935 case llvm::Triple::mips:
6936 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006937 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6938
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00006939 case llvm::Triple::mips64:
6940 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006941 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6942
Tim Northover25e8a672014-05-24 12:51:25 +00006943 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00006944 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00006945 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006946 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00006947 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00006948
Tim Northover573cbee2014-05-24 12:52:07 +00006949 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00006950 }
6951
Daniel Dunbard59655c2009-09-12 00:59:49 +00006952 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006953 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00006954 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006955 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006956 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00006957 if (Triple.getOS() == llvm::Triple::Win32) {
6958 TheTargetCodeGenInfo =
6959 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
6960 return *TheTargetCodeGenInfo;
6961 }
6962
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006963 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006964 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006965 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00006966 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00006967 (CodeGenOpts.FloatABI != "soft" &&
6968 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006969 Kind = ARMABIInfo::AAPCS_VFP;
6970
Derek Schuff71658bd2015-01-29 00:47:04 +00006971 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006972 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00006973
John McCallea8d8bb2010-03-11 00:10:12 +00006974 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00006975 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00006976 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00006977 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00006978 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006979 if (getTarget().getABI() == "elfv2")
6980 Kind = PPC64_SVR4_ABIInfo::ELFv2;
6981
Ulrich Weigandb7122372014-07-21 00:48:09 +00006982 return *(TheTargetCodeGenInfo =
6983 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6984 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00006985 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00006986 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00006987 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00006988 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006989 if (getTarget().getABI() == "elfv1")
6990 Kind = PPC64_SVR4_ABIInfo::ELFv1;
6991
Ulrich Weigandb7122372014-07-21 00:48:09 +00006992 return *(TheTargetCodeGenInfo =
6993 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6994 }
John McCallea8d8bb2010-03-11 00:10:12 +00006995
Peter Collingbournec947aae2012-05-20 23:28:41 +00006996 case llvm::Triple::nvptx:
6997 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00006998 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006999
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007000 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007001 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007002
Ulrich Weigand47445072013-05-06 16:26:41 +00007003 case llvm::Triple::systemz:
7004 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7005
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007006 case llvm::Triple::tce:
7007 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7008
Eli Friedman33465822011-07-08 23:31:17 +00007009 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007010 bool IsDarwinVectorABI = Triple.isOSDarwin();
7011 bool IsSmallStructInRegABI =
7012 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007013 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007014
John McCall1fe2a8c2013-06-18 02:46:29 +00007015 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007016 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007017 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007018 IsDarwinVectorABI, IsSmallStructInRegABI,
7019 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007020 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007021 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007022 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007023 new X86_32TargetCodeGenInfo(Types,
7024 IsDarwinVectorABI, IsSmallStructInRegABI,
7025 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007026 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007027 }
Eli Friedman33465822011-07-08 23:31:17 +00007028 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007029
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007030 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007031 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007032
Chris Lattner04dc9572010-08-31 16:44:54 +00007033 switch (Triple.getOS()) {
7034 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007035 return *(TheTargetCodeGenInfo =
7036 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007037 case llvm::Triple::PS4:
7038 return *(TheTargetCodeGenInfo = new PS4TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007039 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007040 return *(TheTargetCodeGenInfo =
7041 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007042 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007043 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007044 case llvm::Triple::hexagon:
7045 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007046 case llvm::Triple::r600:
7047 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007048 case llvm::Triple::amdgcn:
7049 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007050 case llvm::Triple::sparcv9:
7051 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007052 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007053 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007054 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007055}