blob: 2604720cfe595811a474192767777fbfddac7f14 [file] [log] [blame]
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikovc4a59eb2009-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 Korobeynikov82d0a412010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Stephen Hines176edba2014-12-01 14:53:08 -080018#include "CGValue.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Lacey8b549992013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel34c1af82011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar2c0843f2009-08-24 08:52:16 +000023#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/Type.h"
Daniel Dunbar28df7a52009-12-03 09:13:49 +000026#include "llvm/Support/raw_ostream.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070027
28#include <algorithm> // std::sort
29
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCallaeeb7012010-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 McCalld608cdb2010-08-22 10:59:02 +000045static bool isAggregateTypeForABI(QualType T) {
John McCall9d232c82013-03-07 21:37:08 +000046 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalld608cdb2010-08-22 10:59:02 +000047 T->isMemberFunctionPointerType();
48}
49
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000050ABIInfo::~ABIInfo() {}
51
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000052static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey23630722013-10-06 01:33:34 +000053 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000054 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
55 if (!RD)
56 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000057 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000058}
59
60static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey23630722013-10-06 01:33:34 +000061 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000062 const RecordType *RT = T->getAs<RecordType>();
63 if (!RT)
64 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000065 return getRecordArgABI(RT, CXXABI);
66}
67
Stephen Hines176edba2014-12-01 14:53:08 -080068/// 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 Lacey23630722013-10-06 01:33:34 +000081CGCXXABI &ABIInfo::getCXXABI() const {
82 return CGT.getCXXABI();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000083}
84
Chris Lattnerea044322010-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 Villmow25a6a842012-10-08 16:25:52 +000093const llvm::DataLayout &ABIInfo::getDataLayout() const {
94 return CGT.getDataLayout();
Chris Lattnerea044322010-07-29 02:01:43 +000095}
96
John McCall64aa4b32013-04-16 22:48:15 +000097const TargetInfo &ABIInfo::getTarget() const {
98 return CGT.getTarget();
99}
Chris Lattnerea044322010-07-29 02:01:43 +0000100
Stephen Hines176edba2014-12-01 14:53:08 -0800101bool 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 Korobeynikovc4a59eb2009-06-05 22:08:42 +0000110void ABIArgInfo::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000111 raw_ostream &OS = llvm::errs();
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000112 OS << "(ABIArgInfo Kind=";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000113 switch (TheKind) {
114 case Direct:
Chris Lattner800588f2010-07-29 06:26:06 +0000115 OS << "Direct Type=";
Chris Lattner2acc6e32011-07-18 04:24:23 +0000116 if (llvm::Type *Ty = getCoerceToType())
Chris Lattner800588f2010-07-29 06:26:06 +0000117 Ty->print(OS);
118 else
119 OS << "null";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000120 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000121 case Extend:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000122 OS << "Extend";
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000123 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000124 case Ignore:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000125 OS << "Ignore";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000126 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700127 case InAlloca:
128 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
129 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000130 case Indirect:
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000131 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenbergere9b5d772011-07-15 18:23:44 +0000132 << " ByVal=" << getIndirectByVal()
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000133 << " Realign=" << getIndirectRealign();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000134 break;
135 case Expand:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000136 OS << "Expand";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000137 break;
138 }
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000139 OS << ")\n";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000140}
141
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000142TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
143
John McCall49e34be2011-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 Northoverc264e162013-01-31 12:13:10 +0000152 // AArch64 Linux
John McCall49e34be2011-08-30 01:42:09 +0000153 return 32;
154}
155
John McCallde5d3c72012-02-17 03:33:10 +0000156bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
157 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-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 Kleckner3190ca92013-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 Dunbar98303b92009-09-13 08:03:58 +0000175static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000176
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000177/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000178/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar98303b92009-09-13 08:03:58 +0000179static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
180 bool AllowArrays) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000181 if (FD->isUnnamedBitfield())
182 return true;
183
184 QualType FT = FD->getType();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000185
Eli Friedman7e7ad3f2011-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 Dunbar98303b92009-09-13 08:03:58 +0000188 if (AllowArrays)
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000189 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
190 if (AT->getSize() == 0)
191 return true;
Daniel Dunbar98303b92009-09-13 08:03:58 +0000192 FT = AT->getElementType();
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000193 }
Daniel Dunbar98303b92009-09-13 08:03:58 +0000194
Daniel Dunbar5ea68612010-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 Dunbar98303b92009-09-13 08:03:58 +0000206 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000207}
208
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000209/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000210/// fields. Note that a structure with a flexible array member is not
211/// considered empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000212static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000213 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-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 Dunbar5ea68612010-05-17 16:46:00 +0000219
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000220 // If this is a C++ record, check the bases first.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000221 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -0700222 for (const auto &I : CXXRD->bases())
223 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000224 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000225
Stephen Hines651f13c2014-04-23 16:59:28 -0700226 for (const auto *I : RD->fields())
227 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikovc4a59eb2009-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) {
241 const RecordType *RT = T->getAsStructureType();
242 if (!RT)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700243 return nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000244
245 const RecordDecl *RD = RT->getDecl();
246 if (RD->hasFlexibleArrayMember())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700247 return nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000248
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700249 const Type *Found = nullptr;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000250
Daniel Dunbar9430d5a2010-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)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700253 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000254 // Ignore empty records.
Stephen Hines651f13c2014-04-23 16:59:28 -0700255 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar9430d5a2010-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)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700260 return nullptr;
Daniel Dunbar9430d5a2010-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700264 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000265 if (!Found)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700266 return nullptr;
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000267 }
268 }
269
270 // Check for single element.
Stephen Hines651f13c2014-04-23 16:59:28 -0700271 for (const auto *FD : RD->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000272 QualType FT = FD->getType();
273
274 // Ignore empty fields.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000275 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-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)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700281 return nullptr;
Anton Korobeynikovc4a59eb2009-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 McCalld608cdb2010-08-22 10:59:02 +0000290 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000291 Found = FT.getTypePtr();
292 } else {
293 Found = isSingleElementStruct(FT, Context);
294 if (!Found)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700295 return nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000296 }
297 }
298
Eli Friedmanbd4d3bc2011-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))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700302 return nullptr;
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000303
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000304 return Found;
305}
306
307static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmandb748a32012-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 Dunbara1842d32010-05-14 03:40:53 +0000315 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmandb748a32012-11-29 23:21:04 +0000316 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikovc4a59eb2009-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 Dunbar53012f42009-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 Friedman506d4e32011-11-18 01:32:26 +0000345 uint64_t Size = 0;
346
Stephen Hines651f13c2014-04-23 16:59:28 -0700347 for (const auto *FD : RD->fields()) {
Anton Korobeynikovc4a59eb2009-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 Friedman506d4e32011-11-18 01:32:26 +0000356
357 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000358 }
359
Eli Friedman506d4e32011-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 Korobeynikovc4a59eb2009-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 Lattnerea044322010-07-29 02:01:43 +0000373public:
374 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000375
Chris Lattnera3c109b2010-07-29 02:16:43 +0000376 ABIArgInfo classifyReturnType(QualType RetTy) const;
377 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000378
Stephen Hines651f13c2014-04-23 16:59:28 -0700379 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700380 if (!getCXXABI().classifyReturnType(FI))
381 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -0700382 for (auto &I : FI.arguments())
383 I.info = classifyArgumentType(I.type);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000384 }
385
Stephen Hines651f13c2014-04-23 16:59:28 -0700386 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
387 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000388};
389
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000390class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
391public:
Chris Lattnerea044322010-07-29 02:01:43 +0000392 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
393 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000394};
395
396llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
397 CodeGenFunction &CGF) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700398 return nullptr;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000399}
400
Chris Lattnera3c109b2010-07-29 02:16:43 +0000401ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700402 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000403 return ABIArgInfo::getIndirect(0);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000404
Chris Lattnera14db752010-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 Gregoraa74a1e2010-02-02 20:10:50 +0000408
Chris Lattnera14db752010-03-11 18:19:55 +0000409 return (Ty->isPromotableIntegerType() ?
410 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000411}
412
Bob Wilson0024f942011-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 Schuff9ed63f82012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429// le32/PNaCl bitcode ABI Implementation
Eli Benderskyc0783dc2013-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 Schuff9ed63f82012-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 Benderskyc0783dc2013-04-08 21:31:01 +0000440 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000441
Stephen Hines651f13c2014-04-23 16:59:28 -0700442 void computeInfo(CGFunctionInfo &FI) const override;
443 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
444 CodeGenFunction &CGF) const override;
Derek Schuff9ed63f82012-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 {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700454 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff9ed63f82012-09-06 17:37:28 +0000455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
456
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700457 for (auto &I : FI.arguments())
458 I.info = classifyArgumentType(I.type);
459}
Derek Schuff9ed63f82012-09-06 17:37:28 +0000460
461llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
462 CodeGenFunction &CGF) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700463 return nullptr;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000464}
465
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000466/// \brief Classify argument of given type \p Ty.
467ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff9ed63f82012-09-06 17:37:28 +0000468 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +0000469 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000470 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000471 return ABIArgInfo::getIndirect(0);
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000472 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
473 // Treat an enum type as its underlying type.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000474 Ty = EnumTy->getDecl()->getIntegerType();
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000475 } else if (Ty->isFloatingType()) {
476 // Floating-point types don't go inreg.
477 return ABIArgInfo::getDirect();
Derek Schuff9ed63f82012-09-06 17:37:28 +0000478 }
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000479
480 return (Ty->isPromotableIntegerType() ?
481 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff9ed63f82012-09-06 17:37:28 +0000482}
483
484ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
485 if (RetTy->isVoidType())
486 return ABIArgInfo::getIgnore();
487
Eli Benderskye45dfd12013-04-04 22:49:35 +0000488 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff9ed63f82012-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 Rosier1f1df1f2013-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 Wendlingbb465d72010-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 Foadef6de3d2011-07-11 09:56:20 +0000508static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000509 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000510 llvm::Type* Ty) {
Tim Northover1bea6532013-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
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700514 return nullptr;
Tim Northover1bea6532013-06-07 00:04:50 +0000515 }
516
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000517 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover1bea6532013-06-07 00:04:50 +0000518 }
519
520 // No operation needed
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000521 return Ty;
522}
523
Stephen Hines176edba2014-12-01 14:53:08 -0800524/// 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 Lattnerdce5ad02010-06-28 20:05:43 +0000546//===----------------------------------------------------------------------===//
547// X86-32 ABI Implementation
548//===----------------------------------------------------------------------===//
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000549
Stephen Hines651f13c2014-04-23 16:59:28 -0700550/// \brief Similar to llvm::CCState, but for Clang.
551struct CCState {
Stephen Hines176edba2014-12-01 14:53:08 -0800552 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700553
554 unsigned CC;
555 unsigned FreeRegs;
Stephen Hines176edba2014-12-01 14:53:08 -0800556 unsigned FreeSSERegs;
Stephen Hines651f13c2014-04-23 16:59:28 -0700557};
558
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000559/// X86_32ABIInfo - The X86-32 ABI information.
560class X86_32ABIInfo : public ABIInfo {
Rafael Espindolab48280b2012-07-31 02:44:24 +0000561 enum Class {
562 Integer,
563 Float
564 };
565
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000566 static const unsigned MinABIStackAlignInBytes = 4;
567
David Chisnall1e4249c2009-08-17 23:08:21 +0000568 bool IsDarwinVectorABI;
569 bool IsSmallStructInRegABI;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000570 bool IsWin32StructABI;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000571 unsigned DefaultNumRegisterParameters;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000572
573 static bool isRegisterSize(unsigned Size) {
574 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
575 }
576
Stephen Hines176edba2014-12-01 14:53:08 -0800577 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
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700588 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000589
Daniel Dunbardc6d5742010-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700592 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
593
594 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000595
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000596 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbare59d8582010-09-16 20:42:06 +0000597 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000598
Rafael Espindolab48280b2012-07-31 02:44:24 +0000599 Class classify(QualType Ty) const;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700600 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Stephen Hines651f13c2014-04-23 16:59:28 -0700601 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
602 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
603
604 /// \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;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000611
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000612public:
613
Stephen Hines651f13c2014-04-23 16:59:28 -0700614 void computeInfo(CGFunctionInfo &FI) const override;
615 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
616 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000617
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000618 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindolab48280b2012-07-31 02:44:24 +0000619 unsigned r)
Eli Friedmanc3e0fb42011-07-08 23:31:17 +0000620 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000621 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000622};
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000623
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000624class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
625public:
Eli Friedman55fc7e22012-01-25 22:46:34 +0000626 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier1f1df1f2013-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 Davis74f72932010-02-13 15:54:06 +0000629
John McCallb8b52972013-06-18 02:46:29 +0000630 static bool isStructReturnInRegABI(
631 const llvm::Triple &Triple, const CodeGenOptions &Opts);
632
Charles Davis74f72932010-02-13 15:54:06 +0000633 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -0700634 CodeGen::CodeGenModule &CGM) const override;
John McCall6374c332010-03-06 00:35:14 +0000635
Stephen Hines651f13c2014-04-23 16:59:28 -0700636 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall6374c332010-03-06 00:35:14 +0000637 // Darwin uses different dwarf register numbers for EH.
John McCall64aa4b32013-04-16 22:48:15 +0000638 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCall6374c332010-03-06 00:35:14 +0000639 return 4;
640 }
641
642 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -0700643 llvm::Value *Address) const override;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000644
Jay Foadef6de3d2011-07-11 09:56:20 +0000645 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000646 StringRef Constraint,
Stephen Hines651f13c2014-04-23 16:59:28 -0700647 llvm::Type* Ty) const override {
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000648 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
649 }
650
Stephen Hines176edba2014-12-01 14:53:08 -0800651 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
Stephen Hines651f13c2014-04-23 16:59:28 -0700659 llvm::Constant *
660 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb914e872013-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
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000668};
669
670}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000671
Stephen Hines176edba2014-12-01 14:53:08 -0800672/// Rewrite input constraint references after adding some output constraints.
673/// In the case where there is one output and one input and we add one output,
674/// we need to replace all operand references greater than or equal to 1:
675/// mov $0, $1
676/// mov eax, $1
677/// The result will be:
678/// mov $0, $2
679/// mov eax, $2
680static void rewriteInputConstraintReferences(unsigned FirstIn,
681 unsigned NumNewOuts,
682 std::string &AsmString) {
683 std::string Buf;
684 llvm::raw_string_ostream OS(Buf);
685 size_t Pos = 0;
686 while (Pos < AsmString.size()) {
687 size_t DollarStart = AsmString.find('$', Pos);
688 if (DollarStart == std::string::npos)
689 DollarStart = AsmString.size();
690 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
691 if (DollarEnd == std::string::npos)
692 DollarEnd = AsmString.size();
693 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
694 Pos = DollarEnd;
695 size_t NumDollars = DollarEnd - DollarStart;
696 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
697 // We have an operand reference.
698 size_t DigitStart = Pos;
699 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
700 if (DigitEnd == std::string::npos)
701 DigitEnd = AsmString.size();
702 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
703 unsigned OperandIndex;
704 if (!OperandStr.getAsInteger(10, OperandIndex)) {
705 if (OperandIndex >= FirstIn)
706 OperandIndex += NumNewOuts;
707 OS << OperandIndex;
708 } else {
709 OS << OperandStr;
710 }
711 Pos = DigitEnd;
712 }
713 }
714 AsmString = std::move(OS.str());
715}
716
717/// Add output constraints for EAX:EDX because they are return registers.
718void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
719 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
720 std::vector<llvm::Type *> &ResultRegTypes,
721 std::vector<llvm::Type *> &ResultTruncRegTypes,
722 std::vector<LValue> &ResultRegDests, std::string &AsmString,
723 unsigned NumOutputs) const {
724 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
725
726 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
727 // larger.
728 if (!Constraints.empty())
729 Constraints += ',';
730 if (RetWidth <= 32) {
731 Constraints += "={eax}";
732 ResultRegTypes.push_back(CGF.Int32Ty);
733 } else {
734 // Use the 'A' constraint for EAX:EDX.
735 Constraints += "=A";
736 ResultRegTypes.push_back(CGF.Int64Ty);
737 }
738
739 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
740 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
741 ResultTruncRegTypes.push_back(CoerceTy);
742
743 // Coerce the integer by bitcasting the return slot pointer.
744 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
745 CoerceTy->getPointerTo()));
746 ResultRegDests.push_back(ReturnSlot);
747
748 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
749}
750
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000751/// shouldReturnTypeInRegister - Determine if the given type should be
752/// passed in a register (for the Darwin ABI).
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700753bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
754 ASTContext &Context) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000755 uint64_t Size = Context.getTypeSize(Ty);
756
757 // Type must be register sized.
758 if (!isRegisterSize(Size))
759 return false;
760
761 if (Ty->isVectorType()) {
762 // 64- and 128- bit vectors inside structures are not returned in
763 // registers.
764 if (Size == 64 || Size == 128)
765 return false;
766
767 return true;
768 }
769
Daniel Dunbar77115232010-05-15 00:00:30 +0000770 // If this is a builtin, pointer, enum, complex type, member pointer, or
771 // member function pointer it is ok.
Daniel Dunbara1842d32010-05-14 03:40:53 +0000772 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbar55e59e12009-09-24 05:12:36 +0000773 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar77115232010-05-15 00:00:30 +0000774 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000775 return true;
776
777 // Arrays are treated like records.
778 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700779 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000780
781 // Otherwise, it must be a record type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000782 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000783 if (!RT) return false;
784
Anders Carlssona8874232010-01-27 03:25:19 +0000785 // FIXME: Traverse bases here too.
786
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000787 // Structure types are passed in register if all fields would be
788 // passed in a register.
Stephen Hines651f13c2014-04-23 16:59:28 -0700789 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000790 // Empty fields are ignored.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000791 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000792 continue;
793
794 // Check fields recursively.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700795 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000796 return false;
797 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000798 return true;
799}
800
Stephen Hines651f13c2014-04-23 16:59:28 -0700801ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
802 // If the return value is indirect, then the hidden argument is consuming one
803 // integer register.
804 if (State.FreeRegs) {
805 --State.FreeRegs;
806 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
807 }
808 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
809}
810
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700811ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000812 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000813 return ABIArgInfo::getIgnore();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000814
Stephen Hines176edba2014-12-01 14:53:08 -0800815 const Type *Base = nullptr;
816 uint64_t NumElts = 0;
817 if (State.CC == llvm::CallingConv::X86_VectorCall &&
818 isHomogeneousAggregate(RetTy, Base, NumElts)) {
819 // The LLVM struct type for such an aggregate should lower properly.
820 return ABIArgInfo::getDirect();
821 }
822
Chris Lattnera3c109b2010-07-29 02:16:43 +0000823 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000824 // On Darwin, some vectors are returned in registers.
David Chisnall1e4249c2009-08-17 23:08:21 +0000825 if (IsDarwinVectorABI) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000826 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000827
828 // 128-bit vectors are a special case; they are returned in
829 // registers and we need to make sure to pick a type the LLVM
830 // backend will like.
831 if (Size == 128)
Chris Lattner800588f2010-07-29 06:26:06 +0000832 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattnera3c109b2010-07-29 02:16:43 +0000833 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000834
835 // Always return in register if it fits in a general purpose
836 // register, or if it is 64 bits and has a single element.
837 if ((Size == 8 || Size == 16 || Size == 32) ||
838 (Size == 64 && VT->getNumElements() == 1))
Chris Lattner800588f2010-07-29 06:26:06 +0000839 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +0000840 Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000841
Stephen Hines651f13c2014-04-23 16:59:28 -0700842 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000843 }
844
845 return ABIArgInfo::getDirect();
Chris Lattnera3c109b2010-07-29 02:16:43 +0000846 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000847
John McCalld608cdb2010-08-22 10:59:02 +0000848 if (isAggregateTypeForABI(RetTy)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000849 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson40092972009-10-20 22:07:59 +0000850 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000851 if (RT->getDecl()->hasFlexibleArrayMember())
Stephen Hines651f13c2014-04-23 16:59:28 -0700852 return getIndirectReturnResult(State);
Anders Carlsson40092972009-10-20 22:07:59 +0000853 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000854
David Chisnall1e4249c2009-08-17 23:08:21 +0000855 // If specified, structs and unions are always indirect.
856 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Stephen Hines651f13c2014-04-23 16:59:28 -0700857 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000858
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000859 // Small structures which are register sized are generally returned
860 // in a register.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700861 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000862 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000863
864 // As a special-case, if the struct is a "single-element" struct, and
865 // the field is of type "float" or "double", return it in a
Eli Friedman55fc7e22012-01-25 22:46:34 +0000866 // floating-point register. (MSVC does not apply this special case.)
867 // We apply a similar transformation for pointer types to improve the
868 // quality of the generated IR.
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000869 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000870 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedman55fc7e22012-01-25 22:46:34 +0000871 || SeltTy->hasPointerRepresentation())
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000872 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
873
874 // FIXME: We should be able to narrow this integer in cases with dead
875 // padding.
Chris Lattner800588f2010-07-29 06:26:06 +0000876 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000877 }
878
Stephen Hines651f13c2014-04-23 16:59:28 -0700879 return getIndirectReturnResult(State);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000880 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000881
Chris Lattnera3c109b2010-07-29 02:16:43 +0000882 // Treat an enum type as its underlying type.
883 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
884 RetTy = EnumTy->getDecl()->getIntegerType();
885
886 return (RetTy->isPromotableIntegerType() ?
887 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000888}
889
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000890static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
891 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
892}
893
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000894static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
895 const RecordType *RT = Ty->getAs<RecordType>();
896 if (!RT)
897 return 0;
898 const RecordDecl *RD = RT->getDecl();
899
900 // If this is a C++ record, check the bases first.
901 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -0700902 for (const auto &I : CXXRD->bases())
903 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000904 return false;
905
Stephen Hines651f13c2014-04-23 16:59:28 -0700906 for (const auto *i : RD->fields()) {
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000907 QualType FT = i->getType();
908
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000909 if (isSSEVectorType(Context, FT))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000910 return true;
911
912 if (isRecordWithSSEVectorType(Context, FT))
913 return true;
914 }
915
916 return false;
917}
918
Daniel Dunbare59d8582010-09-16 20:42:06 +0000919unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
920 unsigned Align) const {
921 // Otherwise, if the alignment is less than or equal to the minimum ABI
922 // alignment, just use the default; the backend will handle this.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000923 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbare59d8582010-09-16 20:42:06 +0000924 return 0; // Use default alignment.
925
926 // On non-Darwin, the stack type alignment is always 4.
927 if (!IsDarwinVectorABI) {
928 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000929 return MinABIStackAlignInBytes;
Daniel Dunbare59d8582010-09-16 20:42:06 +0000930 }
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000931
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000932 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000933 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
934 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000935 return 16;
936
937 return MinABIStackAlignInBytes;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000938}
939
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000940ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Stephen Hines651f13c2014-04-23 16:59:28 -0700941 CCState &State) const {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000942 if (!ByVal) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700943 if (State.FreeRegs) {
944 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000945 return ABIArgInfo::getIndirectInReg(0, false);
946 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000947 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000948 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000949
Daniel Dunbare59d8582010-09-16 20:42:06 +0000950 // Compute the byval alignment.
951 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
952 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
953 if (StackAlign == 0)
Stephen Hines651f13c2014-04-23 16:59:28 -0700954 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbare59d8582010-09-16 20:42:06 +0000955
956 // If the stack alignment is less than the type alignment, realign the
957 // argument.
Stephen Hines651f13c2014-04-23 16:59:28 -0700958 bool Realign = TypeAlign > StackAlign;
959 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000960}
961
Rafael Espindolab48280b2012-07-31 02:44:24 +0000962X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
963 const Type *T = isSingleElementStruct(Ty, getContext());
964 if (!T)
965 T = Ty.getTypePtr();
966
967 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
968 BuiltinType::Kind K = BT->getKind();
969 if (K == BuiltinType::Float || K == BuiltinType::Double)
970 return Float;
971 }
972 return Integer;
973}
974
Stephen Hines651f13c2014-04-23 16:59:28 -0700975bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
976 bool &NeedsPadding) const {
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000977 NeedsPadding = false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000978 Class C = classify(Ty);
979 if (C == Float)
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000980 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000981
Rafael Espindolab6932692012-10-24 01:58:58 +0000982 unsigned Size = getContext().getTypeSize(Ty);
983 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindola5f14fcb2012-10-23 02:04:01 +0000984
985 if (SizeInRegs == 0)
986 return false;
987
Stephen Hines651f13c2014-04-23 16:59:28 -0700988 if (SizeInRegs > State.FreeRegs) {
989 State.FreeRegs = 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000990 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000991 }
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000992
Stephen Hines651f13c2014-04-23 16:59:28 -0700993 State.FreeRegs -= SizeInRegs;
Rafael Espindolab6932692012-10-24 01:58:58 +0000994
Stephen Hines176edba2014-12-01 14:53:08 -0800995 if (State.CC == llvm::CallingConv::X86_FastCall ||
996 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindolab6932692012-10-24 01:58:58 +0000997 if (Size > 32)
998 return false;
999
1000 if (Ty->isIntegralOrEnumerationType())
1001 return true;
1002
1003 if (Ty->isPointerType())
1004 return true;
1005
1006 if (Ty->isReferenceType())
1007 return true;
1008
Stephen Hines651f13c2014-04-23 16:59:28 -07001009 if (State.FreeRegs)
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001010 NeedsPadding = true;
1011
Rafael Espindolab6932692012-10-24 01:58:58 +00001012 return false;
1013 }
1014
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001015 return true;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001016}
1017
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001018ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07001019 CCState &State) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001020 // FIXME: Set alignment on indirect arguments.
Daniel Dunbardc6d5742010-04-21 19:10:51 +00001021
Stephen Hines176edba2014-12-01 14:53:08 -08001022 Ty = useFirstFieldIfTransparentUnion(Ty);
1023
1024 // Check with the C++ ABI first.
1025 const RecordType *RT = Ty->getAs<RecordType>();
1026 if (RT) {
1027 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1028 if (RAA == CGCXXABI::RAA_Indirect) {
1029 return getIndirectResult(Ty, false, State);
1030 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1031 // The field index doesn't matter, we'll fix it up later.
1032 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1033 }
1034 }
1035
1036 // vectorcall adds the concept of a homogenous vector aggregate, similar
1037 // to other targets.
1038 const Type *Base = nullptr;
1039 uint64_t NumElts = 0;
1040 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1041 isHomogeneousAggregate(Ty, Base, NumElts)) {
1042 if (State.FreeSSERegs >= NumElts) {
1043 State.FreeSSERegs -= NumElts;
1044 if (Ty->isBuiltinType() || Ty->isVectorType())
1045 return ABIArgInfo::getDirect();
1046 return ABIArgInfo::getExpand();
1047 }
1048 return getIndirectResult(Ty, /*ByVal=*/false, State);
1049 }
1050
1051 if (isAggregateTypeForABI(Ty)) {
1052 if (RT) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001053 // Structs are always byval on win32, regardless of what they contain.
1054 if (IsWin32StructABI)
1055 return getIndirectResult(Ty, true, State);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001056
1057 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001058 if (RT->getDecl()->hasFlexibleArrayMember())
Stephen Hines651f13c2014-04-23 16:59:28 -07001059 return getIndirectResult(Ty, true, State);
Anders Carlssona8874232010-01-27 03:25:19 +00001060 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001061
Eli Friedman5a4d3522011-11-18 00:28:11 +00001062 // Ignore empty structs/unions.
Eli Friedman5a1ac892011-11-18 04:01:36 +00001063 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001064 return ABIArgInfo::getIgnore();
1065
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001066 llvm::LLVMContext &LLVMContext = getVMContext();
1067 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1068 bool NeedsPadding;
Stephen Hines651f13c2014-04-23 16:59:28 -07001069 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001070 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperb9bad792013-07-08 04:47:18 +00001071 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001072 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1073 return ABIArgInfo::getDirectInReg(Result);
1074 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001075 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001076
Daniel Dunbar53012f42009-11-09 01:33:53 +00001077 // Expand small (<= 128-bit) record types when we know that the stack layout
1078 // of those arguments will match the struct. This is important because the
1079 // LLVM backend isn't smart enough to remove byval, which inhibits many
1080 // optimizations.
Chris Lattnera3c109b2010-07-29 02:16:43 +00001081 if (getContext().getTypeSize(Ty) <= 4*32 &&
1082 canExpandIndirectArgument(Ty, getContext()))
Stephen Hines651f13c2014-04-23 16:59:28 -07001083 return ABIArgInfo::getExpandWithPadding(
Stephen Hines176edba2014-12-01 14:53:08 -08001084 State.CC == llvm::CallingConv::X86_FastCall ||
1085 State.CC == llvm::CallingConv::X86_VectorCall,
1086 PaddingType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001087
Stephen Hines651f13c2014-04-23 16:59:28 -07001088 return getIndirectResult(Ty, true, State);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001089 }
1090
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001091 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner7b733502010-08-26 20:08:43 +00001092 // On Darwin, some vectors are passed in memory, we handle this by passing
1093 // it as an i8/i16/i32/i64.
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001094 if (IsDarwinVectorABI) {
1095 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001096 if ((Size == 8 || Size == 16 || Size == 32) ||
1097 (Size == 64 && VT->getNumElements() == 1))
1098 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1099 Size));
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001100 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00001101
Chad Rosier1f1df1f2013-03-25 21:00:27 +00001102 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1103 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001104
Chris Lattnerbbae8b42010-08-26 20:05:13 +00001105 return ABIArgInfo::getDirect();
1106 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001107
1108
Chris Lattnera3c109b2010-07-29 02:16:43 +00001109 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1110 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001111
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +00001112 bool NeedsPadding;
Stephen Hines651f13c2014-04-23 16:59:28 -07001113 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola0b4cc952012-10-19 05:04:37 +00001114
1115 if (Ty->isPromotableIntegerType()) {
1116 if (InReg)
1117 return ABIArgInfo::getExtendInReg();
1118 return ABIArgInfo::getExtend();
1119 }
1120 if (InReg)
1121 return ABIArgInfo::getDirectInReg();
1122 return ABIArgInfo::getDirect();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001123}
1124
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +00001125void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07001126 CCState State(FI.getCallingConvention());
1127 if (State.CC == llvm::CallingConv::X86_FastCall)
1128 State.FreeRegs = 2;
Stephen Hines176edba2014-12-01 14:53:08 -08001129 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1130 State.FreeRegs = 2;
1131 State.FreeSSERegs = 6;
1132 } else if (FI.getHasRegParm())
Stephen Hines651f13c2014-04-23 16:59:28 -07001133 State.FreeRegs = FI.getRegParm();
Rafael Espindolab6932692012-10-24 01:58:58 +00001134 else
Stephen Hines651f13c2014-04-23 16:59:28 -07001135 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindolab48280b2012-07-31 02:44:24 +00001136
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001137 if (!getCXXABI().classifyReturnType(FI)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001138 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001139 } else if (FI.getReturnInfo().isIndirect()) {
1140 // The C++ ABI is not aware of register usage, so we have to check if the
1141 // return value was sret and put it in a register ourselves if appropriate.
1142 if (State.FreeRegs) {
1143 --State.FreeRegs; // The sret parameter consumes a register.
1144 FI.getReturnInfo().setInReg(true);
1145 }
1146 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001147
1148 bool UsedInAlloca = false;
1149 for (auto &I : FI.arguments()) {
1150 I.info = classifyArgumentType(I.type, State);
1151 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Rafael Espindolab48280b2012-07-31 02:44:24 +00001152 }
1153
Stephen Hines651f13c2014-04-23 16:59:28 -07001154 // If we needed to use inalloca for any argument, do a second pass and rewrite
1155 // all the memory arguments to use inalloca.
1156 if (UsedInAlloca)
1157 rewriteWithInAlloca(FI);
1158}
1159
1160void
1161X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1162 unsigned &StackOffset,
1163 ABIArgInfo &Info, QualType Type) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001164 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1165 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1166 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1167 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1168
Stephen Hines651f13c2014-04-23 16:59:28 -07001169 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1170 // byte aligned.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001171 if (StackOffset % 4U) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001172 unsigned OldOffset = StackOffset;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001173 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Stephen Hines651f13c2014-04-23 16:59:28 -07001174 unsigned NumBytes = StackOffset - OldOffset;
1175 assert(NumBytes);
1176 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1177 Ty = llvm::ArrayType::get(Ty, NumBytes);
1178 FrameFields.push_back(Ty);
1179 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001180}
1181
Stephen Hines176edba2014-12-01 14:53:08 -08001182static bool isArgInAlloca(const ABIArgInfo &Info) {
1183 // Leave ignored and inreg arguments alone.
1184 switch (Info.getKind()) {
1185 case ABIArgInfo::InAlloca:
1186 return true;
1187 case ABIArgInfo::Indirect:
1188 assert(Info.getIndirectByVal());
1189 return true;
1190 case ABIArgInfo::Ignore:
1191 return false;
1192 case ABIArgInfo::Direct:
1193 case ABIArgInfo::Extend:
1194 case ABIArgInfo::Expand:
1195 if (Info.getInReg())
1196 return false;
1197 return true;
1198 }
1199 llvm_unreachable("invalid enum");
1200}
1201
Stephen Hines651f13c2014-04-23 16:59:28 -07001202void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1203 assert(IsWin32StructABI && "inalloca only supported on win32");
1204
1205 // Build a packed struct type for all of the arguments in memory.
1206 SmallVector<llvm::Type *, 6> FrameFields;
1207
1208 unsigned StackOffset = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08001209 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1210
1211 // Put 'this' into the struct before 'sret', if necessary.
1212 bool IsThisCall =
1213 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1214 ABIArgInfo &Ret = FI.getReturnInfo();
1215 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1216 isArgInAlloca(I->info)) {
1217 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1218 ++I;
1219 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001220
1221 // Put the sret parameter into the inalloca struct if it's in memory.
Stephen Hines651f13c2014-04-23 16:59:28 -07001222 if (Ret.isIndirect() && !Ret.getInReg()) {
1223 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1224 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1225 // On Windows, the hidden sret parameter is always returned in eax.
1226 Ret.setInAllocaSRet(IsWin32StructABI);
1227 }
1228
1229 // Skip the 'this' parameter in ecx.
Stephen Hines176edba2014-12-01 14:53:08 -08001230 if (IsThisCall)
Stephen Hines651f13c2014-04-23 16:59:28 -07001231 ++I;
1232
1233 // Put arguments passed in memory into the struct.
1234 for (; I != E; ++I) {
Stephen Hines176edba2014-12-01 14:53:08 -08001235 if (isArgInAlloca(I->info))
1236 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Stephen Hines651f13c2014-04-23 16:59:28 -07001237 }
1238
1239 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1240 /*isPacked=*/true));
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +00001241}
1242
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001243llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1244 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001245 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001246
1247 CGBuilderTy &Builder = CGF.Builder;
1248 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1249 "ap");
1250 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman7b1fb812011-11-18 02:12:09 +00001251
1252 // Compute if the address needs to be aligned
1253 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1254 Align = getTypeStackAlignInBytes(Ty, Align);
1255 Align = std::max(Align, 4U);
1256 if (Align > 4) {
1257 // addr = (addr + align - 1) & -align;
1258 llvm::Value *Offset =
1259 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1260 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1261 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1262 CGF.Int32Ty);
1263 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1264 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1265 Addr->getType(),
1266 "ap.cur.aligned");
1267 }
1268
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001269 llvm::Type *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001270 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001271 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1272
1273 uint64_t Offset =
Eli Friedman7b1fb812011-11-18 02:12:09 +00001274 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001275 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00001276 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001277 "ap.next");
1278 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1279
1280 return AddrTyped;
1281}
1282
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001283bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1284 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1285 assert(Triple.getArch() == llvm::Triple::x86);
1286
1287 switch (Opts.getStructReturnConvention()) {
1288 case CodeGenOptions::SRCK_Default:
1289 break;
1290 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1291 return false;
1292 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1293 return true;
1294 }
1295
1296 if (Triple.isOSDarwin())
1297 return true;
1298
1299 switch (Triple.getOS()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001300 case llvm::Triple::DragonFly:
1301 case llvm::Triple::FreeBSD:
1302 case llvm::Triple::OpenBSD:
1303 case llvm::Triple::Bitrig:
1304 return true;
1305 case llvm::Triple::Win32:
1306 switch (Triple.getEnvironment()) {
1307 case llvm::Triple::UnknownEnvironment:
1308 case llvm::Triple::Cygnus:
1309 case llvm::Triple::GNU:
1310 case llvm::Triple::MSVC:
1311 return true;
1312 default:
1313 return false;
1314 }
1315 default:
1316 return false;
1317 }
1318}
1319
Charles Davis74f72932010-02-13 15:54:06 +00001320void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1321 llvm::GlobalValue *GV,
1322 CodeGen::CodeGenModule &CGM) const {
1323 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1324 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1325 // Get the LLVM function.
1326 llvm::Function *Fn = cast<llvm::Function>(GV);
1327
1328 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendling0d583392012-10-15 20:36:26 +00001329 llvm::AttrBuilder B;
Bill Wendlinge91e9ec2012-10-14 03:28:14 +00001330 B.addStackAlignmentAttr(16);
Bill Wendling909b6de2013-01-23 00:21:06 +00001331 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1332 llvm::AttributeSet::get(CGM.getLLVMContext(),
1333 llvm::AttributeSet::FunctionIndex,
1334 B));
Charles Davis74f72932010-02-13 15:54:06 +00001335 }
1336 }
1337}
1338
John McCall6374c332010-03-06 00:35:14 +00001339bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1340 CodeGen::CodeGenFunction &CGF,
1341 llvm::Value *Address) const {
1342 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCall6374c332010-03-06 00:35:14 +00001343
Chris Lattner8b418682012-02-07 00:39:47 +00001344 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001345
John McCall6374c332010-03-06 00:35:14 +00001346 // 0-7 are the eight integer registers; the order is different
1347 // on Darwin (for EH), but the range is the same.
1348 // 8 is %eip.
John McCallaeeb7012010-05-27 06:19:26 +00001349 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCall6374c332010-03-06 00:35:14 +00001350
John McCall64aa4b32013-04-16 22:48:15 +00001351 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCall6374c332010-03-06 00:35:14 +00001352 // 12-16 are st(0..4). Not sure why we stop at 4.
1353 // These have size 16, which is sizeof(long double) on
1354 // platforms with 8-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001355 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCallaeeb7012010-05-27 06:19:26 +00001356 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001357
John McCall6374c332010-03-06 00:35:14 +00001358 } else {
1359 // 9 is %eflags, which doesn't get a size on Darwin for some
1360 // reason.
1361 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1362
1363 // 11-16 are st(0..5). Not sure why we stop at 5.
1364 // These have size 12, which is sizeof(long double) on
1365 // platforms with 4-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001366 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCallaeeb7012010-05-27 06:19:26 +00001367 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1368 }
John McCall6374c332010-03-06 00:35:14 +00001369
1370 return false;
1371}
1372
Chris Lattnerdce5ad02010-06-28 20:05:43 +00001373//===----------------------------------------------------------------------===//
1374// X86-64 ABI Implementation
1375//===----------------------------------------------------------------------===//
1376
1377
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001378namespace {
1379/// X86_64ABIInfo - The X86_64 ABI information.
1380class X86_64ABIInfo : public ABIInfo {
1381 enum Class {
1382 Integer = 0,
1383 SSE,
1384 SSEUp,
1385 X87,
1386 X87Up,
1387 ComplexX87,
1388 NoClass,
1389 Memory
1390 };
1391
1392 /// merge - Implement the X86_64 ABI merging algorithm.
1393 ///
1394 /// Merge an accumulating classification \arg Accum with a field
1395 /// classification \arg Field.
1396 ///
1397 /// \param Accum - The accumulating classification. This should
1398 /// always be either NoClass or the result of a previous merge
1399 /// call. In addition, this should never be Memory (the caller
1400 /// should just return Memory for the aggregate).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001401 static Class merge(Class Accum, Class Field);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001402
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001403 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1404 ///
1405 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1406 /// final MEMORY or SSE classes when necessary.
1407 ///
1408 /// \param AggregateSize - The size of the current aggregate in
1409 /// the classification process.
1410 ///
1411 /// \param Lo - The classification for the parts of the type
1412 /// residing in the low word of the containing object.
1413 ///
1414 /// \param Hi - The classification for the parts of the type
1415 /// residing in the higher words of the containing object.
1416 ///
1417 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1418
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001419 /// classify - Determine the x86_64 register classes in which the
1420 /// given type T should be passed.
1421 ///
1422 /// \param Lo - The classification for the parts of the type
1423 /// residing in the low word of the containing object.
1424 ///
1425 /// \param Hi - The classification for the parts of the type
1426 /// residing in the high word of the containing object.
1427 ///
1428 /// \param OffsetBase - The bit offset of this type in the
1429 /// containing object. Some parameters are classified different
1430 /// depending on whether they straddle an eightbyte boundary.
1431 ///
Eli Friedman7a1b5862013-06-12 00:13:45 +00001432 /// \param isNamedArg - Whether the argument in question is a "named"
1433 /// argument, as used in AMD64-ABI 3.5.7.
1434 ///
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001435 /// If a word is unused its result will be NoClass; if a type should
1436 /// be passed in Memory then at least the classification of \arg Lo
1437 /// will be Memory.
1438 ///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001439 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001440 ///
1441 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1442 /// also be ComplexX87.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001443 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1444 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001445
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001446 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001447 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1448 unsigned IROffset, QualType SourceTy,
1449 unsigned SourceOffset) const;
1450 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1451 unsigned IROffset, QualType SourceTy,
1452 unsigned SourceOffset) const;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001453
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001454 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001455 /// such that the argument will be returned in memory.
Chris Lattner9c254f02010-06-29 06:01:59 +00001456 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001457
1458 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001459 /// such that the argument will be passed in memory.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001460 ///
1461 /// \param freeIntRegs - The number of free integer registers remaining
1462 /// available.
1463 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001464
Chris Lattnera3c109b2010-07-29 02:16:43 +00001465 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001466
Bill Wendlingbb465d72010-10-18 03:41:31 +00001467 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbaredfac032012-03-10 01:03:58 +00001468 unsigned freeIntRegs,
Bill Wendlingbb465d72010-10-18 03:41:31 +00001469 unsigned &neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001470 unsigned &neededSSE,
1471 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001472
Eli Friedmanee1ad992011-12-02 00:11:43 +00001473 bool IsIllegalVectorType(QualType Ty) const;
1474
John McCall67a57732011-04-21 01:20:55 +00001475 /// The 0.98 ABI revision clarified a lot of ambiguities,
1476 /// unfortunately in ways that were not always consistent with
1477 /// certain previous compilers. In particular, platforms which
1478 /// required strict binary compatibility with older versions of GCC
1479 /// may need to exempt themselves.
1480 bool honorsRevision0_98() const {
John McCall64aa4b32013-04-16 22:48:15 +00001481 return !getTarget().getTriple().isOSDarwin();
John McCall67a57732011-04-21 01:20:55 +00001482 }
1483
Eli Friedmanee1ad992011-12-02 00:11:43 +00001484 bool HasAVX;
Derek Schuffbabaf312012-10-11 15:52:22 +00001485 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1486 // 64-bit hardware.
1487 bool Has64BitPointers;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001488
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001489public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001490 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffbabaf312012-10-11 15:52:22 +00001491 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff90da80c2012-10-11 18:21:13 +00001492 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001493 }
Chris Lattner9c254f02010-06-29 06:01:59 +00001494
John McCallde5d3c72012-02-17 03:33:10 +00001495 bool isPassedUsingAVXType(QualType type) const {
1496 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00001497 // The freeIntRegs argument doesn't matter here.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001498 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1499 /*isNamedArg*/true);
John McCallde5d3c72012-02-17 03:33:10 +00001500 if (info.isDirect()) {
1501 llvm::Type *ty = info.getCoerceToType();
1502 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1503 return (vectorTy->getBitWidth() > 128);
1504 }
1505 return false;
1506 }
1507
Stephen Hines651f13c2014-04-23 16:59:28 -07001508 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001509
Stephen Hines651f13c2014-04-23 16:59:28 -07001510 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1511 CodeGenFunction &CGF) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001512};
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001513
Chris Lattnerf13721d2010-08-31 16:44:54 +00001514/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001515class WinX86_64ABIInfo : public ABIInfo {
1516
Stephen Hines176edba2014-12-01 14:53:08 -08001517 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1518 bool IsReturnType) const;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001519
Chris Lattnerf13721d2010-08-31 16:44:54 +00001520public:
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001521 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1522
Stephen Hines651f13c2014-04-23 16:59:28 -07001523 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001524
Stephen Hines651f13c2014-04-23 16:59:28 -07001525 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1526 CodeGenFunction &CGF) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08001527
1528 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1529 // FIXME: Assumes vectorcall is in use.
1530 return isX86VectorTypeForVectorCall(getContext(), Ty);
1531 }
1532
1533 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1534 uint64_t NumMembers) const override {
1535 // FIXME: Assumes vectorcall is in use.
1536 return isX86VectorCallAggregateSmallEnough(NumMembers);
1537 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001538};
1539
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001540class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines176edba2014-12-01 14:53:08 -08001541 bool HasAVX;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001542public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001543 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Stephen Hines176edba2014-12-01 14:53:08 -08001544 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCall6374c332010-03-06 00:35:14 +00001545
John McCallde5d3c72012-02-17 03:33:10 +00001546 const X86_64ABIInfo &getABIInfo() const {
1547 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1548 }
1549
Stephen Hines651f13c2014-04-23 16:59:28 -07001550 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall6374c332010-03-06 00:35:14 +00001551 return 7;
1552 }
1553
1554 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07001555 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00001556 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001557
John McCallaeeb7012010-05-27 06:19:26 +00001558 // 0-15 are the 16 integer registers.
1559 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001560 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCall6374c332010-03-06 00:35:14 +00001561 return false;
1562 }
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001563
Jay Foadef6de3d2011-07-11 09:56:20 +00001564 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001565 StringRef Constraint,
Stephen Hines651f13c2014-04-23 16:59:28 -07001566 llvm::Type* Ty) const override {
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001567 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1568 }
1569
John McCallde5d3c72012-02-17 03:33:10 +00001570 bool isNoProtoCallVariadic(const CallArgList &args,
Stephen Hines651f13c2014-04-23 16:59:28 -07001571 const FunctionNoProtoType *fnType) const override {
John McCall01f151e2011-09-21 08:08:30 +00001572 // The default CC on x86-64 sets %al to the number of SSA
1573 // registers used, and GCC sets this when calling an unprototyped
Eli Friedman3ed79032011-12-01 04:53:19 +00001574 // function, so we override the default behavior. However, don't do
Eli Friedman68805fe2011-12-06 03:08:26 +00001575 // that when AVX types are involved: the ABI explicitly states it is
1576 // undefined, and it doesn't work in practice because of how the ABI
1577 // defines varargs anyway.
Reid Kleckneref072032013-08-27 23:08:25 +00001578 if (fnType->getCallConv() == CC_C) {
Eli Friedman3ed79032011-12-01 04:53:19 +00001579 bool HasAVXType = false;
John McCallde5d3c72012-02-17 03:33:10 +00001580 for (CallArgList::const_iterator
1581 it = args.begin(), ie = args.end(); it != ie; ++it) {
1582 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1583 HasAVXType = true;
1584 break;
Eli Friedman3ed79032011-12-01 04:53:19 +00001585 }
1586 }
John McCallde5d3c72012-02-17 03:33:10 +00001587
Eli Friedman3ed79032011-12-01 04:53:19 +00001588 if (!HasAVXType)
1589 return true;
1590 }
John McCall01f151e2011-09-21 08:08:30 +00001591
John McCallde5d3c72012-02-17 03:33:10 +00001592 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCall01f151e2011-09-21 08:08:30 +00001593 }
1594
Stephen Hines651f13c2014-04-23 16:59:28 -07001595 llvm::Constant *
1596 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb914e872013-10-20 21:29:19 +00001597 unsigned Sig = (0xeb << 0) | // jmp rel8
1598 (0x0a << 8) | // .+0x0c
1599 ('F' << 16) |
1600 ('T' << 24);
1601 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1602 }
1603
Stephen Hines176edba2014-12-01 14:53:08 -08001604 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1605 return HasAVX ? 32 : 16;
1606 }
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001607};
1608
Aaron Ballman89735b92013-05-24 15:06:56 +00001609static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1610 // If the argument does not end in .lib, automatically add the suffix. This
1611 // matches the behavior of MSVC.
1612 std::string ArgStr = Lib;
Rui Ueyama723cead2013-10-31 19:12:53 +00001613 if (!Lib.endswith_lower(".lib"))
Aaron Ballman89735b92013-05-24 15:06:56 +00001614 ArgStr += ".lib";
Aaron Ballman89735b92013-05-24 15:06:56 +00001615 return ArgStr;
1616}
1617
Reid Kleckner3190ca92013-05-08 13:44:39 +00001618class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1619public:
John McCallb8b52972013-06-18 02:46:29 +00001620 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1621 bool d, bool p, bool w, unsigned RegParms)
1622 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Kleckner3190ca92013-05-08 13:44:39 +00001623
1624 void getDependentLibraryOption(llvm::StringRef Lib,
Stephen Hines651f13c2014-04-23 16:59:28 -07001625 llvm::SmallString<24> &Opt) const override {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001626 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001627 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001628 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001629
1630 void getDetectMismatchOption(llvm::StringRef Name,
1631 llvm::StringRef Value,
Stephen Hines651f13c2014-04-23 16:59:28 -07001632 llvm::SmallString<32> &Opt) const override {
Eli Friedman572ac322013-06-07 22:42:22 +00001633 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001634 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001635};
1636
Chris Lattnerf13721d2010-08-31 16:44:54 +00001637class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines176edba2014-12-01 14:53:08 -08001638 bool HasAVX;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001639public:
Stephen Hines176edba2014-12-01 14:53:08 -08001640 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1641 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattnerf13721d2010-08-31 16:44:54 +00001642
Stephen Hines651f13c2014-04-23 16:59:28 -07001643 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattnerf13721d2010-08-31 16:44:54 +00001644 return 7;
1645 }
1646
1647 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07001648 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00001649 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001650
Chris Lattnerf13721d2010-08-31 16:44:54 +00001651 // 0-15 are the 16 integer registers.
1652 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001653 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattnerf13721d2010-08-31 16:44:54 +00001654 return false;
1655 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001656
1657 void getDependentLibraryOption(llvm::StringRef Lib,
Stephen Hines651f13c2014-04-23 16:59:28 -07001658 llvm::SmallString<24> &Opt) const override {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001659 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001660 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001661 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001662
1663 void getDetectMismatchOption(llvm::StringRef Name,
1664 llvm::StringRef Value,
Stephen Hines651f13c2014-04-23 16:59:28 -07001665 llvm::SmallString<32> &Opt) const override {
Eli Friedman572ac322013-06-07 22:42:22 +00001666 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001667 }
Stephen Hines176edba2014-12-01 14:53:08 -08001668
1669 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1670 return HasAVX ? 32 : 16;
1671 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001672};
1673
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001674}
1675
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001676void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1677 Class &Hi) const {
1678 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1679 //
1680 // (a) If one of the classes is Memory, the whole argument is passed in
1681 // memory.
1682 //
1683 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1684 // memory.
1685 //
1686 // (c) If the size of the aggregate exceeds two eightbytes and the first
1687 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1688 // argument is passed in memory. NOTE: This is necessary to keep the
1689 // ABI working for processors that don't support the __m256 type.
1690 //
1691 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1692 //
1693 // Some of these are enforced by the merging logic. Others can arise
1694 // only with unions; for example:
1695 // union { _Complex double; unsigned; }
1696 //
1697 // Note that clauses (b) and (c) were added in 0.98.
1698 //
1699 if (Hi == Memory)
1700 Lo = Memory;
1701 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1702 Lo = Memory;
1703 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1704 Lo = Memory;
1705 if (Hi == SSEUp && Lo != SSE)
1706 Hi = SSE;
1707}
1708
Chris Lattner1090a9b2010-06-28 21:43:59 +00001709X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001710 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1711 // classified recursively so that always two fields are
1712 // considered. The resulting class is calculated according to
1713 // the classes of the fields in the eightbyte:
1714 //
1715 // (a) If both classes are equal, this is the resulting class.
1716 //
1717 // (b) If one of the classes is NO_CLASS, the resulting class is
1718 // the other class.
1719 //
1720 // (c) If one of the classes is MEMORY, the result is the MEMORY
1721 // class.
1722 //
1723 // (d) If one of the classes is INTEGER, the result is the
1724 // INTEGER.
1725 //
1726 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1727 // MEMORY is used as class.
1728 //
1729 // (f) Otherwise class SSE is used.
1730
1731 // Accum should never be memory (we should have returned) or
1732 // ComplexX87 (because this cannot be passed in a structure).
1733 assert((Accum != Memory && Accum != ComplexX87) &&
1734 "Invalid accumulated classification during merge.");
1735 if (Accum == Field || Field == NoClass)
1736 return Accum;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001737 if (Field == Memory)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001738 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001739 if (Accum == NoClass)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001740 return Field;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001741 if (Accum == Integer || Field == Integer)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001742 return Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001743 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1744 Accum == X87 || Accum == X87Up)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001745 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001746 return SSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001747}
1748
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001749void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001750 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001751 // FIXME: This code can be simplified by introducing a simple value class for
1752 // Class pairs with appropriate constructor methods for the various
1753 // situations.
1754
1755 // FIXME: Some of the split computations are wrong; unaligned vectors
1756 // shouldn't be passed in registers for example, so there is no chance they
1757 // can straddle an eightbyte. Verify & simplify.
1758
1759 Lo = Hi = NoClass;
1760
1761 Class &Current = OffsetBase < 64 ? Lo : Hi;
1762 Current = Memory;
1763
John McCall183700f2009-09-21 23:43:11 +00001764 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001765 BuiltinType::Kind k = BT->getKind();
1766
1767 if (k == BuiltinType::Void) {
1768 Current = NoClass;
1769 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1770 Lo = Integer;
1771 Hi = Integer;
1772 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1773 Current = Integer;
Derek Schuff7da46f92012-10-11 16:55:58 +00001774 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1775 (k == BuiltinType::LongDouble &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001776 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001777 Current = SSE;
1778 } else if (k == BuiltinType::LongDouble) {
1779 Lo = X87;
1780 Hi = X87Up;
1781 }
1782 // FIXME: _Decimal32 and _Decimal64 are SSE.
1783 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001784 return;
1785 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001786
Chris Lattner1090a9b2010-06-28 21:43:59 +00001787 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001788 // Classify the underlying integer type.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001789 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattner1090a9b2010-06-28 21:43:59 +00001790 return;
1791 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001792
Chris Lattner1090a9b2010-06-28 21:43:59 +00001793 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001794 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001795 return;
1796 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001797
Chris Lattner1090a9b2010-06-28 21:43:59 +00001798 if (Ty->isMemberPointerType()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001799 if (Ty->isMemberFunctionPointerType()) {
1800 if (Has64BitPointers) {
1801 // If Has64BitPointers, this is an {i64, i64}, so classify both
1802 // Lo and Hi now.
1803 Lo = Hi = Integer;
1804 } else {
1805 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1806 // straddles an eightbyte boundary, Hi should be classified as well.
1807 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1808 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1809 if (EB_FuncPtr != EB_ThisAdj) {
1810 Lo = Hi = Integer;
1811 } else {
1812 Current = Integer;
1813 }
1814 }
1815 } else {
Daniel Dunbar67d438d2010-05-15 00:00:37 +00001816 Current = Integer;
Stephen Hines176edba2014-12-01 14:53:08 -08001817 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001818 return;
1819 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001820
Chris Lattner1090a9b2010-06-28 21:43:59 +00001821 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001822 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001823 if (Size == 32) {
1824 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1825 // float> as integer.
1826 Current = Integer;
1827
1828 // If this type crosses an eightbyte boundary, it should be
1829 // split.
1830 uint64_t EB_Real = (OffsetBase) / 64;
1831 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1832 if (EB_Real != EB_Imag)
1833 Hi = Lo;
1834 } else if (Size == 64) {
1835 // gcc passes <1 x double> in memory. :(
1836 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1837 return;
1838
1839 // gcc passes <1 x long long> as INTEGER.
Chris Lattner473f8e72010-08-26 18:03:20 +00001840 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner0fefa412010-08-26 18:13:50 +00001841 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1842 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1843 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001844 Current = Integer;
1845 else
1846 Current = SSE;
1847
1848 // If this type crosses an eightbyte boundary, it should be
1849 // split.
1850 if (OffsetBase && OffsetBase != 64)
1851 Hi = Lo;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001852 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001853 // Arguments of 256-bits are split into four eightbyte chunks. The
1854 // least significant one belongs to class SSE and all the others to class
1855 // SSEUP. The original Lo and Hi design considers that types can't be
1856 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1857 // This design isn't correct for 256-bits, but since there're no cases
1858 // where the upper parts would need to be inspected, avoid adding
1859 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001860 //
1861 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1862 // registers if they are "named", i.e. not part of the "..." of a
1863 // variadic function.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001864 Lo = SSE;
1865 Hi = SSEUp;
1866 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001867 return;
1868 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001869
Chris Lattner1090a9b2010-06-28 21:43:59 +00001870 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001871 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001872
Chris Lattnerea044322010-07-29 02:01:43 +00001873 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001874 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001875 if (Size <= 64)
1876 Current = Integer;
1877 else if (Size <= 128)
1878 Lo = Hi = Integer;
Chris Lattnerea044322010-07-29 02:01:43 +00001879 } else if (ET == getContext().FloatTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001880 Current = SSE;
Derek Schuff7da46f92012-10-11 16:55:58 +00001881 else if (ET == getContext().DoubleTy ||
1882 (ET == getContext().LongDoubleTy &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001883 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001884 Lo = Hi = SSE;
Chris Lattnerea044322010-07-29 02:01:43 +00001885 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001886 Current = ComplexX87;
1887
1888 // If this complex type crosses an eightbyte boundary then it
1889 // should be split.
1890 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattnerea044322010-07-29 02:01:43 +00001891 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001892 if (Hi == NoClass && EB_Real != EB_Imag)
1893 Hi = Lo;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001894
Chris Lattner1090a9b2010-06-28 21:43:59 +00001895 return;
1896 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001897
Chris Lattnerea044322010-07-29 02:01:43 +00001898 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001899 // Arrays are treated like structures.
1900
Chris Lattnerea044322010-07-29 02:01:43 +00001901 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001902
1903 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001904 // than four eightbytes, ..., it has class MEMORY.
1905 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001906 return;
1907
1908 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1909 // fields, it has class MEMORY.
1910 //
1911 // Only need to check alignment of array base.
Chris Lattnerea044322010-07-29 02:01:43 +00001912 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001913 return;
1914
1915 // Otherwise implement simplified merge. We could be smarter about
1916 // this, but it isn't worth it and would be harder to verify.
1917 Current = NoClass;
Chris Lattnerea044322010-07-29 02:01:43 +00001918 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001919 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes089d8922011-07-12 01:27:38 +00001920
1921 // The only case a 256-bit wide vector could be used is when the array
1922 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1923 // to work for sizes wider than 128, early check and fallback to memory.
1924 if (Size > 128 && EltSize != 256)
1925 return;
1926
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001927 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1928 Class FieldLo, FieldHi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001929 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001930 Lo = merge(Lo, FieldLo);
1931 Hi = merge(Hi, FieldHi);
1932 if (Lo == Memory || Hi == Memory)
1933 break;
1934 }
1935
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001936 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001937 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattner1090a9b2010-06-28 21:43:59 +00001938 return;
1939 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001940
Chris Lattner1090a9b2010-06-28 21:43:59 +00001941 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001942 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001943
1944 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001945 // than four eightbytes, ..., it has class MEMORY.
1946 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001947 return;
1948
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001949 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1950 // copy constructor or a non-trivial destructor, it is passed by invisible
1951 // reference.
Mark Lacey23630722013-10-06 01:33:34 +00001952 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001953 return;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001954
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001955 const RecordDecl *RD = RT->getDecl();
1956
1957 // Assume variable sized types are passed in memory.
1958 if (RD->hasFlexibleArrayMember())
1959 return;
1960
Chris Lattnerea044322010-07-29 02:01:43 +00001961 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001962
1963 // Reset Lo class, this will be recomputed.
1964 Current = NoClass;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001965
1966 // If this is a C++ record, classify the bases first.
1967 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001968 for (const auto &I : CXXRD->bases()) {
1969 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001970 "Unexpected base class!");
1971 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -07001972 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001973
1974 // Classify this field.
1975 //
1976 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1977 // single eightbyte, each is classified separately. Each eightbyte gets
1978 // initialized to class NO_CLASS.
1979 Class FieldLo, FieldHi;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001980 uint64_t Offset =
1981 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Stephen Hines651f13c2014-04-23 16:59:28 -07001982 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001983 Lo = merge(Lo, FieldLo);
1984 Hi = merge(Hi, FieldHi);
1985 if (Lo == Memory || Hi == Memory)
1986 break;
1987 }
1988 }
1989
1990 // Classify the fields one at a time, merging the results.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001991 unsigned idx = 0;
Bruno Cardoso Lopes548e4782011-07-12 22:30:58 +00001992 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001993 i != e; ++i, ++idx) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001994 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1995 bool BitField = i->isBitField();
1996
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001997 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1998 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001999 //
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00002000 // The only case a 256-bit wide vector could be used is when the struct
2001 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2002 // to work for sizes wider than 128, early check and fallback to memory.
2003 //
2004 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2005 Lo = Memory;
2006 return;
2007 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002008 // Note, skip this test for bit-fields, see below.
Chris Lattnerea044322010-07-29 02:01:43 +00002009 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002010 Lo = Memory;
2011 return;
2012 }
2013
2014 // Classify this field.
2015 //
2016 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2017 // exceeds a single eightbyte, each is classified
2018 // separately. Each eightbyte gets initialized to class
2019 // NO_CLASS.
2020 Class FieldLo, FieldHi;
2021
2022 // Bit-fields require special handling, they do not force the
2023 // structure to be passed in memory even if unaligned, and
2024 // therefore they can straddle an eightbyte.
2025 if (BitField) {
2026 // Ignore padding bit-fields.
2027 if (i->isUnnamedBitfield())
2028 continue;
2029
2030 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002031 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002032
2033 uint64_t EB_Lo = Offset / 64;
2034 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru9a6002a2013-10-06 09:54:18 +00002035
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002036 if (EB_Lo) {
2037 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2038 FieldLo = NoClass;
2039 FieldHi = Integer;
2040 } else {
2041 FieldLo = Integer;
2042 FieldHi = EB_Hi ? Integer : NoClass;
2043 }
2044 } else
Eli Friedman7a1b5862013-06-12 00:13:45 +00002045 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002046 Lo = merge(Lo, FieldLo);
2047 Hi = merge(Hi, FieldHi);
2048 if (Lo == Memory || Hi == Memory)
2049 break;
2050 }
2051
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002052 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002053 }
2054}
2055
Chris Lattner9c254f02010-06-29 06:01:59 +00002056ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00002057 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2058 // place naturally.
John McCalld608cdb2010-08-22 10:59:02 +00002059 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00002060 // Treat an enum type as its underlying type.
2061 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2062 Ty = EnumTy->getDecl()->getIntegerType();
2063
2064 return (Ty->isPromotableIntegerType() ?
2065 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2066 }
2067
2068 return ABIArgInfo::getIndirect(0);
2069}
2070
Eli Friedmanee1ad992011-12-02 00:11:43 +00002071bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2072 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2073 uint64_t Size = getContext().getTypeSize(VecTy);
2074 unsigned LargestVector = HasAVX ? 256 : 128;
2075 if (Size <= 64 || Size > LargestVector)
2076 return true;
2077 }
2078
2079 return false;
2080}
2081
Daniel Dunbaredfac032012-03-10 01:03:58 +00002082ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2083 unsigned freeIntRegs) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002084 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2085 // place naturally.
Daniel Dunbaredfac032012-03-10 01:03:58 +00002086 //
2087 // This assumption is optimistic, as there could be free registers available
2088 // when we need to pass this argument in memory, and LLVM could try to pass
2089 // the argument in the free register. This does not seem to happen currently,
2090 // but this code would be much safer if we could mark the argument with
2091 // 'onstack'. See PR12193.
Eli Friedmanee1ad992011-12-02 00:11:43 +00002092 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00002093 // Treat an enum type as its underlying type.
2094 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2095 Ty = EnumTy->getDecl()->getIntegerType();
2096
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00002097 return (Ty->isPromotableIntegerType() ?
2098 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00002099 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002100
Mark Lacey23630722013-10-06 01:33:34 +00002101 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002102 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00002103
Chris Lattner855d2272011-05-22 23:21:23 +00002104 // Compute the byval alignment. We specify the alignment of the byval in all
2105 // cases so that the mid-level optimizer knows the alignment of the byval.
2106 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbaredfac032012-03-10 01:03:58 +00002107
2108 // Attempt to avoid passing indirect results using byval when possible. This
2109 // is important for good codegen.
2110 //
2111 // We do this by coercing the value into a scalar type which the backend can
2112 // handle naturally (i.e., without using byval).
2113 //
2114 // For simplicity, we currently only do this when we have exhausted all of the
2115 // free integer registers. Doing this when there are free integer registers
2116 // would require more care, as we would have to ensure that the coerced value
2117 // did not claim the unused register. That would require either reording the
2118 // arguments to the function (so that any subsequent inreg values came first),
2119 // or only doing this optimization when there were no following arguments that
2120 // might be inreg.
2121 //
2122 // We currently expect it to be rare (particularly in well written code) for
2123 // arguments to be passed on the stack when there are still free integer
2124 // registers available (this would typically imply large structs being passed
2125 // by value), so this seems like a fair tradeoff for now.
2126 //
2127 // We can revisit this if the backend grows support for 'onstack' parameter
2128 // attributes. See PR12193.
2129 if (freeIntRegs == 0) {
2130 uint64_t Size = getContext().getTypeSize(Ty);
2131
2132 // If this type fits in an eightbyte, coerce it into the matching integral
2133 // type, which will end up on the stack (with alignment 8).
2134 if (Align == 8 && Size <= 64)
2135 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2136 Size));
2137 }
2138
Chris Lattner855d2272011-05-22 23:21:23 +00002139 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002140}
2141
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002142/// GetByteVectorType - The ABI specifies that a value should be passed in an
2143/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner0f408f52010-07-29 04:56:46 +00002144/// vector register.
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002145llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002146 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002147
Chris Lattner15842bd2010-07-29 05:02:29 +00002148 // Wrapper structs that just contain vectors are passed just like vectors,
2149 // strip them off if present.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002150 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner15842bd2010-07-29 05:02:29 +00002151 while (STy && STy->getNumElements() == 1) {
2152 IRType = STy->getElementType(0);
2153 STy = dyn_cast<llvm::StructType>(IRType);
2154 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002155
Bruno Cardoso Lopes528a8c72011-07-08 22:57:35 +00002156 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002157 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2158 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002159 unsigned BitWidth = VT->getBitWidth();
Tanya Lattnerce275672011-11-28 23:18:11 +00002160 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner0f408f52010-07-29 04:56:46 +00002161 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2162 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2163 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2164 EltTy->isIntegerTy(128)))
2165 return VT;
2166 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002167
Chris Lattner0f408f52010-07-29 04:56:46 +00002168 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2169}
2170
Chris Lattnere2962be2010-07-29 07:30:00 +00002171/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2172/// is known to either be off the end of the specified type or being in
2173/// alignment padding. The user type specified is known to be at most 128 bits
2174/// in size, and have passed through X86_64ABIInfo::classify with a successful
2175/// classification that put one of the two halves in the INTEGER class.
2176///
2177/// It is conservatively correct to return false.
2178static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2179 unsigned EndBit, ASTContext &Context) {
2180 // If the bytes being queried are off the end of the type, there is no user
2181 // data hiding here. This handles analysis of builtins, vectors and other
2182 // types that don't contain interesting padding.
2183 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2184 if (TySize <= StartBit)
2185 return true;
2186
Chris Lattner021c3a32010-07-29 07:43:55 +00002187 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2188 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2189 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2190
2191 // Check each element to see if the element overlaps with the queried range.
2192 for (unsigned i = 0; i != NumElts; ++i) {
2193 // If the element is after the span we care about, then we're done..
2194 unsigned EltOffset = i*EltSize;
2195 if (EltOffset >= EndBit) break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002196
Chris Lattner021c3a32010-07-29 07:43:55 +00002197 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2198 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2199 EndBit-EltOffset, Context))
2200 return false;
2201 }
2202 // If it overlaps no elements, then it is safe to process as padding.
2203 return true;
2204 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002205
Chris Lattnere2962be2010-07-29 07:30:00 +00002206 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2207 const RecordDecl *RD = RT->getDecl();
2208 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002209
Chris Lattnere2962be2010-07-29 07:30:00 +00002210 // If this is a C++ record, check the bases first.
2211 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002212 for (const auto &I : CXXRD->bases()) {
2213 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnere2962be2010-07-29 07:30:00 +00002214 "Unexpected base class!");
2215 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -07002216 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002217
Chris Lattnere2962be2010-07-29 07:30:00 +00002218 // If the base is after the span we care about, ignore it.
Benjamin Kramerd4f51982012-07-04 18:45:14 +00002219 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnere2962be2010-07-29 07:30:00 +00002220 if (BaseOffset >= EndBit) continue;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002221
Chris Lattnere2962be2010-07-29 07:30:00 +00002222 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Stephen Hines651f13c2014-04-23 16:59:28 -07002223 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnere2962be2010-07-29 07:30:00 +00002224 EndBit-BaseOffset, Context))
2225 return false;
2226 }
2227 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002228
Chris Lattnere2962be2010-07-29 07:30:00 +00002229 // Verify that no field has data that overlaps the region of interest. Yes
2230 // this could be sped up a lot by being smarter about queried fields,
2231 // however we're only looking at structs up to 16 bytes, so we don't care
2232 // much.
2233 unsigned idx = 0;
2234 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2235 i != e; ++i, ++idx) {
2236 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002237
Chris Lattnere2962be2010-07-29 07:30:00 +00002238 // If we found a field after the region we care about, then we're done.
2239 if (FieldOffset >= EndBit) break;
2240
2241 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2242 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2243 Context))
2244 return false;
2245 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002246
Chris Lattnere2962be2010-07-29 07:30:00 +00002247 // If nothing in this record overlapped the area of interest, then we're
2248 // clean.
2249 return true;
2250 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002251
Chris Lattnere2962be2010-07-29 07:30:00 +00002252 return false;
2253}
2254
Chris Lattner0b362002010-07-29 18:39:32 +00002255/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2256/// float member at the specified offset. For example, {int,{float}} has a
2257/// float at offset 4. It is conservatively correct for this routine to return
2258/// false.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002259static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmow25a6a842012-10-08 16:25:52 +00002260 const llvm::DataLayout &TD) {
Chris Lattner0b362002010-07-29 18:39:32 +00002261 // Base case if we find a float.
2262 if (IROffset == 0 && IRType->isFloatTy())
2263 return true;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002264
Chris Lattner0b362002010-07-29 18:39:32 +00002265 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002266 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner0b362002010-07-29 18:39:32 +00002267 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2268 unsigned Elt = SL->getElementContainingOffset(IROffset);
2269 IROffset -= SL->getElementOffset(Elt);
2270 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2271 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002272
Chris Lattner0b362002010-07-29 18:39:32 +00002273 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002274 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2275 llvm::Type *EltTy = ATy->getElementType();
Chris Lattner0b362002010-07-29 18:39:32 +00002276 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2277 IROffset -= IROffset/EltSize*EltSize;
2278 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2279 }
2280
2281 return false;
2282}
2283
Chris Lattnerf47c9442010-07-29 18:13:09 +00002284
2285/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2286/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002287llvm::Type *X86_64ABIInfo::
2288GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattnerf47c9442010-07-29 18:13:09 +00002289 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnercba8d312010-07-29 18:19:50 +00002290 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattnerf47c9442010-07-29 18:13:09 +00002291 // pass as float if the last 4 bytes is just padding. This happens for
2292 // structs that contain 3 floats.
2293 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2294 SourceOffset*8+64, getContext()))
2295 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002296
Chris Lattner0b362002010-07-29 18:39:32 +00002297 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2298 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2299 // case.
Micah Villmow25a6a842012-10-08 16:25:52 +00002300 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2301 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner22fd4ba2010-08-25 23:39:14 +00002302 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002303
Chris Lattnerf47c9442010-07-29 18:13:09 +00002304 return llvm::Type::getDoubleTy(getVMContext());
2305}
2306
2307
Chris Lattner0d2656d2010-07-29 17:40:35 +00002308/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2309/// an 8-byte GPR. This means that we either have a scalar or we are talking
2310/// about the high or low part of an up-to-16-byte struct. This routine picks
2311/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattner49382de2010-07-28 22:44:07 +00002312/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2313/// etc).
2314///
2315/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2316/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2317/// the 8-byte value references. PrefType may be null.
2318///
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002319/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattner49382de2010-07-28 22:44:07 +00002320/// an offset into this that we're processing (which is always either 0 or 8).
2321///
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002322llvm::Type *X86_64ABIInfo::
2323GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner0d2656d2010-07-29 17:40:35 +00002324 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnere2962be2010-07-29 07:30:00 +00002325 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2326 // returning an 8-byte unit starting with it. See if we can safely use it.
2327 if (IROffset == 0) {
2328 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffbabaf312012-10-11 15:52:22 +00002329 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2330 IRType->isIntegerTy(64))
Chris Lattnere2962be2010-07-29 07:30:00 +00002331 return IRType;
Chris Lattner49382de2010-07-28 22:44:07 +00002332
Chris Lattnere2962be2010-07-29 07:30:00 +00002333 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2334 // goodness in the source type is just tail padding. This is allowed to
2335 // kick in for struct {double,int} on the int, but not on
2336 // struct{double,int,int} because we wouldn't return the second int. We
2337 // have to do this analysis on the source type because we can't depend on
2338 // unions being lowered a specific way etc.
2339 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffbabaf312012-10-11 15:52:22 +00002340 IRType->isIntegerTy(32) ||
2341 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2342 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2343 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002344
Chris Lattnere2962be2010-07-29 07:30:00 +00002345 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2346 SourceOffset*8+64, getContext()))
2347 return IRType;
2348 }
2349 }
Chris Lattner49382de2010-07-28 22:44:07 +00002350
Chris Lattner2acc6e32011-07-18 04:24:23 +00002351 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner49382de2010-07-28 22:44:07 +00002352 // If this is a struct, recurse into the field at the specified offset.
Micah Villmow25a6a842012-10-08 16:25:52 +00002353 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattner49382de2010-07-28 22:44:07 +00002354 if (IROffset < SL->getSizeInBytes()) {
2355 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2356 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002357
Chris Lattner0d2656d2010-07-29 17:40:35 +00002358 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2359 SourceTy, SourceOffset);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002360 }
Chris Lattner49382de2010-07-28 22:44:07 +00002361 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002362
Chris Lattner2acc6e32011-07-18 04:24:23 +00002363 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002364 llvm::Type *EltTy = ATy->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00002365 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner021c3a32010-07-29 07:43:55 +00002366 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner0d2656d2010-07-29 17:40:35 +00002367 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2368 SourceOffset);
Chris Lattner021c3a32010-07-29 07:43:55 +00002369 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002370
Chris Lattner49382de2010-07-28 22:44:07 +00002371 // Okay, we don't have any better idea of what to pass, so we pass this in an
2372 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002373 unsigned TySizeInBytes =
2374 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattner49382de2010-07-28 22:44:07 +00002375
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002376 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002377
Chris Lattner49382de2010-07-28 22:44:07 +00002378 // It is always safe to classify this as an integer type up to i64 that
2379 // isn't larger than the structure.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002380 return llvm::IntegerType::get(getVMContext(),
2381 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner9c254f02010-06-29 06:01:59 +00002382}
2383
Chris Lattner66e7b682010-09-01 00:50:20 +00002384
2385/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2386/// be used as elements of a two register pair to pass or return, return a
2387/// first class aggregate to represent them. For example, if the low part of
2388/// a by-value argument should be passed as i32* and the high part as float,
2389/// return {i32*, float}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002390static llvm::Type *
Jay Foadef6de3d2011-07-11 09:56:20 +00002391GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmow25a6a842012-10-08 16:25:52 +00002392 const llvm::DataLayout &TD) {
Chris Lattner66e7b682010-09-01 00:50:20 +00002393 // In order to correctly satisfy the ABI, we need to the high part to start
2394 // at offset 8. If the high and low parts we inferred are both 4-byte types
2395 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2396 // the second element at offset 8. Check for this:
2397 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2398 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Stephen Hines176edba2014-12-01 14:53:08 -08002399 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattner66e7b682010-09-01 00:50:20 +00002400 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002401
Chris Lattner66e7b682010-09-01 00:50:20 +00002402 // To handle this, we have to increase the size of the low part so that the
2403 // second element will start at an 8 byte offset. We can't increase the size
2404 // of the second element because it might make us access off the end of the
2405 // struct.
2406 if (HiStart != 8) {
2407 // There are only two sorts of types the ABI generation code can produce for
2408 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2409 // Promote these to a larger type.
2410 if (Lo->isFloatTy())
2411 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2412 else {
2413 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2414 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2415 }
2416 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002417
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002418 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002419
2420
Chris Lattner66e7b682010-09-01 00:50:20 +00002421 // Verify that the second element is at an 8-byte offset.
2422 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2423 "Invalid x86-64 argument pair!");
2424 return Result;
2425}
2426
Chris Lattner519f68c2010-07-28 23:06:14 +00002427ABIArgInfo X86_64ABIInfo::
Chris Lattnera3c109b2010-07-29 02:16:43 +00002428classifyReturnType(QualType RetTy) const {
Chris Lattner519f68c2010-07-28 23:06:14 +00002429 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2430 // classification algorithm.
2431 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002432 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner519f68c2010-07-28 23:06:14 +00002433
2434 // Check some invariants.
2435 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002436 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2437
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002438 llvm::Type *ResType = nullptr;
Chris Lattner519f68c2010-07-28 23:06:14 +00002439 switch (Lo) {
2440 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002441 if (Hi == NoClass)
2442 return ABIArgInfo::getIgnore();
2443 // If the low part is just padding, it takes no register, leave ResType
2444 // null.
2445 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2446 "Unknown missing lo part");
2447 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002448
2449 case SSEUp:
2450 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002451 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002452
2453 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2454 // hidden argument.
2455 case Memory:
2456 return getIndirectReturnResult(RetTy);
2457
2458 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2459 // available register of the sequence %rax, %rdx is used.
2460 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002461 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002462
Chris Lattnereb518b42010-07-29 21:42:50 +00002463 // If we have a sign or zero extended integer, make sure to return Extend
2464 // so that the parameter gets the right LLVM IR attributes.
2465 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2466 // Treat an enum type as its underlying type.
2467 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2468 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002469
Chris Lattnereb518b42010-07-29 21:42:50 +00002470 if (RetTy->isIntegralOrEnumerationType() &&
2471 RetTy->isPromotableIntegerType())
2472 return ABIArgInfo::getExtend();
2473 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002474 break;
2475
2476 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2477 // available SSE register of the sequence %xmm0, %xmm1 is used.
2478 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002479 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattner0b30c672010-07-28 23:12:33 +00002480 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002481
2482 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2483 // returned on the X87 stack in %st0 as 80-bit x87 number.
2484 case X87:
Chris Lattnerea044322010-07-29 02:01:43 +00002485 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattner0b30c672010-07-28 23:12:33 +00002486 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002487
2488 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2489 // part of the value is returned in %st0 and the imaginary part in
2490 // %st1.
2491 case ComplexX87:
2492 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner7650d952011-06-18 22:49:11 +00002493 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattnerea044322010-07-29 02:01:43 +00002494 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner519f68c2010-07-28 23:06:14 +00002495 NULL);
2496 break;
2497 }
2498
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002499 llvm::Type *HighPart = nullptr;
Chris Lattner519f68c2010-07-28 23:06:14 +00002500 switch (Hi) {
2501 // Memory was handled previously and X87 should
2502 // never occur as a hi class.
2503 case Memory:
2504 case X87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002505 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002506
2507 case ComplexX87: // Previously handled.
Chris Lattner0b30c672010-07-28 23:12:33 +00002508 case NoClass:
2509 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002510
Chris Lattner3db4dde2010-09-01 00:20:33 +00002511 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002512 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002513 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2514 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002515 break;
Chris Lattner3db4dde2010-09-01 00:20:33 +00002516 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002517 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002518 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2519 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002520 break;
2521
2522 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002523 // is passed in the next available eightbyte chunk if the last used
2524 // vector register.
Chris Lattner519f68c2010-07-28 23:06:14 +00002525 //
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002526 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner519f68c2010-07-28 23:06:14 +00002527 case SSEUp:
2528 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002529 ResType = GetByteVectorType(RetTy);
Chris Lattner519f68c2010-07-28 23:06:14 +00002530 break;
2531
2532 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2533 // returned together with the previous X87 value in %st0.
2534 case X87Up:
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002535 // If X87Up is preceded by X87, we don't need to do
Chris Lattner519f68c2010-07-28 23:06:14 +00002536 // anything. However, in some cases with unions it may not be
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002537 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner519f68c2010-07-28 23:06:14 +00002538 // extra bits in an SSE reg.
Chris Lattner603519d2010-07-29 17:49:08 +00002539 if (Lo != X87) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002540 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002541 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2542 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner603519d2010-07-29 17:49:08 +00002543 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002544 break;
2545 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002546
Chris Lattner3db4dde2010-09-01 00:20:33 +00002547 // If a high part was specified, merge it together with the low part. It is
Chris Lattner645406a2010-09-01 00:24:35 +00002548 // known to pass in the high eightbyte of the result. We do this by forming a
2549 // first class struct aggregate with the high and low part: {low, high}
Chris Lattner66e7b682010-09-01 00:50:20 +00002550 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002551 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner519f68c2010-07-28 23:06:14 +00002552
Chris Lattnereb518b42010-07-29 21:42:50 +00002553 return ABIArgInfo::getDirect(ResType);
Chris Lattner519f68c2010-07-28 23:06:14 +00002554}
2555
Daniel Dunbaredfac032012-03-10 01:03:58 +00002556ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman7a1b5862013-06-12 00:13:45 +00002557 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2558 bool isNamedArg)
Daniel Dunbaredfac032012-03-10 01:03:58 +00002559 const
2560{
Stephen Hines176edba2014-12-01 14:53:08 -08002561 Ty = useFirstFieldIfTransparentUnion(Ty);
2562
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002563 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002564 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002565
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002566 // Check some invariants.
2567 // FIXME: Enforce these by construction.
2568 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002569 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2570
2571 neededInt = 0;
2572 neededSSE = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002573 llvm::Type *ResType = nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002574 switch (Lo) {
2575 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002576 if (Hi == NoClass)
2577 return ABIArgInfo::getIgnore();
2578 // If the low part is just padding, it takes no register, leave ResType
2579 // null.
2580 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2581 "Unknown missing lo part");
2582 break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002583
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002584 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2585 // on the stack.
2586 case Memory:
2587
2588 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2589 // COMPLEX_X87, it is passed in memory.
2590 case X87:
2591 case ComplexX87:
Mark Lacey23630722013-10-06 01:33:34 +00002592 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedmanded137f2011-06-29 07:04:55 +00002593 ++neededInt;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002594 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002595
2596 case SSEUp:
2597 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002598 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002599
2600 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2601 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2602 // and %r9 is used.
2603 case Integer:
Chris Lattner9c254f02010-06-29 06:01:59 +00002604 ++neededInt;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002605
Chris Lattner49382de2010-07-28 22:44:07 +00002606 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002607 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattnereb518b42010-07-29 21:42:50 +00002608
2609 // If we have a sign or zero extended integer, make sure to return Extend
2610 // so that the parameter gets the right LLVM IR attributes.
2611 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2612 // Treat an enum type as its underlying type.
2613 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2614 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002615
Chris Lattnereb518b42010-07-29 21:42:50 +00002616 if (Ty->isIntegralOrEnumerationType() &&
2617 Ty->isPromotableIntegerType())
2618 return ABIArgInfo::getExtend();
2619 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002620
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002621 break;
2622
2623 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2624 // available SSE register is used, the registers are taken in the
2625 // order from %xmm0 to %xmm7.
Bill Wendlingbb465d72010-10-18 03:41:31 +00002626 case SSE: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002627 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman14508ff2011-07-02 00:57:27 +00002628 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling99aaae82010-10-18 23:51:38 +00002629 ++neededSSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002630 break;
2631 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00002632 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002633
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002634 llvm::Type *HighPart = nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002635 switch (Hi) {
2636 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002637 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002638 // which is passed in memory.
2639 case Memory:
2640 case X87:
2641 case ComplexX87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002642 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002643
2644 case NoClass: break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002645
Chris Lattner645406a2010-09-01 00:24:35 +00002646 case Integer:
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002647 ++neededInt;
Chris Lattner49382de2010-07-28 22:44:07 +00002648 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002649 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002650
Chris Lattner645406a2010-09-01 00:24:35 +00002651 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2652 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002653 break;
2654
2655 // X87Up generally doesn't occur here (long double is passed in
2656 // memory), except in situations involving unions.
2657 case X87Up:
Chris Lattner645406a2010-09-01 00:24:35 +00002658 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002659 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002660
Chris Lattner645406a2010-09-01 00:24:35 +00002661 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2662 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner117e3f42010-07-30 04:02:24 +00002663
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002664 ++neededSSE;
2665 break;
2666
2667 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2668 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002669 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002670 case SSEUp:
Chris Lattnerab5722e2010-07-28 23:47:21 +00002671 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002672 ResType = GetByteVectorType(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002673 break;
2674 }
2675
Chris Lattner645406a2010-09-01 00:24:35 +00002676 // If a high part was specified, merge it together with the low part. It is
2677 // known to pass in the high eightbyte of the result. We do this by forming a
2678 // first class struct aggregate with the high and low part: {low, high}
2679 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002680 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002681
Chris Lattnereb518b42010-07-29 21:42:50 +00002682 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002683}
2684
Chris Lattneree5dcd02010-07-29 02:31:05 +00002685void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002686
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002687 if (!getCXXABI().classifyReturnType(FI))
2688 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002689
2690 // Keep track of the number of assigned registers.
Bill Wendling99aaae82010-10-18 23:51:38 +00002691 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002692
2693 // If the return value is indirect, then the hidden argument is consuming one
2694 // integer register.
2695 if (FI.getReturnInfo().isIndirect())
2696 --freeIntRegs;
2697
Stephen Hines176edba2014-12-01 14:53:08 -08002698 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002699 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2700 // get assigned (in left-to-right order) for passing as follows...
Stephen Hines176edba2014-12-01 14:53:08 -08002701 unsigned ArgNo = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002702 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Stephen Hines176edba2014-12-01 14:53:08 -08002703 it != ie; ++it, ++ArgNo) {
2704 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002705
Bill Wendling99aaae82010-10-18 23:51:38 +00002706 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002707 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Stephen Hines176edba2014-12-01 14:53:08 -08002708 neededSSE, IsNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002709
2710 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2711 // eightbyte of an argument, the whole argument is passed on the
2712 // stack. If registers have already been assigned for some
2713 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling99aaae82010-10-18 23:51:38 +00002714 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002715 freeIntRegs -= neededInt;
2716 freeSSERegs -= neededSSE;
2717 } else {
Daniel Dunbaredfac032012-03-10 01:03:58 +00002718 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002719 }
2720 }
2721}
2722
2723static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2724 QualType Ty,
2725 CodeGenFunction &CGF) {
2726 llvm::Value *overflow_arg_area_p =
2727 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2728 llvm::Value *overflow_arg_area =
2729 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2730
2731 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2732 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedman8d2fe422011-11-18 02:44:19 +00002733 // It isn't stated explicitly in the standard, but in practice we use
2734 // alignment greater than 16 where necessary.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002735 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2736 if (Align > 8) {
Eli Friedman8d2fe422011-11-18 02:44:19 +00002737 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson0032b272009-08-13 21:57:51 +00002738 llvm::Value *Offset =
Eli Friedman8d2fe422011-11-18 02:44:19 +00002739 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002740 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2741 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner77b89b82010-06-27 07:15:29 +00002742 CGF.Int64Ty);
Eli Friedman8d2fe422011-11-18 02:44:19 +00002743 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002744 overflow_arg_area =
2745 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2746 overflow_arg_area->getType(),
2747 "overflow_arg_area.align");
2748 }
2749
2750 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002751 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002752 llvm::Value *Res =
2753 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002754 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002755
2756 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2757 // l->overflow_arg_area + sizeof(type).
2758 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2759 // an 8 byte boundary.
2760
2761 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson0032b272009-08-13 21:57:51 +00002762 llvm::Value *Offset =
Chris Lattner77b89b82010-06-27 07:15:29 +00002763 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002764 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2765 "overflow_arg_area.next");
2766 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2767
2768 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2769 return Res;
2770}
2771
2772llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2773 CodeGenFunction &CGF) const {
2774 // Assume that va_list type is correct; should be pointer to LLVM type:
2775 // struct {
2776 // i32 gp_offset;
2777 // i32 fp_offset;
2778 // i8* overflow_arg_area;
2779 // i8* reg_save_area;
2780 // };
Bill Wendling99aaae82010-10-18 23:51:38 +00002781 unsigned neededInt, neededSSE;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002782
Chris Lattnera14db752010-03-11 18:19:55 +00002783 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002784 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2785 /*isNamedArg*/false);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002786
2787 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2788 // in the registers. If not go to step 7.
2789 if (!neededInt && !neededSSE)
2790 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2791
2792 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2793 // general purpose registers needed to pass type and num_fp to hold
2794 // the number of floating point registers needed.
2795
2796 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2797 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2798 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2799 //
2800 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2801 // register save space).
2802
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002803 llvm::Value *InRegs = nullptr;
2804 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2805 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002806 if (neededInt) {
2807 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2808 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002809 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2810 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002811 }
2812
2813 if (neededSSE) {
2814 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2815 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2816 llvm::Value *FitsInFP =
Chris Lattner1090a9b2010-06-28 21:43:59 +00002817 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2818 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002819 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2820 }
2821
2822 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2823 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2824 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2825 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2826
2827 // Emit code to load the value if it was passed in registers.
2828
2829 CGF.EmitBlock(InRegBlock);
2830
2831 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2832 // an offset of l->gp_offset and/or l->fp_offset. This may require
2833 // copying to a temporary location in case the parameter is passed
2834 // in different register classes or requires an alignment greater
2835 // than 8 for general purpose registers and 16 for XMM registers.
2836 //
2837 // FIXME: This really results in shameful code when we end up needing to
2838 // collect arguments from different places; often what should result in a
2839 // simple assembling of a structure from scattered addresses has many more
2840 // loads than necessary. Can we clean this up?
Chris Lattner2acc6e32011-07-18 04:24:23 +00002841 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002842 llvm::Value *RegAddr =
2843 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2844 "reg_save_area");
2845 if (neededInt && neededSSE) {
2846 // FIXME: Cleanup.
Chris Lattner800588f2010-07-29 06:26:06 +00002847 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002848 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmaneeb00622013-06-07 23:20:55 +00002849 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2850 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002851 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002852 llvm::Type *TyLo = ST->getElementType(0);
2853 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattnera8b7a7d2010-08-26 06:28:35 +00002854 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002855 "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002856 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2857 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002858 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2859 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002860 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2861 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002862 llvm::Value *V =
2863 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2864 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2865 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2866 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2867
Owen Andersona1cf15f2009-07-14 23:10:40 +00002868 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002869 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002870 } else if (neededInt) {
2871 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2872 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002873 llvm::PointerType::getUnqual(LTy));
Eli Friedmaneeb00622013-06-07 23:20:55 +00002874
2875 // Copy to a temporary if necessary to ensure the appropriate alignment.
2876 std::pair<CharUnits, CharUnits> SizeAlign =
2877 CGF.getContext().getTypeInfoInChars(Ty);
2878 uint64_t TySize = SizeAlign.first.getQuantity();
2879 unsigned TyAlign = SizeAlign.second.getQuantity();
2880 if (TyAlign > 8) {
Eli Friedmaneeb00622013-06-07 23:20:55 +00002881 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2882 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2883 RegAddr = Tmp;
2884 }
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002885 } else if (neededSSE == 1) {
2886 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2887 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2888 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002889 } else {
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002890 assert(neededSSE == 2 && "Invalid number of needed registers!");
2891 // SSE registers are spaced 16 bytes apart in the register save
2892 // area, we need to collect the two eightbytes together.
2893 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattner1090a9b2010-06-28 21:43:59 +00002894 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattner8b418682012-02-07 00:39:47 +00002895 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002896 llvm::Type *DblPtrTy =
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002897 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmaneeb00622013-06-07 23:20:55 +00002898 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2899 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2900 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002901 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2902 DblPtrTy));
2903 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2904 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2905 DblPtrTy));
2906 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2907 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2908 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002909 }
2910
2911 // AMD64-ABI 3.5.7p5: Step 5. Set:
2912 // l->gp_offset = l->gp_offset + num_gp * 8
2913 // l->fp_offset = l->fp_offset + num_fp * 16.
2914 if (neededInt) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002915 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002916 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2917 gp_offset_p);
2918 }
2919 if (neededSSE) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002920 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002921 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2922 fp_offset_p);
2923 }
2924 CGF.EmitBranch(ContBlock);
2925
2926 // Emit code to load the value if it was passed in memory.
2927
2928 CGF.EmitBlock(InMemBlock);
2929 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2930
2931 // Return the appropriate result.
2932
2933 CGF.EmitBlock(ContBlock);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002934 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002935 "vaarg.addr");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002936 ResAddr->addIncoming(RegAddr, InRegBlock);
2937 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002938 return ResAddr;
2939}
2940
Stephen Hines176edba2014-12-01 14:53:08 -08002941ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
2942 bool IsReturnType) const {
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002943
2944 if (Ty->isVoidType())
2945 return ABIArgInfo::getIgnore();
2946
2947 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2948 Ty = EnumTy->getDecl()->getIntegerType();
2949
Stephen Hines176edba2014-12-01 14:53:08 -08002950 TypeInfo Info = getContext().getTypeInfo(Ty);
2951 uint64_t Width = Info.Width;
2952 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002953
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002954 const RecordType *RT = Ty->getAs<RecordType>();
2955 if (RT) {
2956 if (!IsReturnType) {
Mark Lacey23630722013-10-06 01:33:34 +00002957 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002958 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2959 }
2960
2961 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002962 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2963
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002964 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Stephen Hines176edba2014-12-01 14:53:08 -08002965 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002966 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Stephen Hines176edba2014-12-01 14:53:08 -08002967 Width));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002968 }
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002969
Stephen Hines176edba2014-12-01 14:53:08 -08002970 // vectorcall adds the concept of a homogenous vector aggregate, similar to
2971 // other targets.
2972 const Type *Base = nullptr;
2973 uint64_t NumElts = 0;
2974 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
2975 if (FreeSSERegs >= NumElts) {
2976 FreeSSERegs -= NumElts;
2977 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
2978 return ABIArgInfo::getDirect();
2979 return ABIArgInfo::getExpand();
2980 }
2981 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
2982 }
2983
2984
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002985 if (Ty->isMemberPointerType()) {
2986 // If the member pointer is represented by an LLVM int or ptr, pass it
2987 // directly.
2988 llvm::Type *LLTy = CGT.ConvertType(Ty);
2989 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2990 return ABIArgInfo::getDirect();
2991 }
2992
2993 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002994 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2995 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Stephen Hines176edba2014-12-01 14:53:08 -08002996 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002997 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002998
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002999 // Otherwise, coerce it to a small integer.
Stephen Hines176edba2014-12-01 14:53:08 -08003000 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003001 }
3002
Stephen Hines176edba2014-12-01 14:53:08 -08003003 // Bool type is always extended to the ABI, other builtin types are not
3004 // extended.
3005 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3006 if (BT && BT->getKind() == BuiltinType::Bool)
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003007 return ABIArgInfo::getExtend();
3008
3009 return ABIArgInfo::getDirect();
3010}
3011
3012void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines176edba2014-12-01 14:53:08 -08003013 bool IsVectorCall =
3014 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003015
Stephen Hines176edba2014-12-01 14:53:08 -08003016 // We can use up to 4 SSE return registers with vectorcall.
3017 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3018 if (!getCXXABI().classifyReturnType(FI))
3019 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3020
3021 // We can use up to 6 SSE register parameters with vectorcall.
3022 FreeSSERegs = IsVectorCall ? 6 : 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07003023 for (auto &I : FI.arguments())
Stephen Hines176edba2014-12-01 14:53:08 -08003024 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00003025}
3026
Chris Lattnerf13721d2010-08-31 16:44:54 +00003027llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3028 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003029 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003030
Chris Lattnerf13721d2010-08-31 16:44:54 +00003031 CGBuilderTy &Builder = CGF.Builder;
3032 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3033 "ap");
3034 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3035 llvm::Type *PTy =
3036 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3037 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3038
3039 uint64_t Offset =
3040 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3041 llvm::Value *NextAddr =
3042 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3043 "ap.next");
3044 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3045
3046 return AddrTyped;
3047}
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003048
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003049namespace {
3050
Derek Schuff263366f2012-10-16 22:30:41 +00003051class NaClX86_64ABIInfo : public ABIInfo {
3052 public:
3053 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3054 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07003055 void computeInfo(CGFunctionInfo &FI) const override;
3056 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3057 CodeGenFunction &CGF) const override;
Derek Schuff263366f2012-10-16 22:30:41 +00003058 private:
3059 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3060 X86_64ABIInfo NInfo; // Used for everything else.
3061};
3062
3063class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines176edba2014-12-01 14:53:08 -08003064 bool HasAVX;
Derek Schuff263366f2012-10-16 22:30:41 +00003065 public:
Stephen Hines176edba2014-12-01 14:53:08 -08003066 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3067 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {
3068 }
3069 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3070 return HasAVX ? 32 : 16;
3071 }
Derek Schuff263366f2012-10-16 22:30:41 +00003072};
3073
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003074}
3075
Derek Schuff263366f2012-10-16 22:30:41 +00003076void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3077 if (FI.getASTCallingConvention() == CC_PnaclCall)
3078 PInfo.computeInfo(FI);
3079 else
3080 NInfo.computeInfo(FI);
3081}
3082
3083llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3084 CodeGenFunction &CGF) const {
3085 // Always use the native convention; calling pnacl-style varargs functions
3086 // is unuspported.
3087 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
3088}
3089
3090
John McCallec853ba2010-03-11 00:10:12 +00003091// PowerPC-32
John McCallec853ba2010-03-11 00:10:12 +00003092namespace {
Stephen Hines176edba2014-12-01 14:53:08 -08003093/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3094class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallec853ba2010-03-11 00:10:12 +00003095public:
Stephen Hines176edba2014-12-01 14:53:08 -08003096 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3097
3098 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3099 CodeGenFunction &CGF) const override;
3100};
3101
3102class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3103public:
3104 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003105
Stephen Hines651f13c2014-04-23 16:59:28 -07003106 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallec853ba2010-03-11 00:10:12 +00003107 // This is recovered from gcc output.
3108 return 1; // r1 is the dedicated stack pointer
3109 }
3110
3111 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07003112 llvm::Value *Address) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08003113
3114 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3115 return 16; // Natural alignment for Altivec vectors.
3116 }
John McCallec853ba2010-03-11 00:10:12 +00003117};
3118
3119}
3120
Stephen Hines176edba2014-12-01 14:53:08 -08003121llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3122 QualType Ty,
3123 CodeGenFunction &CGF) const {
3124 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3125 // TODO: Implement this. For now ignore.
3126 (void)CTy;
3127 return nullptr;
3128 }
3129
3130 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3131 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3132 llvm::Type *CharPtr = CGF.Int8PtrTy;
3133 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3134
3135 CGBuilderTy &Builder = CGF.Builder;
3136 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3137 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3138 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3139 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3140 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3141 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3142 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3143 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3144 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3145 // Align GPR when TY is i64.
3146 if (isI64) {
3147 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3148 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3149 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3150 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3151 }
3152 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3153 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3154 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3155 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3156 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3157
3158 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3159 Builder.getInt8(8), "cond");
3160
3161 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3162 Builder.getInt8(isInt ? 4 : 8));
3163
3164 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3165
3166 if (Ty->isFloatingType())
3167 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3168
3169 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3170 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3171 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3172
3173 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3174
3175 CGF.EmitBlock(UsingRegs);
3176
3177 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3178 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3179 // Increase the GPR/FPR indexes.
3180 if (isInt) {
3181 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3182 Builder.CreateStore(GPR, GPRPtr);
3183 } else {
3184 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3185 Builder.CreateStore(FPR, FPRPtr);
3186 }
3187 CGF.EmitBranch(Cont);
3188
3189 CGF.EmitBlock(UsingOverflow);
3190
3191 // Increase the overflow area.
3192 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3193 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3194 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3195 CGF.EmitBranch(Cont);
3196
3197 CGF.EmitBlock(Cont);
3198
3199 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3200 Result->addIncoming(Result1, UsingRegs);
3201 Result->addIncoming(Result2, UsingOverflow);
3202
3203 if (Ty->isAggregateType()) {
3204 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3205 return Builder.CreateLoad(AGGPtr, false, "aggr");
3206 }
3207
3208 return Result;
3209}
3210
John McCallec853ba2010-03-11 00:10:12 +00003211bool
3212PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3213 llvm::Value *Address) const {
3214 // This is calculated from the LLVM and GCC tables and verified
3215 // against gcc output. AFAIK all ABIs use the same encoding.
3216
3217 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallec853ba2010-03-11 00:10:12 +00003218
Chris Lattner8b418682012-02-07 00:39:47 +00003219 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallec853ba2010-03-11 00:10:12 +00003220 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3221 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3222 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3223
3224 // 0-31: r0-31, the 4-byte general-purpose registers
John McCallaeeb7012010-05-27 06:19:26 +00003225 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallec853ba2010-03-11 00:10:12 +00003226
3227 // 32-63: fp0-31, the 8-byte floating-point registers
John McCallaeeb7012010-05-27 06:19:26 +00003228 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallec853ba2010-03-11 00:10:12 +00003229
3230 // 64-76 are various 4-byte special-purpose registers:
3231 // 64: mq
3232 // 65: lr
3233 // 66: ctr
3234 // 67: ap
3235 // 68-75 cr0-7
3236 // 76: xer
John McCallaeeb7012010-05-27 06:19:26 +00003237 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallec853ba2010-03-11 00:10:12 +00003238
3239 // 77-108: v0-31, the 16-byte vector registers
John McCallaeeb7012010-05-27 06:19:26 +00003240 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallec853ba2010-03-11 00:10:12 +00003241
3242 // 109: vrsave
3243 // 110: vscr
3244 // 111: spe_acc
3245 // 112: spefscr
3246 // 113: sfp
John McCallaeeb7012010-05-27 06:19:26 +00003247 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallec853ba2010-03-11 00:10:12 +00003248
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003249 return false;
John McCallec853ba2010-03-11 00:10:12 +00003250}
3251
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003252// PowerPC-64
3253
3254namespace {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003255/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3256class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Stephen Hines176edba2014-12-01 14:53:08 -08003257public:
3258 enum ABIKind {
3259 ELFv1 = 0,
3260 ELFv2
3261 };
3262
3263private:
3264 static const unsigned GPRBits = 64;
3265 ABIKind Kind;
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003266
3267public:
Stephen Hines176edba2014-12-01 14:53:08 -08003268 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3269 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003270
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003271 bool isPromotableTypeForABI(QualType Ty) const;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003272 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003273
3274 ABIArgInfo classifyReturnType(QualType RetTy) const;
3275 ABIArgInfo classifyArgumentType(QualType Ty) const;
3276
Stephen Hines176edba2014-12-01 14:53:08 -08003277 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3278 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3279 uint64_t Members) const override;
3280
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003281 // TODO: We can add more logic to computeInfo to improve performance.
3282 // Example: For aggregate arguments that fit in a register, we could
3283 // use getDirectInReg (as is done below for structs containing a single
3284 // floating-point value) to avoid pushing them to memory on function
3285 // entry. This would require changing the logic in PPCISelLowering
3286 // when lowering the parameters in the caller and args in the callee.
Stephen Hines651f13c2014-04-23 16:59:28 -07003287 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003288 if (!getCXXABI().classifyReturnType(FI))
3289 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07003290 for (auto &I : FI.arguments()) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003291 // We rely on the default argument classification for the most part.
3292 // One exception: An aggregate containing a single floating-point
Bill Schmidtb1993102013-07-23 22:15:57 +00003293 // or vector item must be passed in a register if one is available.
Stephen Hines651f13c2014-04-23 16:59:28 -07003294 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003295 if (T) {
3296 const BuiltinType *BT = T->getAs<BuiltinType>();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003297 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3298 (BT && BT->isFloatingPoint())) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003299 QualType QT(T, 0);
Stephen Hines651f13c2014-04-23 16:59:28 -07003300 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003301 continue;
3302 }
3303 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003304 I.info = classifyArgumentType(I.type);
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00003305 }
3306 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003307
Stephen Hines651f13c2014-04-23 16:59:28 -07003308 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3309 CodeGenFunction &CGF) const override;
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003310};
3311
3312class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3313public:
Stephen Hines176edba2014-12-01 14:53:08 -08003314 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3315 PPC64_SVR4_ABIInfo::ABIKind Kind)
3316 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003317
Stephen Hines651f13c2014-04-23 16:59:28 -07003318 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003319 // This is recovered from gcc output.
3320 return 1; // r1 is the dedicated stack pointer
3321 }
3322
3323 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07003324 llvm::Value *Address) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08003325
3326 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3327 return 16; // Natural alignment for Altivec and VSX vectors.
3328 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003329};
3330
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003331class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3332public:
3333 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3334
Stephen Hines651f13c2014-04-23 16:59:28 -07003335 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003336 // This is recovered from gcc output.
3337 return 1; // r1 is the dedicated stack pointer
3338 }
3339
3340 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07003341 llvm::Value *Address) const override;
Stephen Hines176edba2014-12-01 14:53:08 -08003342
3343 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3344 return 16; // Natural alignment for Altivec vectors.
3345 }
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003346};
3347
3348}
3349
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003350// Return true if the ABI requires Ty to be passed sign- or zero-
3351// extended to 64 bits.
3352bool
3353PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3354 // Treat an enum type as its underlying type.
3355 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3356 Ty = EnumTy->getDecl()->getIntegerType();
3357
3358 // Promotable integer types are required to be promoted by the ABI.
3359 if (Ty->isPromotableIntegerType())
3360 return true;
3361
3362 // In addition to the usual promotable integer types, we also need to
3363 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3364 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3365 switch (BT->getKind()) {
3366 case BuiltinType::Int:
3367 case BuiltinType::UInt:
3368 return true;
3369 default:
3370 break;
3371 }
3372
3373 return false;
3374}
3375
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003376/// isAlignedParamType - Determine whether a type requires 16-byte
3377/// alignment in the parameter area.
3378bool
3379PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3380 // Complex types are passed just like their elements.
3381 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3382 Ty = CTy->getElementType();
3383
3384 // Only vector types of size 16 bytes need alignment (larger types are
3385 // passed via reference, smaller types are not aligned).
3386 if (Ty->isVectorType())
3387 return getContext().getTypeSize(Ty) == 128;
3388
3389 // For single-element float/vector structs, we consider the whole type
3390 // to have the same alignment requirements as its single element.
3391 const Type *AlignAsType = nullptr;
3392 const Type *EltType = isSingleElementStruct(Ty, getContext());
3393 if (EltType) {
3394 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3395 if ((EltType->isVectorType() &&
3396 getContext().getTypeSize(EltType) == 128) ||
3397 (BT && BT->isFloatingPoint()))
3398 AlignAsType = EltType;
3399 }
3400
Stephen Hines176edba2014-12-01 14:53:08 -08003401 // Likewise for ELFv2 homogeneous aggregates.
3402 const Type *Base = nullptr;
3403 uint64_t Members = 0;
3404 if (!AlignAsType && Kind == ELFv2 &&
3405 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3406 AlignAsType = Base;
3407
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003408 // With special case aggregates, only vector base types need alignment.
3409 if (AlignAsType)
3410 return AlignAsType->isVectorType();
3411
3412 // Otherwise, we only need alignment for any aggregate type that
3413 // has an alignment requirement of >= 16 bytes.
3414 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3415 return true;
3416
3417 return false;
3418}
3419
Stephen Hines176edba2014-12-01 14:53:08 -08003420/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3421/// aggregate. Base is set to the base element type, and Members is set
3422/// to the number of base elements.
3423bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3424 uint64_t &Members) const {
3425 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3426 uint64_t NElements = AT->getSize().getZExtValue();
3427 if (NElements == 0)
3428 return false;
3429 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3430 return false;
3431 Members *= NElements;
3432 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3433 const RecordDecl *RD = RT->getDecl();
3434 if (RD->hasFlexibleArrayMember())
3435 return false;
3436
3437 Members = 0;
3438
3439 // If this is a C++ record, check the bases first.
3440 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3441 for (const auto &I : CXXRD->bases()) {
3442 // Ignore empty records.
3443 if (isEmptyRecord(getContext(), I.getType(), true))
3444 continue;
3445
3446 uint64_t FldMembers;
3447 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3448 return false;
3449
3450 Members += FldMembers;
3451 }
3452 }
3453
3454 for (const auto *FD : RD->fields()) {
3455 // Ignore (non-zero arrays of) empty records.
3456 QualType FT = FD->getType();
3457 while (const ConstantArrayType *AT =
3458 getContext().getAsConstantArrayType(FT)) {
3459 if (AT->getSize().getZExtValue() == 0)
3460 return false;
3461 FT = AT->getElementType();
3462 }
3463 if (isEmptyRecord(getContext(), FT, true))
3464 continue;
3465
3466 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3467 if (getContext().getLangOpts().CPlusPlus &&
3468 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3469 continue;
3470
3471 uint64_t FldMembers;
3472 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3473 return false;
3474
3475 Members = (RD->isUnion() ?
3476 std::max(Members, FldMembers) : Members + FldMembers);
3477 }
3478
3479 if (!Base)
3480 return false;
3481
3482 // Ensure there is no padding.
3483 if (getContext().getTypeSize(Base) * Members !=
3484 getContext().getTypeSize(Ty))
3485 return false;
3486 } else {
3487 Members = 1;
3488 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3489 Members = 2;
3490 Ty = CT->getElementType();
3491 }
3492
3493 // Most ABIs only support float, double, and some vector type widths.
3494 if (!isHomogeneousAggregateBaseType(Ty))
3495 return false;
3496
3497 // The base type must be the same for all members. Types that
3498 // agree in both total size and mode (float vs. vector) are
3499 // treated as being equivalent here.
3500 const Type *TyPtr = Ty.getTypePtr();
3501 if (!Base)
3502 Base = TyPtr;
3503
3504 if (Base->isVectorType() != TyPtr->isVectorType() ||
3505 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3506 return false;
3507 }
3508 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3509}
3510
3511bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3512 // Homogeneous aggregates for ELFv2 must have base types of float,
3513 // double, long double, or 128-bit vectors.
3514 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3515 if (BT->getKind() == BuiltinType::Float ||
3516 BT->getKind() == BuiltinType::Double ||
3517 BT->getKind() == BuiltinType::LongDouble)
3518 return true;
3519 }
3520 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3521 if (getContext().getTypeSize(VT) == 128)
3522 return true;
3523 }
3524 return false;
3525}
3526
3527bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3528 const Type *Base, uint64_t Members) const {
3529 // Vector types require one register, floating point types require one
3530 // or two registers depending on their size.
3531 uint32_t NumRegs =
3532 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
3533
3534 // Homogeneous Aggregates may occupy at most 8 registers.
3535 return Members * NumRegs <= 8;
3536}
3537
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003538ABIArgInfo
3539PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Stephen Hines176edba2014-12-01 14:53:08 -08003540 Ty = useFirstFieldIfTransparentUnion(Ty);
3541
Bill Schmidtc9715fc2012-11-27 02:46:43 +00003542 if (Ty->isAnyComplexType())
3543 return ABIArgInfo::getDirect();
3544
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003545 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3546 // or via reference (larger than 16 bytes).
3547 if (Ty->isVectorType()) {
3548 uint64_t Size = getContext().getTypeSize(Ty);
3549 if (Size > 128)
3550 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3551 else if (Size < 128) {
3552 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3553 return ABIArgInfo::getDirect(CoerceTy);
3554 }
3555 }
3556
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003557 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +00003558 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003559 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003560
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003561 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3562 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Stephen Hines176edba2014-12-01 14:53:08 -08003563
3564 // ELFv2 homogeneous aggregates are passed as array types.
3565 const Type *Base = nullptr;
3566 uint64_t Members = 0;
3567 if (Kind == ELFv2 &&
3568 isHomogeneousAggregate(Ty, Base, Members)) {
3569 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3570 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3571 return ABIArgInfo::getDirect(CoerceTy);
3572 }
3573
3574 // If an aggregate may end up fully in registers, we do not
3575 // use the ByVal method, but pass the aggregate as array.
3576 // This is usually beneficial since we avoid forcing the
3577 // back-end to store the argument to memory.
3578 uint64_t Bits = getContext().getTypeSize(Ty);
3579 if (Bits > 0 && Bits <= 8 * GPRBits) {
3580 llvm::Type *CoerceTy;
3581
3582 // Types up to 8 bytes are passed as integer type (which will be
3583 // properly aligned in the argument save area doubleword).
3584 if (Bits <= GPRBits)
3585 CoerceTy = llvm::IntegerType::get(getVMContext(),
3586 llvm::RoundUpToAlignment(Bits, 8));
3587 // Larger types are passed as arrays, with the base type selected
3588 // according to the required alignment in the save area.
3589 else {
3590 uint64_t RegBits = ABIAlign * 8;
3591 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3592 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3593 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3594 }
3595
3596 return ABIArgInfo::getDirect(CoerceTy);
3597 }
3598
3599 // All other aggregates are passed ByVal.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003600 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3601 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003602 }
3603
3604 return (isPromotableTypeForABI(Ty) ?
3605 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3606}
3607
3608ABIArgInfo
3609PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3610 if (RetTy->isVoidType())
3611 return ABIArgInfo::getIgnore();
3612
Bill Schmidt9e6111a2012-12-17 04:20:17 +00003613 if (RetTy->isAnyComplexType())
3614 return ABIArgInfo::getDirect();
3615
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003616 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3617 // or via reference (larger than 16 bytes).
3618 if (RetTy->isVectorType()) {
3619 uint64_t Size = getContext().getTypeSize(RetTy);
3620 if (Size > 128)
3621 return ABIArgInfo::getIndirect(0);
3622 else if (Size < 128) {
3623 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3624 return ABIArgInfo::getDirect(CoerceTy);
3625 }
3626 }
3627
Stephen Hines176edba2014-12-01 14:53:08 -08003628 if (isAggregateTypeForABI(RetTy)) {
3629 // ELFv2 homogeneous aggregates are returned as array types.
3630 const Type *Base = nullptr;
3631 uint64_t Members = 0;
3632 if (Kind == ELFv2 &&
3633 isHomogeneousAggregate(RetTy, Base, Members)) {
3634 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3635 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3636 return ABIArgInfo::getDirect(CoerceTy);
3637 }
3638
3639 // ELFv2 small aggregates are returned in up to two registers.
3640 uint64_t Bits = getContext().getTypeSize(RetTy);
3641 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3642 if (Bits == 0)
3643 return ABIArgInfo::getIgnore();
3644
3645 llvm::Type *CoerceTy;
3646 if (Bits > GPRBits) {
3647 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3648 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3649 } else
3650 CoerceTy = llvm::IntegerType::get(getVMContext(),
3651 llvm::RoundUpToAlignment(Bits, 8));
3652 return ABIArgInfo::getDirect(CoerceTy);
3653 }
3654
3655 // All other aggregates are returned indirectly.
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003656 return ABIArgInfo::getIndirect(0);
Stephen Hines176edba2014-12-01 14:53:08 -08003657 }
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00003658
3659 return (isPromotableTypeForABI(RetTy) ?
3660 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3661}
3662
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003663// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3664llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3665 QualType Ty,
3666 CodeGenFunction &CGF) const {
3667 llvm::Type *BP = CGF.Int8PtrTy;
3668 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3669
3670 CGBuilderTy &Builder = CGF.Builder;
3671 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3672 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3673
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003674 // Handle types that require 16-byte alignment in the parameter save area.
3675 if (isAlignedParamType(Ty)) {
3676 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3677 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3678 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3679 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3680 }
3681
Bill Schmidt19f8e852013-01-14 17:45:36 +00003682 // Update the va_list pointer. The pointer should be bumped by the
3683 // size of the object. We can trust getTypeSize() except for a complex
3684 // type whose base type is smaller than a doubleword. For these, the
3685 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003686 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt19f8e852013-01-14 17:45:36 +00003687 QualType BaseTy;
3688 unsigned CplxBaseSize = 0;
3689
3690 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3691 BaseTy = CTy->getElementType();
3692 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3693 if (CplxBaseSize < 8)
3694 SizeInBytes = 16;
3695 }
3696
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003697 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3698 llvm::Value *NextAddr =
3699 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3700 "ap.next");
3701 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3702
Bill Schmidt19f8e852013-01-14 17:45:36 +00003703 // If we have a complex type and the base type is smaller than 8 bytes,
3704 // the ABI calls for the real and imaginary parts to be right-adjusted
3705 // in separate doublewords. However, Clang expects us to produce a
3706 // pointer to a structure with the two parts packed tightly. So generate
3707 // loads of the real and imaginary parts relative to the va_list pointer,
3708 // and store them to a temporary structure.
3709 if (CplxBaseSize && CplxBaseSize < 8) {
3710 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3711 llvm::Value *ImagAddr = RealAddr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003712 if (CGF.CGM.getDataLayout().isBigEndian()) {
3713 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3714 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3715 } else {
3716 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3717 }
Bill Schmidt19f8e852013-01-14 17:45:36 +00003718 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3719 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3720 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3721 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3722 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3723 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3724 "vacplx");
3725 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3726 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3727 Builder.CreateStore(Real, RealPtr, false);
3728 Builder.CreateStore(Imag, ImagPtr, false);
3729 return Ptr;
3730 }
3731
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003732 // If the argument is smaller than 8 bytes, it is right-adjusted in
3733 // its doubleword slot. Adjust the pointer to pick it up from the
3734 // correct offset.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003735 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003736 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3737 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3738 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3739 }
3740
3741 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3742 return Builder.CreateBitCast(Addr, PTy);
3743}
3744
3745static bool
3746PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3747 llvm::Value *Address) {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00003748 // This is calculated from the LLVM and GCC tables and verified
3749 // against gcc output. AFAIK all ABIs use the same encoding.
3750
3751 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3752
3753 llvm::IntegerType *i8 = CGF.Int8Ty;
3754 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3755 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3756 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3757
3758 // 0-31: r0-31, the 8-byte general-purpose registers
3759 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3760
3761 // 32-63: fp0-31, the 8-byte floating-point registers
3762 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3763
3764 // 64-76 are various 4-byte special-purpose registers:
3765 // 64: mq
3766 // 65: lr
3767 // 66: ctr
3768 // 67: ap
3769 // 68-75 cr0-7
3770 // 76: xer
3771 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3772
3773 // 77-108: v0-31, the 16-byte vector registers
3774 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3775
3776 // 109: vrsave
3777 // 110: vscr
3778 // 111: spe_acc
3779 // 112: spefscr
3780 // 113: sfp
3781 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3782
3783 return false;
3784}
John McCallec853ba2010-03-11 00:10:12 +00003785
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003786bool
3787PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3788 CodeGen::CodeGenFunction &CGF,
3789 llvm::Value *Address) const {
3790
3791 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3792}
3793
3794bool
3795PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3796 llvm::Value *Address) const {
3797
3798 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3799}
3800
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003801//===----------------------------------------------------------------------===//
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003802// AArch64 ABI Implementation
Stephen Hines651f13c2014-04-23 16:59:28 -07003803//===----------------------------------------------------------------------===//
3804
3805namespace {
3806
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003807class AArch64ABIInfo : public ABIInfo {
Stephen Hines651f13c2014-04-23 16:59:28 -07003808public:
3809 enum ABIKind {
3810 AAPCS = 0,
3811 DarwinPCS
3812 };
3813
3814private:
3815 ABIKind Kind;
3816
3817public:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003818 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07003819
3820private:
3821 ABIKind getABIKind() const { return Kind; }
3822 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3823
3824 ABIArgInfo classifyReturnType(QualType RetTy) const;
3825 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3826 bool &IsHA, unsigned &AllocatedGPR,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003827 bool &IsSmallAggr, bool IsNamedArg) const;
Stephen Hines176edba2014-12-01 14:53:08 -08003828 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3829 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3830 uint64_t Members) const override;
3831
Stephen Hines651f13c2014-04-23 16:59:28 -07003832 bool isIllegalVectorType(QualType Ty) const;
3833
Stephen Hines176edba2014-12-01 14:53:08 -08003834 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines651f13c2014-04-23 16:59:28 -07003835 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3836 // number of SIMD and Floating-point registers allocated so far.
3837 // If the argument is an HFA or an HVA and there are sufficient unallocated
3838 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3839 // and Floating-point Registers (with one register per member of the HFA or
3840 // HVA). Otherwise, the NSRN is set to 8.
3841 unsigned AllocatedVFP = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003842
Stephen Hines651f13c2014-04-23 16:59:28 -07003843 // To correctly handle small aggregates, we need to keep track of the number
3844 // of GPRs allocated so far. If the small aggregate can't all fit into
3845 // registers, it will be on stack. We don't allow the aggregate to be
3846 // partially in registers.
3847 unsigned AllocatedGPR = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003848
3849 // Find the number of named arguments. Variadic arguments get special
3850 // treatment with the Darwin ABI.
Stephen Hines176edba2014-12-01 14:53:08 -08003851 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003852
3853 if (!getCXXABI().classifyReturnType(FI))
3854 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines176edba2014-12-01 14:53:08 -08003855 unsigned ArgNo = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -07003856 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Stephen Hines176edba2014-12-01 14:53:08 -08003857 it != ie; ++it, ++ArgNo) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003858 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3859 bool IsHA = false, IsSmallAggr = false;
3860 const unsigned NumVFPs = 8;
3861 const unsigned NumGPRs = 8;
Stephen Hines176edba2014-12-01 14:53:08 -08003862 bool IsNamedArg = ArgNo < NumRequiredArgs;
Stephen Hines651f13c2014-04-23 16:59:28 -07003863 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003864 AllocatedGPR, IsSmallAggr, IsNamedArg);
3865
3866 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3867 // as sequences of floats since they'll get "holes" inserted as
3868 // padding by the back end.
3869 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3870 getContext().getTypeAlign(it->type) < 64) {
3871 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3872 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
3873
3874 llvm::Type *CoerceTy = llvm::ArrayType::get(
3875 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3876 it->info = ABIArgInfo::getDirect(CoerceTy);
3877 }
3878
Stephen Hines651f13c2014-04-23 16:59:28 -07003879 // If we do not have enough VFP registers for the HA, any VFP registers
3880 // that are unallocated are marked as unavailable. To achieve this, we add
3881 // padding of (NumVFPs - PreAllocation) floats.
3882 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3883 llvm::Type *PaddingTy = llvm::ArrayType::get(
3884 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003885 it->info.setPaddingType(PaddingTy);
Stephen Hines651f13c2014-04-23 16:59:28 -07003886 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003887
Stephen Hines651f13c2014-04-23 16:59:28 -07003888 // If we do not have enough GPRs for the small aggregate, any GPR regs
3889 // that are unallocated are marked as unavailable.
3890 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3891 llvm::Type *PaddingTy = llvm::ArrayType::get(
3892 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3893 it->info =
3894 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3895 }
3896 }
3897 }
3898
3899 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3900 CodeGenFunction &CGF) const;
3901
3902 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3903 CodeGenFunction &CGF) const;
3904
3905 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Stephen Hines176edba2014-12-01 14:53:08 -08003906 CodeGenFunction &CGF) const override {
Stephen Hines651f13c2014-04-23 16:59:28 -07003907 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3908 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3909 }
3910};
3911
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003912class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines651f13c2014-04-23 16:59:28 -07003913public:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003914 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3915 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07003916
3917 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3918 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3919 }
3920
3921 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3922
3923 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3924};
3925}
3926
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003927ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3928 unsigned &AllocatedVFP,
3929 bool &IsHA,
3930 unsigned &AllocatedGPR,
3931 bool &IsSmallAggr,
3932 bool IsNamedArg) const {
Stephen Hines176edba2014-12-01 14:53:08 -08003933 Ty = useFirstFieldIfTransparentUnion(Ty);
3934
Stephen Hines651f13c2014-04-23 16:59:28 -07003935 // Handle illegal vector types here.
3936 if (isIllegalVectorType(Ty)) {
3937 uint64_t Size = getContext().getTypeSize(Ty);
Tim Murray9212d4f2014-08-15 16:00:15 -07003938 // Android promotes <2 x i8> to i16, not i32
3939 if (Size <= 16) {
3940 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
3941 AllocatedGPR++;
3942 return ABIArgInfo::getDirect(ResType);
3943 }
3944 if (Size == 32) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003945 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3946 AllocatedGPR++;
3947 return ABIArgInfo::getDirect(ResType);
3948 }
3949 if (Size == 64) {
3950 llvm::Type *ResType =
3951 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3952 AllocatedVFP++;
3953 return ABIArgInfo::getDirect(ResType);
3954 }
3955 if (Size == 128) {
3956 llvm::Type *ResType =
3957 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3958 AllocatedVFP++;
3959 return ABIArgInfo::getDirect(ResType);
3960 }
3961 AllocatedGPR++;
3962 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3963 }
3964 if (Ty->isVectorType())
3965 // Size of a legal vector should be either 64 or 128.
3966 AllocatedVFP++;
3967 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3968 if (BT->getKind() == BuiltinType::Half ||
3969 BT->getKind() == BuiltinType::Float ||
3970 BT->getKind() == BuiltinType::Double ||
3971 BT->getKind() == BuiltinType::LongDouble)
3972 AllocatedVFP++;
3973 }
3974
3975 if (!isAggregateTypeForABI(Ty)) {
3976 // Treat an enum type as its underlying type.
3977 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3978 Ty = EnumTy->getDecl()->getIntegerType();
3979
3980 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003981 unsigned Alignment = getContext().getTypeAlign(Ty);
3982 if (!isDarwinPCS() && Alignment > 64)
3983 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3984
Stephen Hines651f13c2014-04-23 16:59:28 -07003985 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3986 AllocatedGPR += RegsNeeded;
3987 }
3988 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3989 ? ABIArgInfo::getExtend()
3990 : ABIArgInfo::getDirect());
3991 }
3992
3993 // Structures with either a non-trivial destructor or a non-trivial
3994 // copy constructor are always indirect.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003995 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003996 AllocatedGPR++;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003997 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3998 CGCXXABI::RAA_DirectInMemory);
Stephen Hines651f13c2014-04-23 16:59:28 -07003999 }
4000
4001 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4002 // elsewhere for GNU compatibility.
4003 if (isEmptyRecord(getContext(), Ty, true)) {
4004 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4005 return ABIArgInfo::getIgnore();
4006
4007 ++AllocatedGPR;
4008 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4009 }
4010
4011 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004012 const Type *Base = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004013 uint64_t Members = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08004014 if (isHomogeneousAggregate(Ty, Base, Members)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004015 IsHA = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004016 if (!IsNamedArg && isDarwinPCS()) {
4017 // With the Darwin ABI, variadic arguments are always passed on the stack
4018 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
4019 uint64_t Size = getContext().getTypeSize(Ty);
4020 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
4021 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4022 }
4023 AllocatedVFP += Members;
Stephen Hines651f13c2014-04-23 16:59:28 -07004024 return ABIArgInfo::getExpand();
4025 }
4026
4027 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4028 uint64_t Size = getContext().getTypeSize(Ty);
4029 if (Size <= 128) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004030 unsigned Alignment = getContext().getTypeAlign(Ty);
4031 if (!isDarwinPCS() && Alignment > 64)
4032 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
4033
Stephen Hines651f13c2014-04-23 16:59:28 -07004034 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4035 AllocatedGPR += Size / 64;
4036 IsSmallAggr = true;
4037 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4038 // For aggregates with 16-byte alignment, we use i128.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004039 if (Alignment < 128 && Size == 128) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004040 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4041 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4042 }
4043 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4044 }
4045
4046 AllocatedGPR++;
4047 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4048}
4049
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004050ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07004051 if (RetTy->isVoidType())
4052 return ABIArgInfo::getIgnore();
4053
4054 // Large vector types should be returned via memory.
4055 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
4056 return ABIArgInfo::getIndirect(0);
4057
4058 if (!isAggregateTypeForABI(RetTy)) {
4059 // Treat an enum type as its underlying type.
4060 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4061 RetTy = EnumTy->getDecl()->getIntegerType();
4062
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004063 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4064 ? ABIArgInfo::getExtend()
4065 : ABIArgInfo::getDirect());
Stephen Hines651f13c2014-04-23 16:59:28 -07004066 }
4067
Stephen Hines651f13c2014-04-23 16:59:28 -07004068 if (isEmptyRecord(getContext(), RetTy, true))
4069 return ABIArgInfo::getIgnore();
4070
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004071 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08004072 uint64_t Members = 0;
4073 if (isHomogeneousAggregate(RetTy, Base, Members))
Stephen Hines651f13c2014-04-23 16:59:28 -07004074 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4075 return ABIArgInfo::getDirect();
4076
4077 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4078 uint64_t Size = getContext().getTypeSize(RetTy);
4079 if (Size <= 128) {
4080 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
4081 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4082 }
4083
4084 return ABIArgInfo::getIndirect(0);
4085}
4086
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004087/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4088bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07004089 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4090 // Check whether VT is legal.
4091 unsigned NumElements = VT->getNumElements();
4092 uint64_t Size = getContext().getTypeSize(VT);
4093 // NumElements should be power of 2 between 1 and 16.
4094 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4095 return true;
4096 return Size != 64 && (Size != 128 || NumElements == 1);
4097 }
4098 return false;
4099}
4100
Stephen Hines176edba2014-12-01 14:53:08 -08004101bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4102 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4103 // point type or a short-vector type. This is the same as the 32-bit ABI,
4104 // but with the difference that any floating-point type is allowed,
4105 // including __fp16.
4106 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4107 if (BT->isFloatingPoint())
4108 return true;
4109 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4110 unsigned VecSize = getContext().getTypeSize(VT);
4111 if (VecSize == 64 || VecSize == 128)
4112 return true;
4113 }
4114 return false;
4115}
4116
4117bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4118 uint64_t Members) const {
4119 return Members <= 4;
4120}
4121
4122llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
4123 CodeGenFunction &CGF) const {
4124 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4125 bool IsHA = false, IsSmallAggr = false;
4126 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4127 IsSmallAggr, false /*IsNamedArg*/);
4128 bool IsIndirect = AI.isIndirect();
4129
Stephen Hines651f13c2014-04-23 16:59:28 -07004130 // The AArch64 va_list type and handling is specified in the Procedure Call
4131 // Standard, section B.4:
4132 //
4133 // struct {
4134 // void *__stack;
4135 // void *__gr_top;
4136 // void *__vr_top;
4137 // int __gr_offs;
4138 // int __vr_offs;
4139 // };
4140
4141 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4142 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4143 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4144 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4145 auto &Ctx = CGF.getContext();
4146
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004147 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004148 int reg_top_index;
4149 int RegSize;
4150 if (AllocatedGPR) {
4151 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
4152 // 3 is the field number of __gr_offs
4153 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4154 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4155 reg_top_index = 1; // field number for __gr_top
4156 RegSize = 8 * AllocatedGPR;
4157 } else {
4158 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
4159 // 4 is the field number of __vr_offs.
4160 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4161 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4162 reg_top_index = 2; // field number for __vr_top
4163 RegSize = 16 * AllocatedVFP;
4164 }
4165
4166 //=======================================
4167 // Find out where argument was passed
4168 //=======================================
4169
4170 // If reg_offs >= 0 we're already using the stack for this type of
4171 // argument. We don't want to keep updating reg_offs (in case it overflows,
4172 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4173 // whatever they get).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004174 llvm::Value *UsingStack = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004175 UsingStack = CGF.Builder.CreateICmpSGE(
4176 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4177
4178 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4179
4180 // Otherwise, at least some kind of argument could go in these registers, the
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004181 // question is whether this particular type is too big.
Stephen Hines651f13c2014-04-23 16:59:28 -07004182 CGF.EmitBlock(MaybeRegBlock);
4183
4184 // Integer arguments may need to correct register alignment (for example a
4185 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4186 // align __gr_offs to calculate the potential address.
4187 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4188 int Align = Ctx.getTypeAlign(Ty) / 8;
4189
4190 reg_offs = CGF.Builder.CreateAdd(
4191 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4192 "align_regoffs");
4193 reg_offs = CGF.Builder.CreateAnd(
4194 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4195 "aligned_regoffs");
4196 }
4197
4198 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004199 llvm::Value *NewOffset = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004200 NewOffset = CGF.Builder.CreateAdd(
4201 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4202 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4203
4204 // Now we're in a position to decide whether this argument really was in
4205 // registers or not.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004206 llvm::Value *InRegs = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004207 InRegs = CGF.Builder.CreateICmpSLE(
4208 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4209
4210 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4211
4212 //=======================================
4213 // Argument was in registers
4214 //=======================================
4215
4216 // Now we emit the code for if the argument was originally passed in
4217 // registers. First start the appropriate block:
4218 CGF.EmitBlock(InRegBlock);
4219
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004220 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004221 reg_top_p =
4222 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4223 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4224 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004225 llvm::Value *RegAddr = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004226 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4227
4228 if (IsIndirect) {
4229 // If it's been passed indirectly (actually a struct), whatever we find from
4230 // stored registers or on the stack will actually be a struct **.
4231 MemTy = llvm::PointerType::getUnqual(MemTy);
4232 }
4233
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004234 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08004235 uint64_t NumMembers = 0;
4236 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004237 if (IsHFA && NumMembers > 1) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004238 // Homogeneous aggregates passed in registers will have their elements split
4239 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4240 // qN+1, ...). We reload and store into a temporary local variable
4241 // contiguously.
4242 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4243 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4244 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4245 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4246 int Offset = 0;
4247
4248 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4249 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4250 for (unsigned i = 0; i < NumMembers; ++i) {
4251 llvm::Value *BaseOffset =
4252 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4253 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4254 LoadAddr = CGF.Builder.CreateBitCast(
4255 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4256 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4257
4258 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4259 CGF.Builder.CreateStore(Elem, StoreAddr);
4260 }
4261
4262 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4263 } else {
4264 // Otherwise the object is contiguous in memory
4265 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004266 if (CGF.CGM.getDataLayout().isBigEndian() &&
4267 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07004268 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4269 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4270 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4271
4272 BaseAddr = CGF.Builder.CreateAdd(
4273 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4274
4275 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4276 }
4277
4278 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4279 }
4280
4281 CGF.EmitBranch(ContBlock);
4282
4283 //=======================================
4284 // Argument was on the stack
4285 //=======================================
4286 CGF.EmitBlock(OnStackBlock);
4287
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004288 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004289 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4290 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4291
4292 // Again, stack arguments may need realigmnent. In this case both integer and
4293 // floating-point ones might be affected.
4294 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4295 int Align = Ctx.getTypeAlign(Ty) / 8;
4296
4297 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4298
4299 OnStackAddr = CGF.Builder.CreateAdd(
4300 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4301 "align_stack");
4302 OnStackAddr = CGF.Builder.CreateAnd(
4303 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4304 "align_stack");
4305
4306 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4307 }
4308
4309 uint64_t StackSize;
4310 if (IsIndirect)
4311 StackSize = 8;
4312 else
4313 StackSize = Ctx.getTypeSize(Ty) / 8;
4314
4315 // All stack slots are 8 bytes
4316 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4317
4318 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4319 llvm::Value *NewStack =
4320 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4321
4322 // Write the new value of __stack for the next call to va_arg
4323 CGF.Builder.CreateStore(NewStack, stack_p);
4324
4325 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4326 Ctx.getTypeSize(Ty) < 64) {
4327 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4328 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4329
4330 OnStackAddr = CGF.Builder.CreateAdd(
4331 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4332
4333 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4334 }
4335
4336 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4337
4338 CGF.EmitBranch(ContBlock);
4339
4340 //=======================================
4341 // Tidy up
4342 //=======================================
4343 CGF.EmitBlock(ContBlock);
4344
4345 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4346 ResAddr->addIncoming(RegAddr, InRegBlock);
4347 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4348
4349 if (IsIndirect)
4350 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4351
4352 return ResAddr;
4353}
4354
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004355llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07004356 CodeGenFunction &CGF) const {
4357 // We do not support va_arg for aggregates or illegal vector types.
4358 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4359 // other cases.
4360 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004361 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004362
4363 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4364 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4365
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004366 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08004367 uint64_t Members = 0;
4368 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Stephen Hines651f13c2014-04-23 16:59:28 -07004369
4370 bool isIndirect = false;
4371 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4372 // be passed indirectly.
4373 if (Size > 16 && !isHA) {
4374 isIndirect = true;
4375 Size = 8;
4376 Align = 8;
4377 }
4378
4379 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4380 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4381
4382 CGBuilderTy &Builder = CGF.Builder;
4383 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4384 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4385
4386 if (isEmptyRecord(getContext(), Ty, true)) {
4387 // These are ignored for parameter passing purposes.
4388 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4389 return Builder.CreateBitCast(Addr, PTy);
4390 }
4391
4392 const uint64_t MinABIAlign = 8;
4393 if (Align > MinABIAlign) {
4394 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4395 Addr = Builder.CreateGEP(Addr, Offset);
4396 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4397 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4398 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4399 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4400 }
4401
4402 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4403 llvm::Value *NextAddr = Builder.CreateGEP(
4404 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4405 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4406
4407 if (isIndirect)
4408 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4409 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4410 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4411
4412 return AddrTyped;
4413}
4414
4415//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00004416// ARM ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004417//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00004418
4419namespace {
4420
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004421class ARMABIInfo : public ABIInfo {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004422public:
4423 enum ABIKind {
4424 APCS = 0,
4425 AAPCS = 1,
4426 AAPCS_VFP
4427 };
4428
4429private:
4430 ABIKind Kind;
Stephen Hines651f13c2014-04-23 16:59:28 -07004431 mutable int VFPRegs[16];
4432 const unsigned NumVFPs;
4433 const unsigned NumGPRs;
4434 mutable unsigned AllocatedGPRs;
4435 mutable unsigned AllocatedVFPs;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004436
4437public:
Stephen Hines651f13c2014-04-23 16:59:28 -07004438 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4439 NumVFPs(16), NumGPRs(4) {
John McCallbd7370a2013-02-28 19:01:20 +00004440 setRuntimeCC();
Stephen Hines651f13c2014-04-23 16:59:28 -07004441 resetAllocatedRegs();
John McCallbd7370a2013-02-28 19:01:20 +00004442 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004443
John McCall49e34be2011-08-30 01:42:09 +00004444 bool isEABI() const {
Stephen Hines651f13c2014-04-23 16:59:28 -07004445 switch (getTarget().getTriple().getEnvironment()) {
4446 case llvm::Triple::Android:
4447 case llvm::Triple::EABI:
4448 case llvm::Triple::EABIHF:
4449 case llvm::Triple::GNUEABI:
4450 case llvm::Triple::GNUEABIHF:
4451 return true;
4452 default:
4453 return false;
4454 }
4455 }
4456
4457 bool isEABIHF() const {
4458 switch (getTarget().getTriple().getEnvironment()) {
4459 case llvm::Triple::EABIHF:
4460 case llvm::Triple::GNUEABIHF:
4461 return true;
4462 default:
4463 return false;
4464 }
John McCall49e34be2011-08-30 01:42:09 +00004465 }
4466
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004467 ABIKind getABIKind() const { return Kind; }
4468
Tim Northover64eac852013-10-01 14:34:25 +00004469private:
Stephen Hines651f13c2014-04-23 16:59:28 -07004470 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004471 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Stephen Hines651f13c2014-04-23 16:59:28 -07004472 bool &IsCPRC) const;
Manman Ren97f81572012-10-16 19:18:39 +00004473 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004474
Stephen Hines176edba2014-12-01 14:53:08 -08004475 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4476 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4477 uint64_t Members) const override;
4478
Stephen Hines651f13c2014-04-23 16:59:28 -07004479 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004480
Stephen Hines651f13c2014-04-23 16:59:28 -07004481 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4482 CodeGenFunction &CGF) const override;
John McCallbd7370a2013-02-28 19:01:20 +00004483
4484 llvm::CallingConv::ID getLLVMDefaultCC() const;
4485 llvm::CallingConv::ID getABIDefaultCC() const;
4486 void setRuntimeCC();
Stephen Hines651f13c2014-04-23 16:59:28 -07004487
4488 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4489 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4490 void resetAllocatedRegs(void) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004491};
4492
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004493class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4494public:
Chris Lattnerea044322010-07-29 02:01:43 +00004495 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4496 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCall6374c332010-03-06 00:35:14 +00004497
John McCall49e34be2011-08-30 01:42:09 +00004498 const ARMABIInfo &getABIInfo() const {
4499 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4500 }
4501
Stephen Hines651f13c2014-04-23 16:59:28 -07004502 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCall6374c332010-03-06 00:35:14 +00004503 return 13;
4504 }
Roman Divacky09345d12011-05-18 19:36:54 +00004505
Stephen Hines651f13c2014-04-23 16:59:28 -07004506 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCallf85e1932011-06-15 23:02:42 +00004507 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4508 }
4509
Roman Divacky09345d12011-05-18 19:36:54 +00004510 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07004511 llvm::Value *Address) const override {
Chris Lattner8b418682012-02-07 00:39:47 +00004512 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divacky09345d12011-05-18 19:36:54 +00004513
4514 // 0-15 are the 16 integer registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004515 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divacky09345d12011-05-18 19:36:54 +00004516 return false;
4517 }
John McCall49e34be2011-08-30 01:42:09 +00004518
Stephen Hines651f13c2014-04-23 16:59:28 -07004519 unsigned getSizeOfUnwindException() const override {
John McCall49e34be2011-08-30 01:42:09 +00004520 if (getABIInfo().isEABI()) return 88;
4521 return TargetCodeGenInfo::getSizeOfUnwindException();
4522 }
Tim Northover64eac852013-10-01 14:34:25 +00004523
4524 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07004525 CodeGen::CodeGenModule &CGM) const override {
Tim Northover64eac852013-10-01 14:34:25 +00004526 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4527 if (!FD)
4528 return;
4529
4530 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4531 if (!Attr)
4532 return;
4533
4534 const char *Kind;
4535 switch (Attr->getInterrupt()) {
4536 case ARMInterruptAttr::Generic: Kind = ""; break;
4537 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4538 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4539 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4540 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4541 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4542 }
4543
4544 llvm::Function *Fn = cast<llvm::Function>(GV);
4545
4546 Fn->addFnAttr("interrupt", Kind);
4547
4548 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4549 return;
4550
4551 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4552 // however this is not necessarily true on taking any interrupt. Instruct
4553 // the backend to perform a realignment as part of the function prologue.
4554 llvm::AttrBuilder B;
4555 B.addStackAlignmentAttr(8);
4556 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4557 llvm::AttributeSet::get(CGM.getLLVMContext(),
4558 llvm::AttributeSet::FunctionIndex,
4559 B));
4560 }
4561
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004562};
4563
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00004564}
4565
Chris Lattneree5dcd02010-07-29 02:31:05 +00004566void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00004567 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Ren710c5172012-10-31 19:02:26 +00004568 // VFP registers allocated so far.
Manman Renb3fa55f2012-10-30 23:21:41 +00004569 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4570 // VFP registers of the appropriate type unallocated then the argument is
4571 // allocated to the lowest-numbered sequence of such registers.
4572 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4573 // unallocated are marked as unavailable.
Stephen Hines651f13c2014-04-23 16:59:28 -07004574 resetAllocatedRegs();
4575
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004576 if (getCXXABI().classifyReturnType(FI)) {
4577 if (FI.getReturnInfo().isIndirect())
4578 markAllocatedGPRs(1, 1);
4579 } else {
4580 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4581 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004582 for (auto &I : FI.arguments()) {
4583 unsigned PreAllocationVFPs = AllocatedVFPs;
4584 unsigned PreAllocationGPRs = AllocatedGPRs;
Stephen Hines651f13c2014-04-23 16:59:28 -07004585 bool IsCPRC = false;
Manman Renb3fa55f2012-10-30 23:21:41 +00004586 // 6.1.2.3 There is one VFP co-processor register class using registers
4587 // s0-s15 (d0-d7) for passing arguments.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004588 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Stephen Hines651f13c2014-04-23 16:59:28 -07004589
4590 // If we have allocated some arguments onto the stack (due to running
4591 // out of VFP registers), we cannot split an argument between GPRs and
4592 // the stack. If this situation occurs, we add padding to prevent the
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004593 // GPRs from being used. In this situation, the current argument could
Stephen Hines651f13c2014-04-23 16:59:28 -07004594 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4595 // unusable anyway.
Stephen Hines176edba2014-12-01 14:53:08 -08004596 // We do not have to do this if the argument is being passed ByVal, as the
4597 // backend can handle that situation correctly.
Stephen Hines651f13c2014-04-23 16:59:28 -07004598 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Stephen Hines176edba2014-12-01 14:53:08 -08004599 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4600 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4601 StackUsed && !IsByVal) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004602 llvm::Type *PaddingTy = llvm::ArrayType::get(
4603 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004604 if (I.info.canHaveCoerceToType()) {
Stephen Hines176edba2014-12-01 14:53:08 -08004605 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */,
4606 0 /* offset */, PaddingTy, true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004607 } else {
4608 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Stephen Hines176edba2014-12-01 14:53:08 -08004609 PaddingTy, true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004610 }
Manman Renb3fa55f2012-10-30 23:21:41 +00004611 }
4612 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004613
Anton Korobeynikov414d8962011-04-14 20:06:49 +00004614 // Always honor user-specified calling convention.
4615 if (FI.getCallingConvention() != llvm::CallingConv::C)
4616 return;
4617
John McCallbd7370a2013-02-28 19:01:20 +00004618 llvm::CallingConv::ID cc = getRuntimeCC();
4619 if (cc != llvm::CallingConv::C)
4620 FI.setEffectiveCallingConvention(cc);
4621}
Rafael Espindola25117ab2010-06-16 16:13:39 +00004622
John McCallbd7370a2013-02-28 19:01:20 +00004623/// Return the default calling convention that LLVM will use.
4624llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4625 // The default calling convention that LLVM will infer.
Stephen Hines651f13c2014-04-23 16:59:28 -07004626 if (isEABIHF())
John McCallbd7370a2013-02-28 19:01:20 +00004627 return llvm::CallingConv::ARM_AAPCS_VFP;
4628 else if (isEABI())
4629 return llvm::CallingConv::ARM_AAPCS;
4630 else
4631 return llvm::CallingConv::ARM_APCS;
4632}
4633
4634/// Return the calling convention that our ABI would like us to use
4635/// as the C calling convention.
4636llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004637 switch (getABIKind()) {
John McCallbd7370a2013-02-28 19:01:20 +00004638 case APCS: return llvm::CallingConv::ARM_APCS;
4639 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4640 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00004641 }
John McCallbd7370a2013-02-28 19:01:20 +00004642 llvm_unreachable("bad ABI kind");
4643}
4644
4645void ARMABIInfo::setRuntimeCC() {
4646 assert(getRuntimeCC() == llvm::CallingConv::C);
4647
4648 // Don't muddy up the IR with a ton of explicit annotations if
4649 // they'd just match what LLVM will infer from the triple.
4650 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4651 if (abiCC != getLLVMDefaultCC())
4652 RuntimeCC = abiCC;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004653}
4654
Manman Ren710c5172012-10-31 19:02:26 +00004655/// markAllocatedVFPs - update VFPRegs according to the alignment and
4656/// number of VFP registers (unit is S register) requested.
Stephen Hines651f13c2014-04-23 16:59:28 -07004657void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4658 unsigned NumRequired) const {
Manman Ren710c5172012-10-31 19:02:26 +00004659 // Early Exit.
Stephen Hines651f13c2014-04-23 16:59:28 -07004660 if (AllocatedVFPs >= 16) {
4661 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4662 // the stack.
4663 AllocatedVFPs = 17;
Manman Ren710c5172012-10-31 19:02:26 +00004664 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07004665 }
Manman Ren710c5172012-10-31 19:02:26 +00004666 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4667 // VFP registers of the appropriate type unallocated then the argument is
4668 // allocated to the lowest-numbered sequence of such registers.
4669 for (unsigned I = 0; I < 16; I += Alignment) {
4670 bool FoundSlot = true;
4671 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4672 if (J >= 16 || VFPRegs[J]) {
4673 FoundSlot = false;
4674 break;
4675 }
4676 if (FoundSlot) {
4677 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4678 VFPRegs[J] = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07004679 AllocatedVFPs += NumRequired;
Manman Ren710c5172012-10-31 19:02:26 +00004680 return;
4681 }
4682 }
4683 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4684 // unallocated are marked as unavailable.
4685 for (unsigned I = 0; I < 16; I++)
4686 VFPRegs[I] = 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07004687 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Ren710c5172012-10-31 19:02:26 +00004688}
4689
Stephen Hines651f13c2014-04-23 16:59:28 -07004690/// Update AllocatedGPRs to record the number of general purpose registers
4691/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4692/// this represents arguments being stored on the stack.
4693void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004694 unsigned NumRequired) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07004695 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4696
4697 if (Alignment == 2 && AllocatedGPRs & 0x1)
4698 AllocatedGPRs += 1;
4699
4700 AllocatedGPRs += NumRequired;
4701}
4702
4703void ARMABIInfo::resetAllocatedRegs(void) const {
4704 AllocatedGPRs = 0;
4705 AllocatedVFPs = 0;
4706 for (unsigned i = 0; i < NumVFPs; ++i)
4707 VFPRegs[i] = 0;
4708}
4709
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004710ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Stephen Hines651f13c2014-04-23 16:59:28 -07004711 bool &IsCPRC) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00004712 // We update number of allocated VFPs according to
4713 // 6.1.2.1 The following argument types are VFP CPRCs:
4714 // A single-precision floating-point type (including promoted
4715 // half-precision types); A double-precision floating-point type;
4716 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4717 // with a Base Type of a single- or double-precision floating-point type,
4718 // 64-bit containerized vectors or 128-bit containerized vectors with one
4719 // to four Elements.
Stephen Hines176edba2014-12-01 14:53:08 -08004720 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
4721
4722 Ty = useFirstFieldIfTransparentUnion(Ty);
Manman Renb3fa55f2012-10-30 23:21:41 +00004723
Manman Ren97f81572012-10-16 19:18:39 +00004724 // Handle illegal vector types here.
4725 if (isIllegalVectorType(Ty)) {
4726 uint64_t Size = getContext().getTypeSize(Ty);
4727 if (Size <= 32) {
4728 llvm::Type *ResType =
4729 llvm::Type::getInt32Ty(getVMContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07004730 markAllocatedGPRs(1, 1);
Manman Ren97f81572012-10-16 19:18:39 +00004731 return ABIArgInfo::getDirect(ResType);
4732 }
4733 if (Size == 64) {
4734 llvm::Type *ResType = llvm::VectorType::get(
4735 llvm::Type::getInt32Ty(getVMContext()), 2);
Stephen Hines651f13c2014-04-23 16:59:28 -07004736 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4737 markAllocatedGPRs(2, 2);
4738 } else {
4739 markAllocatedVFPs(2, 2);
4740 IsCPRC = true;
4741 }
Manman Ren97f81572012-10-16 19:18:39 +00004742 return ABIArgInfo::getDirect(ResType);
4743 }
4744 if (Size == 128) {
4745 llvm::Type *ResType = llvm::VectorType::get(
4746 llvm::Type::getInt32Ty(getVMContext()), 4);
Stephen Hines651f13c2014-04-23 16:59:28 -07004747 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4748 markAllocatedGPRs(2, 4);
4749 } else {
4750 markAllocatedVFPs(4, 4);
4751 IsCPRC = true;
4752 }
Manman Ren97f81572012-10-16 19:18:39 +00004753 return ABIArgInfo::getDirect(ResType);
4754 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004755 markAllocatedGPRs(1, 1);
Manman Ren97f81572012-10-16 19:18:39 +00004756 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4757 }
Manman Ren710c5172012-10-31 19:02:26 +00004758 // Update VFPRegs for legal vector types.
Stephen Hines651f13c2014-04-23 16:59:28 -07004759 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4760 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4761 uint64_t Size = getContext().getTypeSize(VT);
4762 // Size of a legal vector should be power of 2 and above 64.
4763 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4764 IsCPRC = true;
4765 }
Manman Renb3fa55f2012-10-30 23:21:41 +00004766 }
Manman Ren710c5172012-10-31 19:02:26 +00004767 // Update VFPRegs for floating point types.
Stephen Hines651f13c2014-04-23 16:59:28 -07004768 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4769 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4770 if (BT->getKind() == BuiltinType::Half ||
4771 BT->getKind() == BuiltinType::Float) {
4772 markAllocatedVFPs(1, 1);
4773 IsCPRC = true;
4774 }
4775 if (BT->getKind() == BuiltinType::Double ||
4776 BT->getKind() == BuiltinType::LongDouble) {
4777 markAllocatedVFPs(2, 2);
4778 IsCPRC = true;
4779 }
4780 }
Manman Renb3fa55f2012-10-30 23:21:41 +00004781 }
Manman Ren97f81572012-10-16 19:18:39 +00004782
John McCalld608cdb2010-08-22 10:59:02 +00004783 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004784 // Treat an enum type as its underlying type.
Stephen Hines651f13c2014-04-23 16:59:28 -07004785 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004786 Ty = EnumTy->getDecl()->getIntegerType();
Stephen Hines651f13c2014-04-23 16:59:28 -07004787 }
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004788
Stephen Hines651f13c2014-04-23 16:59:28 -07004789 unsigned Size = getContext().getTypeSize(Ty);
4790 if (!IsCPRC)
4791 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Stephen Hines176edba2014-12-01 14:53:08 -08004792 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4793 : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004794 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004795
Stephen Hines651f13c2014-04-23 16:59:28 -07004796 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4797 markAllocatedGPRs(1, 1);
Tim Northoverf5c3a252013-06-21 22:49:34 +00004798 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Stephen Hines651f13c2014-04-23 16:59:28 -07004799 }
Tim Northoverf5c3a252013-06-21 22:49:34 +00004800
Daniel Dunbar42025572009-09-14 21:54:03 +00004801 // Ignore empty records.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004802 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar42025572009-09-14 21:54:03 +00004803 return ABIArgInfo::getIgnore();
4804
Stephen Hines176edba2014-12-01 14:53:08 -08004805 if (IsEffectivelyAAPCS_VFP) {
Manman Renb3fa55f2012-10-30 23:21:41 +00004806 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4807 // into VFP registers.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004808 const Type *Base = nullptr;
Manman Renb3fa55f2012-10-30 23:21:41 +00004809 uint64_t Members = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08004810 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004811 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Renb3fa55f2012-10-30 23:21:41 +00004812 // Base can be a floating-point or a vector.
4813 if (Base->isVectorType()) {
4814 // ElementSize is in number of floats.
4815 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Stephen Hines651f13c2014-04-23 16:59:28 -07004816 markAllocatedVFPs(ElementSize,
Manman Rencb489dd2012-11-06 19:05:29 +00004817 Members * ElementSize);
Manman Renb3fa55f2012-10-30 23:21:41 +00004818 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Stephen Hines651f13c2014-04-23 16:59:28 -07004819 markAllocatedVFPs(1, Members);
Manman Renb3fa55f2012-10-30 23:21:41 +00004820 else {
4821 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4822 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Stephen Hines651f13c2014-04-23 16:59:28 -07004823 markAllocatedVFPs(2, Members * 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00004824 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004825 IsCPRC = true;
Stephen Hines176edba2014-12-01 14:53:08 -08004826 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00004827 }
Bob Wilson194f06a2011-08-03 05:58:22 +00004828 }
4829
Manman Ren634b3d22012-08-13 21:23:55 +00004830 // Support byval for ARM.
Manman Rencb489dd2012-11-06 19:05:29 +00004831 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4832 // most 8-byte. We realign the indirect argument if type alignment is bigger
4833 // than ABI alignment.
Manman Renfd1ba912012-11-05 22:42:46 +00004834 uint64_t ABIAlign = 4;
4835 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4836 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4837 getABIKind() == ARMABIInfo::AAPCS)
4838 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren885ad692012-11-06 04:58:01 +00004839 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004840 // Update Allocated GPRs. Since this is only used when the size of the
4841 // argument is greater than 64 bytes, this will always use up any available
4842 // registers (of which there are 4). We also don't care about getting the
4843 // alignment right, because general-purpose registers cannot be back-filled.
4844 markAllocatedGPRs(1, 4);
Stephen Hines651f13c2014-04-23 16:59:28 -07004845 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Rencb489dd2012-11-06 19:05:29 +00004846 /*Realign=*/TyAlign > ABIAlign);
Eli Friedman79f30982012-08-09 00:31:40 +00004847 }
4848
Daniel Dunbar8aa87c72010-09-23 01:54:28 +00004849 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2acc6e32011-07-18 04:24:23 +00004850 llvm::Type* ElemTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004851 unsigned SizeRegs;
Eli Friedman79f30982012-08-09 00:31:40 +00004852 // FIXME: Try to match the types of the arguments more accurately where
4853 // we can.
4854 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson53fc1a62011-08-01 23:39:04 +00004855 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4856 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Stephen Hines651f13c2014-04-23 16:59:28 -07004857 markAllocatedGPRs(1, SizeRegs);
Manman Ren78eb76e2012-06-25 22:04:00 +00004858 } else {
Manman Ren78eb76e2012-06-25 22:04:00 +00004859 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4860 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stephen Hines651f13c2014-04-23 16:59:28 -07004861 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastings67d097e2011-04-27 17:24:02 +00004862 }
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00004863
Stephen Hines176edba2014-12-01 14:53:08 -08004864 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004865}
4866
Chris Lattnera3c109b2010-07-29 02:16:43 +00004867static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar98303b92009-09-13 08:03:58 +00004868 llvm::LLVMContext &VMContext) {
4869 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4870 // is called integer-like if its size is less than or equal to one word, and
4871 // the offset of each of its addressable sub-fields is zero.
4872
4873 uint64_t Size = Context.getTypeSize(Ty);
4874
4875 // Check that the type fits in a word.
4876 if (Size > 32)
4877 return false;
4878
4879 // FIXME: Handle vector types!
4880 if (Ty->isVectorType())
4881 return false;
4882
Daniel Dunbarb0d58192009-09-14 02:20:34 +00004883 // Float types are never treated as "integer like".
4884 if (Ty->isRealFloatingType())
4885 return false;
4886
Daniel Dunbar98303b92009-09-13 08:03:58 +00004887 // If this is a builtin or pointer type then it is ok.
John McCall183700f2009-09-21 23:43:11 +00004888 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar98303b92009-09-13 08:03:58 +00004889 return true;
4890
Daniel Dunbar45815812010-02-01 23:31:26 +00004891 // Small complex integer types are "integer like".
4892 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4893 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004894
4895 // Single element and zero sized arrays should be allowed, by the definition
4896 // above, but they are not.
4897
4898 // Otherwise, it must be a record type.
4899 const RecordType *RT = Ty->getAs<RecordType>();
4900 if (!RT) return false;
4901
4902 // Ignore records with flexible arrays.
4903 const RecordDecl *RD = RT->getDecl();
4904 if (RD->hasFlexibleArrayMember())
4905 return false;
4906
4907 // Check that all sub-fields are at offset 0, and are themselves "integer
4908 // like".
4909 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4910
4911 bool HadField = false;
4912 unsigned idx = 0;
4913 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4914 i != e; ++i, ++idx) {
David Blaikie581deb32012-06-06 20:45:41 +00004915 const FieldDecl *FD = *i;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004916
Daniel Dunbar679855a2010-01-29 03:22:29 +00004917 // Bit-fields are not addressable, we only need to verify they are "integer
4918 // like". We still have to disallow a subsequent non-bitfield, for example:
4919 // struct { int : 0; int x }
4920 // is non-integer like according to gcc.
4921 if (FD->isBitField()) {
4922 if (!RD->isUnion())
4923 HadField = true;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004924
Daniel Dunbar679855a2010-01-29 03:22:29 +00004925 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4926 return false;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004927
Daniel Dunbar679855a2010-01-29 03:22:29 +00004928 continue;
Daniel Dunbar98303b92009-09-13 08:03:58 +00004929 }
4930
Daniel Dunbar679855a2010-01-29 03:22:29 +00004931 // Check if this field is at offset 0.
4932 if (Layout.getFieldOffset(idx) != 0)
4933 return false;
4934
Daniel Dunbar98303b92009-09-13 08:03:58 +00004935 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4936 return false;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00004937
Daniel Dunbar679855a2010-01-29 03:22:29 +00004938 // Only allow at most one field in a structure. This doesn't match the
4939 // wording above, but follows gcc in situations with a field following an
4940 // empty structure.
Daniel Dunbar98303b92009-09-13 08:03:58 +00004941 if (!RD->isUnion()) {
4942 if (HadField)
4943 return false;
4944
4945 HadField = true;
4946 }
4947 }
4948
4949 return true;
4950}
4951
Stephen Hines651f13c2014-04-23 16:59:28 -07004952ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4953 bool isVariadic) const {
Stephen Hines176edba2014-12-01 14:53:08 -08004954 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
4955
Daniel Dunbar98303b92009-09-13 08:03:58 +00004956 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004957 return ABIArgInfo::getIgnore();
Daniel Dunbar98303b92009-09-13 08:03:58 +00004958
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004959 // Large vector types should be returned via memory.
Stephen Hines651f13c2014-04-23 16:59:28 -07004960 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4961 markAllocatedGPRs(1, 1);
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004962 return ABIArgInfo::getIndirect(0);
Stephen Hines651f13c2014-04-23 16:59:28 -07004963 }
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00004964
John McCalld608cdb2010-08-22 10:59:02 +00004965 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004966 // Treat an enum type as its underlying type.
4967 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4968 RetTy = EnumTy->getDecl()->getIntegerType();
4969
Stephen Hines176edba2014-12-01 14:53:08 -08004970 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4971 : ABIArgInfo::getDirect();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00004972 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00004973
4974 // Are we following APCS?
4975 if (getABIKind() == APCS) {
Chris Lattnera3c109b2010-07-29 02:16:43 +00004976 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar98303b92009-09-13 08:03:58 +00004977 return ABIArgInfo::getIgnore();
4978
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00004979 // Complex types are all returned as packed integers.
4980 //
4981 // FIXME: Consider using 2 x vector types if the back end handles them
4982 // correctly.
4983 if (RetTy->isAnyComplexType())
Stephen Hines176edba2014-12-01 14:53:08 -08004984 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4985 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00004986
Daniel Dunbar98303b92009-09-13 08:03:58 +00004987 // Integer like structures are returned in r0.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004988 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar98303b92009-09-13 08:03:58 +00004989 // Return in the smallest viable integer type.
Chris Lattnera3c109b2010-07-29 02:16:43 +00004990 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar98303b92009-09-13 08:03:58 +00004991 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00004992 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00004993 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00004994 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4995 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00004996 }
4997
4998 // Otherwise return in memory.
Stephen Hines651f13c2014-04-23 16:59:28 -07004999 markAllocatedGPRs(1, 1);
Daniel Dunbar98303b92009-09-13 08:03:58 +00005000 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005001 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00005002
5003 // Otherwise this is an AAPCS variant.
5004
Chris Lattnera3c109b2010-07-29 02:16:43 +00005005 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar16a08082009-09-14 00:56:55 +00005006 return ABIArgInfo::getIgnore();
5007
Bob Wilson3b694fa2011-11-02 04:51:36 +00005008 // Check for homogeneous aggregates with AAPCS-VFP.
Stephen Hines176edba2014-12-01 14:53:08 -08005009 if (IsEffectivelyAAPCS_VFP) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005010 const Type *Base = nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -08005011 uint64_t Members;
5012 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00005013 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson3b694fa2011-11-02 04:51:36 +00005014 // Homogeneous Aggregates are returned directly.
Stephen Hines176edba2014-12-01 14:53:08 -08005015 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00005016 }
Bob Wilson3b694fa2011-11-02 04:51:36 +00005017 }
5018
Daniel Dunbar98303b92009-09-13 08:03:58 +00005019 // Aggregates <= 4 bytes are returned in r0; other aggregates
5020 // are returned indirectly.
Chris Lattnera3c109b2010-07-29 02:16:43 +00005021 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar16a08082009-09-14 00:56:55 +00005022 if (Size <= 32) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07005023 if (getDataLayout().isBigEndian())
5024 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
5025 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5026
Daniel Dunbar16a08082009-09-14 00:56:55 +00005027 // Return in the smallest viable integer type.
5028 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00005029 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00005030 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00005031 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5032 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00005033 }
5034
Stephen Hines651f13c2014-04-23 16:59:28 -07005035 markAllocatedGPRs(1, 1);
Daniel Dunbar98303b92009-09-13 08:03:58 +00005036 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005037}
5038
Manman Ren97f81572012-10-16 19:18:39 +00005039/// isIllegalVector - check whether Ty is an illegal vector type.
5040bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5041 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5042 // Check whether VT is legal.
5043 unsigned NumElements = VT->getNumElements();
Manman Ren97f81572012-10-16 19:18:39 +00005044 // NumElements should be power of 2.
Stephen Hinesc3c9d172013-01-15 23:50:35 -08005045 if (((NumElements & (NumElements - 1)) != 0) && NumElements != 3)
Manman Ren97f81572012-10-16 19:18:39 +00005046 return true;
Manman Ren97f81572012-10-16 19:18:39 +00005047 }
5048 return false;
5049}
5050
Stephen Hines176edba2014-12-01 14:53:08 -08005051bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5052 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5053 // double, or 64-bit or 128-bit vectors.
5054 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5055 if (BT->getKind() == BuiltinType::Float ||
5056 BT->getKind() == BuiltinType::Double ||
5057 BT->getKind() == BuiltinType::LongDouble)
5058 return true;
5059 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5060 unsigned VecSize = getContext().getTypeSize(VT);
5061 if (VecSize == 64 || VecSize == 128)
5062 return true;
5063 }
5064 return false;
5065}
5066
5067bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5068 uint64_t Members) const {
5069 return Members <= 4;
5070}
5071
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005072llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner77b89b82010-06-27 07:15:29 +00005073 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00005074 llvm::Type *BP = CGF.Int8PtrTy;
5075 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005076
5077 CGBuilderTy &Builder = CGF.Builder;
Chris Lattner8b418682012-02-07 00:39:47 +00005078 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005079 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rend105e732012-10-16 19:01:37 +00005080
Tim Northover373ac0a2013-06-21 23:05:33 +00005081 if (isEmptyRecord(getContext(), Ty, true)) {
5082 // These are ignored for parameter passing purposes.
5083 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5084 return Builder.CreateBitCast(Addr, PTy);
5085 }
5086
Manman Rend105e732012-10-16 19:01:37 +00005087 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindolae164c182011-08-02 22:33:37 +00005088 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Ren97f81572012-10-16 19:18:39 +00005089 bool IsIndirect = false;
Manman Rend105e732012-10-16 19:01:37 +00005090
5091 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5092 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren93371022012-10-16 19:51:48 +00005093 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5094 getABIKind() == ARMABIInfo::AAPCS)
5095 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5096 else
5097 TyAlign = 4;
Stephen Hinesc3c9d172013-01-15 23:50:35 -08005098 // Use indirect if size of the illegal vector is bigger than 32 bytes.
5099 if (isIllegalVectorType(Ty) && Size > 32) {
Manman Ren97f81572012-10-16 19:18:39 +00005100 IsIndirect = true;
5101 Size = 4;
5102 TyAlign = 4;
5103 }
Manman Rend105e732012-10-16 19:01:37 +00005104
5105 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindolae164c182011-08-02 22:33:37 +00005106 if (TyAlign > 4) {
5107 assert((TyAlign & (TyAlign - 1)) == 0 &&
5108 "Alignment is not power of 2!");
5109 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5110 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5111 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rend105e732012-10-16 19:01:37 +00005112 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindolae164c182011-08-02 22:33:37 +00005113 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005114
5115 uint64_t Offset =
Manman Rend105e732012-10-16 19:01:37 +00005116 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005117 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00005118 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005119 "ap.next");
5120 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5121
Manman Ren97f81572012-10-16 19:18:39 +00005122 if (IsIndirect)
5123 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren93371022012-10-16 19:51:48 +00005124 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rend105e732012-10-16 19:01:37 +00005125 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5126 // may not be correctly aligned for the vector type. We create an aligned
5127 // temporary space and copy the content over from ap.cur to the temporary
5128 // space. This is necessary if the natural alignment of the type is greater
5129 // than the ABI alignment.
5130 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5131 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5132 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5133 "var.align");
5134 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5135 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5136 Builder.CreateMemCpy(Dst, Src,
5137 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5138 TyAlign, false);
5139 Addr = AlignedTemp; //The content is in aligned location.
5140 }
5141 llvm::Type *PTy =
5142 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5143 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5144
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005145 return AddrTyped;
5146}
5147
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00005148namespace {
5149
Derek Schuff263366f2012-10-16 22:30:41 +00005150class NaClARMABIInfo : public ABIInfo {
5151 public:
5152 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5153 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07005154 void computeInfo(CGFunctionInfo &FI) const override;
5155 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5156 CodeGenFunction &CGF) const override;
Derek Schuff263366f2012-10-16 22:30:41 +00005157 private:
5158 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
5159 ARMABIInfo NInfo; // Used for everything else.
5160};
5161
5162class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
5163 public:
5164 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5165 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
5166};
5167
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00005168}
5169
Derek Schuff263366f2012-10-16 22:30:41 +00005170void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5171 if (FI.getASTCallingConvention() == CC_PnaclCall)
5172 PInfo.computeInfo(FI);
5173 else
5174 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
5175}
5176
5177llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5178 CodeGenFunction &CGF) const {
5179 // Always use the native convention; calling pnacl-style varargs functions
5180 // is unsupported.
5181 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
5182}
5183
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005184//===----------------------------------------------------------------------===//
Justin Holewinski2c585b92012-05-24 17:43:12 +00005185// NVPTX ABI Implementation
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005186//===----------------------------------------------------------------------===//
5187
5188namespace {
5189
Justin Holewinski2c585b92012-05-24 17:43:12 +00005190class NVPTXABIInfo : public ABIInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005191public:
Justin Holewinskidca8f332013-03-30 14:38:24 +00005192 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005193
5194 ABIArgInfo classifyReturnType(QualType RetTy) const;
5195 ABIArgInfo classifyArgumentType(QualType Ty) const;
5196
Stephen Hines651f13c2014-04-23 16:59:28 -07005197 void computeInfo(CGFunctionInfo &FI) const override;
5198 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5199 CodeGenFunction &CFG) const override;
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005200};
5201
Justin Holewinski2c585b92012-05-24 17:43:12 +00005202class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005203public:
Justin Holewinski2c585b92012-05-24 17:43:12 +00005204 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5205 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07005206
5207 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5208 CodeGen::CodeGenModule &M) const override;
Justin Holewinskidca8f332013-03-30 14:38:24 +00005209private:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005210 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5211 // resulting MDNode to the nvvm.annotations MDNode.
5212 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005213};
5214
Justin Holewinski2c585b92012-05-24 17:43:12 +00005215ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005216 if (RetTy->isVoidType())
5217 return ABIArgInfo::getIgnore();
Bill Wendling846ff9f2013-11-21 23:31:45 +00005218
5219 // note: this is different from default ABI
5220 if (!RetTy->isScalarType())
5221 return ABIArgInfo::getDirect();
5222
5223 // Treat an enum type as its underlying type.
5224 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5225 RetTy = EnumTy->getDecl()->getIntegerType();
5226
5227 return (RetTy->isPromotableIntegerType() ?
5228 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005229}
5230
Justin Holewinski2c585b92012-05-24 17:43:12 +00005231ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Bill Wendling846ff9f2013-11-21 23:31:45 +00005232 // Treat an enum type as its underlying type.
5233 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5234 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005235
Stephen Hines176edba2014-12-01 14:53:08 -08005236 // Return aggregates type as indirect by value
5237 if (isAggregateTypeForABI(Ty))
5238 return ABIArgInfo::getIndirect(0, /* byval */ true);
5239
Bill Wendling846ff9f2013-11-21 23:31:45 +00005240 return (Ty->isPromotableIntegerType() ?
5241 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005242}
5243
Justin Holewinski2c585b92012-05-24 17:43:12 +00005244void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005245 if (!getCXXABI().classifyReturnType(FI))
5246 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07005247 for (auto &I : FI.arguments())
5248 I.info = classifyArgumentType(I.type);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005249
5250 // Always honor user-specified calling convention.
5251 if (FI.getCallingConvention() != llvm::CallingConv::C)
5252 return;
5253
John McCallbd7370a2013-02-28 19:01:20 +00005254 FI.setEffectiveCallingConvention(getRuntimeCC());
5255}
5256
Justin Holewinski2c585b92012-05-24 17:43:12 +00005257llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5258 CodeGenFunction &CFG) const {
5259 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005260}
5261
Justin Holewinski2c585b92012-05-24 17:43:12 +00005262void NVPTXTargetCodeGenInfo::
5263SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5264 CodeGen::CodeGenModule &M) const{
Justin Holewinski818eafb2011-10-05 17:58:44 +00005265 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5266 if (!FD) return;
5267
5268 llvm::Function *F = cast<llvm::Function>(GV);
5269
5270 // Perform special handling in OpenCL mode
David Blaikie4e4d0842012-03-11 07:00:24 +00005271 if (M.getLangOpts().OpenCL) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005272 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00005273 // By default, all functions are device functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00005274 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005275 // OpenCL __kernel functions get kernel metadata
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005276 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5277 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski818eafb2011-10-05 17:58:44 +00005278 // And kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00005279 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski818eafb2011-10-05 17:58:44 +00005280 }
Peter Collingbourne744d90b2011-10-06 16:49:54 +00005281 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00005282
Peter Collingbourne744d90b2011-10-06 16:49:54 +00005283 // Perform special handling in CUDA mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00005284 if (M.getLangOpts().CUDA) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005285 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne744d90b2011-10-06 16:49:54 +00005286 // __global__ functions cannot be called from the device, we do not
5287 // need to set the noinline attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005288 if (FD->hasAttr<CUDAGlobalAttr>()) {
5289 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5290 addNVVMMetadata(F, "kernel", 1);
5291 }
5292 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5293 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5294 addNVVMMetadata(F, "maxntidx",
5295 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5296 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5297 // zero value from getMinBlocks either means it was not specified in
5298 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5299 // don't have to add a PTX directive.
5300 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5301 if (MinCTASM > 0) {
5302 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5303 addNVVMMetadata(F, "minctasm", MinCTASM);
5304 }
5305 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00005306 }
5307}
5308
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005309void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5310 int Operand) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00005311 llvm::Module *M = F->getParent();
5312 llvm::LLVMContext &Ctx = M->getContext();
5313
5314 // Get "nvvm.annotations" metadata node
5315 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5316
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005317 llvm::Value *MDVals[] = {
5318 F, llvm::MDString::get(Ctx, Name),
5319 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinskidca8f332013-03-30 14:38:24 +00005320 // Append metadata to nvvm.annotations
5321 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5322}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005323}
5324
5325//===----------------------------------------------------------------------===//
Ulrich Weigandb8409212013-05-06 16:26:41 +00005326// SystemZ ABI Implementation
5327//===----------------------------------------------------------------------===//
5328
5329namespace {
5330
5331class SystemZABIInfo : public ABIInfo {
5332public:
5333 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5334
5335 bool isPromotableIntegerType(QualType Ty) const;
5336 bool isCompoundType(QualType Ty) const;
5337 bool isFPArgumentType(QualType Ty) const;
5338
5339 ABIArgInfo classifyReturnType(QualType RetTy) const;
5340 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5341
Stephen Hines651f13c2014-04-23 16:59:28 -07005342 void computeInfo(CGFunctionInfo &FI) const override {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005343 if (!getCXXABI().classifyReturnType(FI))
5344 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07005345 for (auto &I : FI.arguments())
5346 I.info = classifyArgumentType(I.type);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005347 }
5348
Stephen Hines651f13c2014-04-23 16:59:28 -07005349 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5350 CodeGenFunction &CGF) const override;
Ulrich Weigandb8409212013-05-06 16:26:41 +00005351};
5352
5353class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5354public:
5355 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5356 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5357};
5358
5359}
5360
5361bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5362 // Treat an enum type as its underlying type.
5363 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5364 Ty = EnumTy->getDecl()->getIntegerType();
5365
5366 // Promotable integer types are required to be promoted by the ABI.
5367 if (Ty->isPromotableIntegerType())
5368 return true;
5369
5370 // 32-bit values must also be promoted.
5371 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5372 switch (BT->getKind()) {
5373 case BuiltinType::Int:
5374 case BuiltinType::UInt:
5375 return true;
5376 default:
5377 return false;
5378 }
5379 return false;
5380}
5381
5382bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5383 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5384}
5385
5386bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5387 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5388 switch (BT->getKind()) {
5389 case BuiltinType::Float:
5390 case BuiltinType::Double:
5391 return true;
5392 default:
5393 return false;
5394 }
5395
5396 if (const RecordType *RT = Ty->getAsStructureType()) {
5397 const RecordDecl *RD = RT->getDecl();
5398 bool Found = false;
5399
5400 // If this is a C++ record, check the bases first.
5401 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Stephen Hines651f13c2014-04-23 16:59:28 -07005402 for (const auto &I : CXXRD->bases()) {
5403 QualType Base = I.getType();
Ulrich Weigandb8409212013-05-06 16:26:41 +00005404
5405 // Empty bases don't affect things either way.
5406 if (isEmptyRecord(getContext(), Base, true))
5407 continue;
5408
5409 if (Found)
5410 return false;
5411 Found = isFPArgumentType(Base);
5412 if (!Found)
5413 return false;
5414 }
5415
5416 // Check the fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07005417 for (const auto *FD : RD->fields()) {
Ulrich Weigandb8409212013-05-06 16:26:41 +00005418 // Empty bitfields don't affect things either way.
5419 // Unlike isSingleElementStruct(), empty structure and array fields
5420 // do count. So do anonymous bitfields that aren't zero-sized.
5421 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5422 return true;
5423
5424 // Unlike isSingleElementStruct(), arrays do not count.
5425 // Nested isFPArgumentType structures still do though.
5426 if (Found)
5427 return false;
5428 Found = isFPArgumentType(FD->getType());
5429 if (!Found)
5430 return false;
5431 }
5432
5433 // Unlike isSingleElementStruct(), trailing padding is allowed.
5434 // An 8-byte aligned struct s { float f; } is passed as a double.
5435 return Found;
5436 }
5437
5438 return false;
5439}
5440
5441llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5442 CodeGenFunction &CGF) const {
5443 // Assume that va_list type is correct; should be pointer to LLVM type:
5444 // struct {
5445 // i64 __gpr;
5446 // i64 __fpr;
5447 // i8 *__overflow_arg_area;
5448 // i8 *__reg_save_area;
5449 // };
5450
5451 // Every argument occupies 8 bytes and is passed by preference in either
5452 // GPRs or FPRs.
5453 Ty = CGF.getContext().getCanonicalType(Ty);
5454 ABIArgInfo AI = classifyArgumentType(Ty);
5455 bool InFPRs = isFPArgumentType(Ty);
5456
5457 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5458 bool IsIndirect = AI.isIndirect();
5459 unsigned UnpaddedBitSize;
5460 if (IsIndirect) {
5461 APTy = llvm::PointerType::getUnqual(APTy);
5462 UnpaddedBitSize = 64;
5463 } else
5464 UnpaddedBitSize = getContext().getTypeSize(Ty);
5465 unsigned PaddedBitSize = 64;
5466 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5467
5468 unsigned PaddedSize = PaddedBitSize / 8;
5469 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5470
5471 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5472 if (InFPRs) {
5473 MaxRegs = 4; // Maximum of 4 FPR arguments
5474 RegCountField = 1; // __fpr
5475 RegSaveIndex = 16; // save offset for f0
5476 RegPadding = 0; // floats are passed in the high bits of an FPR
5477 } else {
5478 MaxRegs = 5; // Maximum of 5 GPR arguments
5479 RegCountField = 0; // __gpr
5480 RegSaveIndex = 2; // save offset for r2
5481 RegPadding = Padding; // values are passed in the low bits of a GPR
5482 }
5483
5484 llvm::Value *RegCountPtr =
5485 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5486 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5487 llvm::Type *IndexTy = RegCount->getType();
5488 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5489 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005490 "fits_in_regs");
Ulrich Weigandb8409212013-05-06 16:26:41 +00005491
5492 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5493 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5494 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5495 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5496
5497 // Emit code to load the value if it was passed in registers.
5498 CGF.EmitBlock(InRegBlock);
5499
5500 // Work out the address of an argument register.
5501 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5502 llvm::Value *ScaledRegCount =
5503 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5504 llvm::Value *RegBase =
5505 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5506 llvm::Value *RegOffset =
5507 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5508 llvm::Value *RegSaveAreaPtr =
5509 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5510 llvm::Value *RegSaveArea =
5511 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5512 llvm::Value *RawRegAddr =
5513 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5514 llvm::Value *RegAddr =
5515 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5516
5517 // Update the register count
5518 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5519 llvm::Value *NewRegCount =
5520 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5521 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5522 CGF.EmitBranch(ContBlock);
5523
5524 // Emit code to load the value if it was passed in memory.
5525 CGF.EmitBlock(InMemBlock);
5526
5527 // Work out the address of a stack argument.
5528 llvm::Value *OverflowArgAreaPtr =
5529 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5530 llvm::Value *OverflowArgArea =
5531 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5532 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5533 llvm::Value *RawMemAddr =
5534 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5535 llvm::Value *MemAddr =
5536 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5537
5538 // Update overflow_arg_area_ptr pointer
5539 llvm::Value *NewOverflowArgArea =
5540 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5541 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5542 CGF.EmitBranch(ContBlock);
5543
5544 // Return the appropriate result.
5545 CGF.EmitBlock(ContBlock);
5546 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5547 ResAddr->addIncoming(RegAddr, InRegBlock);
5548 ResAddr->addIncoming(MemAddr, InMemBlock);
5549
5550 if (IsIndirect)
5551 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5552
5553 return ResAddr;
5554}
5555
Ulrich Weigandb8409212013-05-06 16:26:41 +00005556ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5557 if (RetTy->isVoidType())
5558 return ABIArgInfo::getIgnore();
5559 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5560 return ABIArgInfo::getIndirect(0);
5561 return (isPromotableIntegerType(RetTy) ?
5562 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5563}
5564
5565ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5566 // Handle the generic C++ ABI.
Mark Lacey23630722013-10-06 01:33:34 +00005567 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigandb8409212013-05-06 16:26:41 +00005568 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5569
5570 // Integers and enums are extended to full register width.
5571 if (isPromotableIntegerType(Ty))
5572 return ABIArgInfo::getExtend();
5573
5574 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5575 uint64_t Size = getContext().getTypeSize(Ty);
5576 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandiford148a3522013-12-04 10:02:36 +00005577 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005578
5579 // Handle small structures.
5580 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5581 // Structures with flexible arrays have variable length, so really
5582 // fail the size test above.
5583 const RecordDecl *RD = RT->getDecl();
5584 if (RD->hasFlexibleArrayMember())
Richard Sandiford148a3522013-12-04 10:02:36 +00005585 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005586
5587 // The structure is passed as an unextended integer, a float, or a double.
5588 llvm::Type *PassTy;
5589 if (isFPArgumentType(Ty)) {
5590 assert(Size == 32 || Size == 64);
5591 if (Size == 32)
5592 PassTy = llvm::Type::getFloatTy(getVMContext());
5593 else
5594 PassTy = llvm::Type::getDoubleTy(getVMContext());
5595 } else
5596 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5597 return ABIArgInfo::getDirect(PassTy);
5598 }
5599
5600 // Non-structure compounds are passed indirectly.
5601 if (isCompoundType(Ty))
Richard Sandiford148a3522013-12-04 10:02:36 +00005602 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005603
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005604 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigandb8409212013-05-06 16:26:41 +00005605}
5606
5607//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005608// MSP430 ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005609//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005610
5611namespace {
5612
5613class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5614public:
Chris Lattnerea044322010-07-29 02:01:43 +00005615 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5616 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005617 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005618 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005619};
5620
5621}
5622
5623void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5624 llvm::GlobalValue *GV,
5625 CodeGen::CodeGenModule &M) const {
5626 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5627 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5628 // Handle 'interrupt' attribute:
5629 llvm::Function *F = cast<llvm::Function>(GV);
5630
5631 // Step 1: Set ISR calling convention.
5632 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5633
5634 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00005635 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005636
5637 // Step 3: Emit ISR vector alias.
Anton Korobeynikovf419a852012-11-26 18:59:10 +00005638 unsigned Num = attr->getNumber() / 2;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005639 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5640 "__isr_" + Twine(Num), F);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005641 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005642 }
5643}
5644
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005645//===----------------------------------------------------------------------===//
John McCallaeeb7012010-05-27 06:19:26 +00005646// MIPS ABI Implementation. This works for both little-endian and
5647// big-endian variants.
Chris Lattnerdce5ad02010-06-28 20:05:43 +00005648//===----------------------------------------------------------------------===//
5649
John McCallaeeb7012010-05-27 06:19:26 +00005650namespace {
Akira Hatanaka619e8872011-06-02 00:09:17 +00005651class MipsABIInfo : public ABIInfo {
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005652 bool IsO32;
Akira Hatanakac359f202012-07-03 19:24:06 +00005653 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5654 void CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00005655 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005656 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005657 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005658 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005659public:
Akira Hatanakab551dd32011-11-03 00:05:50 +00005660 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakac359f202012-07-03 19:24:06 +00005661 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
5662 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanaka619e8872011-06-02 00:09:17 +00005663
5664 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005665 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Stephen Hines651f13c2014-04-23 16:59:28 -07005666 void computeInfo(CGFunctionInfo &FI) const override;
5667 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5668 CodeGenFunction &CGF) const override;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005669};
5670
John McCallaeeb7012010-05-27 06:19:26 +00005671class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanakae624fa02011-09-20 18:23:28 +00005672 unsigned SizeOfUnwindException;
John McCallaeeb7012010-05-27 06:19:26 +00005673public:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00005674 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5675 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
5676 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCallaeeb7012010-05-27 06:19:26 +00005677
Stephen Hines651f13c2014-04-23 16:59:28 -07005678 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallaeeb7012010-05-27 06:19:26 +00005679 return 29;
5680 }
5681
Reed Kotler7dfd1822013-01-16 17:10:28 +00005682 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Stephen Hines651f13c2014-04-23 16:59:28 -07005683 CodeGen::CodeGenModule &CGM) const override {
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005684 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5685 if (!FD) return;
Rafael Espindolad8e6d6d2013-03-19 14:32:23 +00005686 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005687 if (FD->hasAttr<Mips16Attr>()) {
5688 Fn->addFnAttr("mips16");
5689 }
5690 else if (FD->hasAttr<NoMips16Attr>()) {
5691 Fn->addFnAttr("nomips16");
5692 }
Reed Kotler7dfd1822013-01-16 17:10:28 +00005693 }
Reed Kotlerad4b8b42013-03-13 20:40:30 +00005694
John McCallaeeb7012010-05-27 06:19:26 +00005695 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Stephen Hines651f13c2014-04-23 16:59:28 -07005696 llvm::Value *Address) const override;
John McCall49e34be2011-08-30 01:42:09 +00005697
Stephen Hines651f13c2014-04-23 16:59:28 -07005698 unsigned getSizeOfUnwindException() const override {
Akira Hatanakae624fa02011-09-20 18:23:28 +00005699 return SizeOfUnwindException;
John McCall49e34be2011-08-30 01:42:09 +00005700 }
John McCallaeeb7012010-05-27 06:19:26 +00005701};
5702}
5703
Akira Hatanakac359f202012-07-03 19:24:06 +00005704void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00005705 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00005706 llvm::IntegerType *IntTy =
5707 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005708
5709 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5710 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5711 ArgList.push_back(IntTy);
5712
5713 // If necessary, add one more integer type to ArgList.
5714 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5715
5716 if (R)
5717 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005718}
5719
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005720// In N32/64, an aligned double precision floating point field is passed in
5721// a register.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005722llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00005723 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5724
5725 if (IsO32) {
5726 CoerceToIntArgs(TySize, ArgList);
5727 return llvm::StructType::get(getVMContext(), ArgList);
5728 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005729
Akira Hatanaka2afd23d2012-01-12 00:52:17 +00005730 if (Ty->isComplexType())
5731 return CGT.ConvertType(Ty);
Akira Hatanaka6d1080f2012-01-10 23:12:19 +00005732
Akira Hatanakaa34e9212012-02-09 19:54:16 +00005733 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005734
Akira Hatanakac359f202012-07-03 19:24:06 +00005735 // Unions/vectors are passed in integer registers.
5736 if (!RT || !RT->isStructureOrClassType()) {
5737 CoerceToIntArgs(TySize, ArgList);
5738 return llvm::StructType::get(getVMContext(), ArgList);
5739 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005740
5741 const RecordDecl *RD = RT->getDecl();
5742 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005743 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005744
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005745 uint64_t LastOffset = 0;
5746 unsigned idx = 0;
5747 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5748
Akira Hatanakaa34e9212012-02-09 19:54:16 +00005749 // Iterate over fields in the struct/class and check if there are any aligned
5750 // double fields.
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005751 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5752 i != e; ++i, ++idx) {
David Blaikie262bc182012-04-30 02:36:29 +00005753 const QualType Ty = i->getType();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005754 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5755
5756 if (!BT || BT->getKind() != BuiltinType::Double)
5757 continue;
5758
5759 uint64_t Offset = Layout.getFieldOffset(idx);
5760 if (Offset % 64) // Ignore doubles that are not aligned.
5761 continue;
5762
5763 // Add ((Offset - LastOffset) / 64) args of type i64.
5764 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5765 ArgList.push_back(I64);
5766
5767 // Add double type.
5768 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5769 LastOffset = Offset + 64;
5770 }
5771
Akira Hatanakac359f202012-07-03 19:24:06 +00005772 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5773 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanakad5a257f2011-11-02 23:54:49 +00005774
5775 return llvm::StructType::get(getVMContext(), ArgList);
5776}
5777
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005778llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5779 uint64_t Offset) const {
5780 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005781 return nullptr;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005782
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005783 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005784}
Akira Hatanaka9659d592012-01-10 22:44:52 +00005785
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005786ABIArgInfo
5787MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005788 uint64_t OrigOffset = Offset;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005789 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005790 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005791
Akira Hatanakac359f202012-07-03 19:24:06 +00005792 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5793 (uint64_t)StackAlignInBytes);
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005794 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5795 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005796
Akira Hatanakac359f202012-07-03 19:24:06 +00005797 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanaka619e8872011-06-02 00:09:17 +00005798 // Ignore empty aggregates.
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005799 if (TySize == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00005800 return ABIArgInfo::getIgnore();
5801
Mark Lacey23630722013-10-06 01:33:34 +00005802 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005803 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005804 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00005805 }
Akira Hatanaka511949b2011-08-01 18:09:58 +00005806
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005807 // If we have reached here, aggregates are passed directly by coercing to
5808 // another structure type. Padding is inserted if the offset of the
5809 // aggregate is unaligned.
Stephen Hines176edba2014-12-01 14:53:08 -08005810 ABIArgInfo ArgInfo =
5811 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5812 getPaddingType(OrigOffset, CurrOffset));
5813 ArgInfo.setInReg(true);
5814 return ArgInfo;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005815 }
5816
5817 // Treat an enum type as its underlying type.
5818 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5819 Ty = EnumTy->getDecl()->getIntegerType();
5820
Stephen Hines176edba2014-12-01 14:53:08 -08005821 // All integral types are promoted to the GPR width.
5822 if (Ty->isIntegralOrEnumerationType())
Akira Hatanakaa33fd392012-01-09 19:31:25 +00005823 return ABIArgInfo::getExtend();
5824
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00005825 return ABIArgInfo::getDirect(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005826 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00005827}
5828
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005829llvm::Type*
5830MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakada54ff32012-02-09 18:49:26 +00005831 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakac359f202012-07-03 19:24:06 +00005832 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005833
Akira Hatanakada54ff32012-02-09 18:49:26 +00005834 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005835 const RecordDecl *RD = RT->getDecl();
Akira Hatanakada54ff32012-02-09 18:49:26 +00005836 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5837 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005838
Akira Hatanakada54ff32012-02-09 18:49:26 +00005839 // N32/64 returns struct/classes in floating point registers if the
5840 // following conditions are met:
5841 // 1. The size of the struct/class is no larger than 128-bit.
5842 // 2. The struct/class has one or two fields all of which are floating
5843 // point types.
5844 // 3. The offset of the first field is zero (this follows what gcc does).
5845 //
5846 // Any other composite results are returned in integer registers.
5847 //
5848 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5849 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5850 for (; b != e; ++b) {
David Blaikie262bc182012-04-30 02:36:29 +00005851 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005852
Akira Hatanakada54ff32012-02-09 18:49:26 +00005853 if (!BT || !BT->isFloatingPoint())
5854 break;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005855
David Blaikie262bc182012-04-30 02:36:29 +00005856 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakada54ff32012-02-09 18:49:26 +00005857 }
5858
5859 if (b == e)
5860 return llvm::StructType::get(getVMContext(), RTList,
5861 RD->hasAttr<PackedAttr>());
5862
5863 RTList.clear();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005864 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005865 }
5866
Akira Hatanakac359f202012-07-03 19:24:06 +00005867 CoerceToIntArgs(Size, RTList);
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005868 return llvm::StructType::get(getVMContext(), RTList);
5869}
5870
Akira Hatanaka619e8872011-06-02 00:09:17 +00005871ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanakaa8536c02012-01-23 23:18:57 +00005872 uint64_t Size = getContext().getTypeSize(RetTy);
5873
Stephen Hines176edba2014-12-01 14:53:08 -08005874 if (RetTy->isVoidType())
5875 return ABIArgInfo::getIgnore();
5876
5877 // O32 doesn't treat zero-sized structs differently from other structs.
5878 // However, N32/N64 ignores zero sized return values.
5879 if (!IsO32 && Size == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00005880 return ABIArgInfo::getIgnore();
5881
Akira Hatanaka8aeb1472012-05-11 21:01:17 +00005882 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005883 if (Size <= 128) {
5884 if (RetTy->isAnyComplexType())
5885 return ABIArgInfo::getDirect();
5886
Stephen Hines176edba2014-12-01 14:53:08 -08005887 // O32 returns integer vectors in registers and N32/N64 returns all small
5888 // aggregates in registers.
5889 if (!IsO32 ||
5890 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5891 ABIArgInfo ArgInfo =
5892 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5893 ArgInfo.setInReg(true);
5894 return ArgInfo;
5895 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00005896 }
Akira Hatanaka619e8872011-06-02 00:09:17 +00005897
5898 return ABIArgInfo::getIndirect(0);
5899 }
5900
5901 // Treat an enum type as its underlying type.
5902 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5903 RetTy = EnumTy->getDecl()->getIntegerType();
5904
5905 return (RetTy->isPromotableIntegerType() ?
5906 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5907}
5908
5909void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakacc662542012-01-12 01:10:09 +00005910 ABIArgInfo &RetInfo = FI.getReturnInfo();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005911 if (!getCXXABI().classifyReturnType(FI))
5912 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanakacc662542012-01-12 01:10:09 +00005913
5914 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00005915 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanakacc662542012-01-12 01:10:09 +00005916
Stephen Hines651f13c2014-04-23 16:59:28 -07005917 for (auto &I : FI.arguments())
5918 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanaka619e8872011-06-02 00:09:17 +00005919}
5920
5921llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5922 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00005923 llvm::Type *BP = CGF.Int8PtrTy;
5924 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Stephen Hines176edba2014-12-01 14:53:08 -08005925
5926 // Integer arguments are promoted 32-bit on O32 and 64-bit on N32/N64.
5927 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
5928 if (Ty->isIntegerType() &&
5929 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) {
5930 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5931 Ty->isSignedIntegerType());
5932 }
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005933
5934 CGBuilderTy &Builder = CGF.Builder;
5935 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5936 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Stephen Hines176edba2014-12-01 14:53:08 -08005937 int64_t TypeAlign =
5938 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005939 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5940 llvm::Value *AddrTyped;
John McCall64aa4b32013-04-16 22:48:15 +00005941 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005942 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005943
5944 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005945 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5946 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5947 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5948 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005949 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5950 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5951 }
5952 else
5953 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5954
5955 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005956 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Stephen Hines176edba2014-12-01 14:53:08 -08005957 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5958 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005959 llvm::Value *NextAddr =
Akira Hatanaka8f675e42012-01-23 23:59:52 +00005960 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakac35e69d2011-08-01 20:48:01 +00005961 "ap.next");
5962 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5963
5964 return AddrTyped;
Akira Hatanaka619e8872011-06-02 00:09:17 +00005965}
5966
John McCallaeeb7012010-05-27 06:19:26 +00005967bool
5968MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5969 llvm::Value *Address) const {
5970 // This information comes from gcc's implementation, which seems to
5971 // as canonical as it gets.
5972
John McCallaeeb7012010-05-27 06:19:26 +00005973 // Everything on MIPS is 4 bytes. Double-precision FP registers
5974 // are aliased to pairs of single-precision FP registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005975 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCallaeeb7012010-05-27 06:19:26 +00005976
5977 // 0-31 are the general purpose registers, $0 - $31.
5978 // 32-63 are the floating-point registers, $f0 - $f31.
5979 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5980 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattner8b418682012-02-07 00:39:47 +00005981 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCallaeeb7012010-05-27 06:19:26 +00005982
5983 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5984 // They are one bit wide and ignored here.
5985
5986 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5987 // (coprocessor 1 is the FP unit)
5988 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5989 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5990 // 176-181 are the DSP accumulator registers.
Chris Lattner8b418682012-02-07 00:39:47 +00005991 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCallaeeb7012010-05-27 06:19:26 +00005992 return false;
5993}
5994
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005995//===----------------------------------------------------------------------===//
5996// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5997// Currently subclassed only to implement custom OpenCL C function attribute
5998// handling.
5999//===----------------------------------------------------------------------===//
6000
6001namespace {
6002
6003class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6004public:
6005 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6006 : DefaultTargetCodeGenInfo(CGT) {}
6007
Stephen Hines651f13c2014-04-23 16:59:28 -07006008 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6009 CodeGen::CodeGenModule &M) const override;
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00006010};
6011
6012void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
6013 llvm::GlobalValue *GV,
6014 CodeGen::CodeGenModule &M) const {
6015 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6016 if (!FD) return;
6017
6018 llvm::Function *F = cast<llvm::Function>(GV);
6019
David Blaikie4e4d0842012-03-11 07:00:24 +00006020 if (M.getLangOpts().OpenCL) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00006021 if (FD->hasAttr<OpenCLKernelAttr>()) {
6022 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00006023 F->addFnAttr(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -07006024 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6025 if (Attr) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00006026 // Convert the reqd_work_group_size() attributes to metadata.
6027 llvm::LLVMContext &Context = F->getContext();
6028 llvm::NamedMDNode *OpenCLMetadata =
6029 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
6030
6031 SmallVector<llvm::Value*, 5> Operands;
6032 Operands.push_back(F);
6033
Chris Lattner8b418682012-02-07 00:39:47 +00006034 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07006035 llvm::APInt(32, Attr->getXDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00006036 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07006037 llvm::APInt(32, Attr->getYDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00006038 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07006039 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00006040
6041 // Add a boolean constant operand for "required" (true) or "hint" (false)
6042 // for implementing the work_group_size_hint attr later. Currently
6043 // always true as the hint is not yet implemented.
Chris Lattner8b418682012-02-07 00:39:47 +00006044 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00006045 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6046 }
6047 }
6048 }
6049}
6050
6051}
John McCallaeeb7012010-05-27 06:19:26 +00006052
Tony Linthicum96319392011-12-12 21:14:55 +00006053//===----------------------------------------------------------------------===//
6054// Hexagon ABI Implementation
6055//===----------------------------------------------------------------------===//
6056
6057namespace {
6058
6059class HexagonABIInfo : public ABIInfo {
6060
6061
6062public:
6063 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6064
6065private:
6066
6067 ABIArgInfo classifyReturnType(QualType RetTy) const;
6068 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6069
Stephen Hines651f13c2014-04-23 16:59:28 -07006070 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum96319392011-12-12 21:14:55 +00006071
Stephen Hines651f13c2014-04-23 16:59:28 -07006072 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6073 CodeGenFunction &CGF) const override;
Tony Linthicum96319392011-12-12 21:14:55 +00006074};
6075
6076class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6077public:
6078 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6079 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6080
Stephen Hines651f13c2014-04-23 16:59:28 -07006081 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum96319392011-12-12 21:14:55 +00006082 return 29;
6083 }
6084};
6085
6086}
6087
6088void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006089 if (!getCXXABI().classifyReturnType(FI))
6090 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Stephen Hines651f13c2014-04-23 16:59:28 -07006091 for (auto &I : FI.arguments())
6092 I.info = classifyArgumentType(I.type);
Tony Linthicum96319392011-12-12 21:14:55 +00006093}
6094
6095ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6096 if (!isAggregateTypeForABI(Ty)) {
6097 // Treat an enum type as its underlying type.
6098 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6099 Ty = EnumTy->getDecl()->getIntegerType();
6100
6101 return (Ty->isPromotableIntegerType() ?
6102 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6103 }
6104
6105 // Ignore empty records.
6106 if (isEmptyRecord(getContext(), Ty, true))
6107 return ABIArgInfo::getIgnore();
6108
Mark Lacey23630722013-10-06 01:33:34 +00006109 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00006110 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum96319392011-12-12 21:14:55 +00006111
6112 uint64_t Size = getContext().getTypeSize(Ty);
6113 if (Size > 64)
6114 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6115 // Pass in the smallest viable integer type.
6116 else if (Size > 32)
6117 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6118 else if (Size > 16)
6119 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6120 else if (Size > 8)
6121 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6122 else
6123 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6124}
6125
6126ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6127 if (RetTy->isVoidType())
6128 return ABIArgInfo::getIgnore();
6129
6130 // Large vector types should be returned via memory.
6131 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6132 return ABIArgInfo::getIndirect(0);
6133
6134 if (!isAggregateTypeForABI(RetTy)) {
6135 // Treat an enum type as its underlying type.
6136 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6137 RetTy = EnumTy->getDecl()->getIntegerType();
6138
6139 return (RetTy->isPromotableIntegerType() ?
6140 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6141 }
6142
Tony Linthicum96319392011-12-12 21:14:55 +00006143 if (isEmptyRecord(getContext(), RetTy, true))
6144 return ABIArgInfo::getIgnore();
6145
6146 // Aggregates <= 8 bytes are returned in r0; other aggregates
6147 // are returned indirectly.
6148 uint64_t Size = getContext().getTypeSize(RetTy);
6149 if (Size <= 64) {
6150 // Return in the smallest viable integer type.
6151 if (Size <= 8)
6152 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6153 if (Size <= 16)
6154 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6155 if (Size <= 32)
6156 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6157 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6158 }
6159
6160 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6161}
6162
6163llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner8b418682012-02-07 00:39:47 +00006164 CodeGenFunction &CGF) const {
Tony Linthicum96319392011-12-12 21:14:55 +00006165 // FIXME: Need to handle alignment
Chris Lattner8b418682012-02-07 00:39:47 +00006166 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum96319392011-12-12 21:14:55 +00006167
6168 CGBuilderTy &Builder = CGF.Builder;
6169 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6170 "ap");
6171 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6172 llvm::Type *PTy =
6173 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6174 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6175
6176 uint64_t Offset =
6177 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6178 llvm::Value *NextAddr =
6179 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6180 "ap.next");
6181 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6182
6183 return AddrTyped;
6184}
6185
6186
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006187//===----------------------------------------------------------------------===//
6188// SPARC v9 ABI Implementation.
6189// Based on the SPARC Compliance Definition version 2.4.1.
6190//
6191// Function arguments a mapped to a nominal "parameter array" and promoted to
6192// registers depending on their type. Each argument occupies 8 or 16 bytes in
6193// the array, structs larger than 16 bytes are passed indirectly.
6194//
6195// One case requires special care:
6196//
6197// struct mixed {
6198// int i;
6199// float f;
6200// };
6201//
6202// When a struct mixed is passed by value, it only occupies 8 bytes in the
6203// parameter array, but the int is passed in an integer register, and the float
6204// is passed in a floating point register. This is represented as two arguments
6205// with the LLVM IR inreg attribute:
6206//
6207// declare void f(i32 inreg %i, float inreg %f)
6208//
6209// The code generator will only allocate 4 bytes from the parameter array for
6210// the inreg arguments. All other arguments are allocated a multiple of 8
6211// bytes.
6212//
6213namespace {
6214class SparcV9ABIInfo : public ABIInfo {
6215public:
6216 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6217
6218private:
6219 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Stephen Hines651f13c2014-04-23 16:59:28 -07006220 void computeInfo(CGFunctionInfo &FI) const override;
6221 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6222 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00006223
6224 // Coercion type builder for structs passed in registers. The coercion type
6225 // serves two purposes:
6226 //
6227 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6228 // in registers.
6229 // 2. Expose aligned floating point elements as first-level elements, so the
6230 // code generator knows to pass them in floating point registers.
6231 //
6232 // We also compute the InReg flag which indicates that the struct contains
6233 // aligned 32-bit floats.
6234 //
6235 struct CoerceBuilder {
6236 llvm::LLVMContext &Context;
6237 const llvm::DataLayout &DL;
6238 SmallVector<llvm::Type*, 8> Elems;
6239 uint64_t Size;
6240 bool InReg;
6241
6242 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6243 : Context(c), DL(dl), Size(0), InReg(false) {}
6244
6245 // Pad Elems with integers until Size is ToSize.
6246 void pad(uint64_t ToSize) {
6247 assert(ToSize >= Size && "Cannot remove elements");
6248 if (ToSize == Size)
6249 return;
6250
6251 // Finish the current 64-bit word.
6252 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6253 if (Aligned > Size && Aligned <= ToSize) {
6254 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6255 Size = Aligned;
6256 }
6257
6258 // Add whole 64-bit words.
6259 while (Size + 64 <= ToSize) {
6260 Elems.push_back(llvm::Type::getInt64Ty(Context));
6261 Size += 64;
6262 }
6263
6264 // Final in-word padding.
6265 if (Size < ToSize) {
6266 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6267 Size = ToSize;
6268 }
6269 }
6270
6271 // Add a floating point element at Offset.
6272 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6273 // Unaligned floats are treated as integers.
6274 if (Offset % Bits)
6275 return;
6276 // The InReg flag is only required if there are any floats < 64 bits.
6277 if (Bits < 64)
6278 InReg = true;
6279 pad(Offset);
6280 Elems.push_back(Ty);
6281 Size = Offset + Bits;
6282 }
6283
6284 // Add a struct type to the coercion type, starting at Offset (in bits).
6285 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6286 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6287 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6288 llvm::Type *ElemTy = StrTy->getElementType(i);
6289 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6290 switch (ElemTy->getTypeID()) {
6291 case llvm::Type::StructTyID:
6292 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6293 break;
6294 case llvm::Type::FloatTyID:
6295 addFloat(ElemOffset, ElemTy, 32);
6296 break;
6297 case llvm::Type::DoubleTyID:
6298 addFloat(ElemOffset, ElemTy, 64);
6299 break;
6300 case llvm::Type::FP128TyID:
6301 addFloat(ElemOffset, ElemTy, 128);
6302 break;
6303 case llvm::Type::PointerTyID:
6304 if (ElemOffset % 64 == 0) {
6305 pad(ElemOffset);
6306 Elems.push_back(ElemTy);
6307 Size += 64;
6308 }
6309 break;
6310 default:
6311 break;
6312 }
6313 }
6314 }
6315
6316 // Check if Ty is a usable substitute for the coercion type.
6317 bool isUsableType(llvm::StructType *Ty) const {
6318 if (Ty->getNumElements() != Elems.size())
6319 return false;
6320 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6321 if (Elems[i] != Ty->getElementType(i))
6322 return false;
6323 return true;
6324 }
6325
6326 // Get the coercion type as a literal struct type.
6327 llvm::Type *getType() const {
6328 if (Elems.size() == 1)
6329 return Elems.front();
6330 else
6331 return llvm::StructType::get(Context, Elems);
6332 }
6333 };
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006334};
6335} // end anonymous namespace
6336
6337ABIArgInfo
6338SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6339 if (Ty->isVoidType())
6340 return ABIArgInfo::getIgnore();
6341
6342 uint64_t Size = getContext().getTypeSize(Ty);
6343
6344 // Anything too big to fit in registers is passed with an explicit indirect
6345 // pointer / sret pointer.
6346 if (Size > SizeLimit)
6347 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6348
6349 // Treat an enum type as its underlying type.
6350 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6351 Ty = EnumTy->getDecl()->getIntegerType();
6352
6353 // Integer types smaller than a register are extended.
6354 if (Size < 64 && Ty->isIntegerType())
6355 return ABIArgInfo::getExtend();
6356
6357 // Other non-aggregates go in registers.
6358 if (!isAggregateTypeForABI(Ty))
6359 return ABIArgInfo::getDirect();
6360
Stephen Hines651f13c2014-04-23 16:59:28 -07006361 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6362 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6363 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6364 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6365
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006366 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00006367 // Build a coercion type from the LLVM struct type.
6368 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6369 if (!StrTy)
6370 return ABIArgInfo::getDirect();
6371
6372 CoerceBuilder CB(getVMContext(), getDataLayout());
6373 CB.addStruct(0, StrTy);
6374 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6375
6376 // Try to use the original type for coercion.
6377 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6378
6379 if (CB.InReg)
6380 return ABIArgInfo::getDirectInReg(CoerceTy);
6381 else
6382 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006383}
6384
6385llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6386 CodeGenFunction &CGF) const {
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00006387 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6388 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6389 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6390 AI.setCoerceToType(ArgTy);
6391
6392 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6393 CGBuilderTy &Builder = CGF.Builder;
6394 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6395 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6396 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6397 llvm::Value *ArgAddr;
6398 unsigned Stride;
6399
6400 switch (AI.getKind()) {
6401 case ABIArgInfo::Expand:
Stephen Hines651f13c2014-04-23 16:59:28 -07006402 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00006403 llvm_unreachable("Unsupported ABI kind for va_arg");
6404
6405 case ABIArgInfo::Extend:
6406 Stride = 8;
6407 ArgAddr = Builder
6408 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6409 "extend");
6410 break;
6411
6412 case ABIArgInfo::Direct:
6413 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6414 ArgAddr = Addr;
6415 break;
6416
6417 case ABIArgInfo::Indirect:
6418 Stride = 8;
6419 ArgAddr = Builder.CreateBitCast(Addr,
6420 llvm::PointerType::getUnqual(ArgPtrTy),
6421 "indirect");
6422 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6423 break;
6424
6425 case ABIArgInfo::Ignore:
6426 return llvm::UndefValue::get(ArgPtrTy);
6427 }
6428
6429 // Update VAList.
6430 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6431 Builder.CreateStore(Addr, VAListAddrAsBPP);
6432
6433 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006434}
6435
6436void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6437 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Stephen Hines651f13c2014-04-23 16:59:28 -07006438 for (auto &I : FI.arguments())
6439 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006440}
6441
6442namespace {
6443class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6444public:
6445 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6446 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07006447
6448 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
6449 return 14;
6450 }
6451
6452 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6453 llvm::Value *Address) const override;
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006454};
6455} // end anonymous namespace
6456
Stephen Hines651f13c2014-04-23 16:59:28 -07006457bool
6458SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6459 llvm::Value *Address) const {
6460 // This is calculated from the LLVM and GCC tables and verified
6461 // against gcc output. AFAIK all ABIs use the same encoding.
6462
6463 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6464
6465 llvm::IntegerType *i8 = CGF.Int8Ty;
6466 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6467 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6468
6469 // 0-31: the 8-byte general-purpose registers
6470 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6471
6472 // 32-63: f0-31, the 4-byte floating-point registers
6473 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6474
6475 // Y = 64
6476 // PSR = 65
6477 // WIM = 66
6478 // TBR = 67
6479 // PC = 68
6480 // NPC = 69
6481 // FSR = 70
6482 // CSR = 71
6483 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6484
6485 // 72-87: d0-15, the 8-byte floating-point registers
6486 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6487
6488 return false;
6489}
6490
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00006491
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006492//===----------------------------------------------------------------------===//
Stephen Hines651f13c2014-04-23 16:59:28 -07006493// XCore ABI Implementation
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006494//===----------------------------------------------------------------------===//
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006495
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006496namespace {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006497
6498/// A SmallStringEnc instance is used to build up the TypeString by passing
6499/// it by reference between functions that append to it.
6500typedef llvm::SmallString<128> SmallStringEnc;
6501
6502/// TypeStringCache caches the meta encodings of Types.
6503///
6504/// The reason for caching TypeStrings is two fold:
6505/// 1. To cache a type's encoding for later uses;
6506/// 2. As a means to break recursive member type inclusion.
6507///
6508/// A cache Entry can have a Status of:
6509/// NonRecursive: The type encoding is not recursive;
6510/// Recursive: The type encoding is recursive;
6511/// Incomplete: An incomplete TypeString;
6512/// IncompleteUsed: An incomplete TypeString that has been used in a
6513/// Recursive type encoding.
6514///
6515/// A NonRecursive entry will have all of its sub-members expanded as fully
6516/// as possible. Whilst it may contain types which are recursive, the type
6517/// itself is not recursive and thus its encoding may be safely used whenever
6518/// the type is encountered.
6519///
6520/// A Recursive entry will have all of its sub-members expanded as fully as
6521/// possible. The type itself is recursive and it may contain other types which
6522/// are recursive. The Recursive encoding must not be used during the expansion
6523/// of a recursive type's recursive branch. For simplicity the code uses
6524/// IncompleteCount to reject all usage of Recursive encodings for member types.
6525///
6526/// An Incomplete entry is always a RecordType and only encodes its
6527/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6528/// are placed into the cache during type expansion as a means to identify and
6529/// handle recursive inclusion of types as sub-members. If there is recursion
6530/// the entry becomes IncompleteUsed.
6531///
6532/// During the expansion of a RecordType's members:
6533///
6534/// If the cache contains a NonRecursive encoding for the member type, the
6535/// cached encoding is used;
6536///
6537/// If the cache contains a Recursive encoding for the member type, the
6538/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6539///
6540/// If the member is a RecordType, an Incomplete encoding is placed into the
6541/// cache to break potential recursive inclusion of itself as a sub-member;
6542///
6543/// Once a member RecordType has been expanded, its temporary incomplete
6544/// entry is removed from the cache. If a Recursive encoding was swapped out
6545/// it is swapped back in;
6546///
6547/// If an incomplete entry is used to expand a sub-member, the incomplete
6548/// entry is marked as IncompleteUsed. The cache keeps count of how many
6549/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6550///
6551/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6552/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6553/// Else the member is part of a recursive type and thus the recursion has
6554/// been exited too soon for the encoding to be correct for the member.
6555///
6556class TypeStringCache {
6557 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6558 struct Entry {
6559 std::string Str; // The encoded TypeString for the type.
6560 enum Status State; // Information about the encoding in 'Str'.
6561 std::string Swapped; // A temporary place holder for a Recursive encoding
6562 // during the expansion of RecordType's members.
6563 };
6564 std::map<const IdentifierInfo *, struct Entry> Map;
6565 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6566 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6567public:
6568 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
6569 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6570 bool removeIncomplete(const IdentifierInfo *ID);
6571 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6572 bool IsRecursive);
6573 StringRef lookupStr(const IdentifierInfo *ID);
6574};
6575
6576/// TypeString encodings for enum & union fields must be order.
6577/// FieldEncoding is a helper for this ordering process.
6578class FieldEncoding {
6579 bool HasName;
6580 std::string Enc;
6581public:
6582 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6583 StringRef str() {return Enc.c_str();};
6584 bool operator<(const FieldEncoding &rhs) const {
6585 if (HasName != rhs.HasName) return HasName;
6586 return Enc < rhs.Enc;
6587 }
6588};
6589
Robert Lytton276c2892013-08-19 09:46:39 +00006590class XCoreABIInfo : public DefaultABIInfo {
6591public:
6592 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Stephen Hines651f13c2014-04-23 16:59:28 -07006593 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6594 CodeGenFunction &CGF) const override;
Robert Lytton276c2892013-08-19 09:46:39 +00006595};
6596
Stephen Hines651f13c2014-04-23 16:59:28 -07006597class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006598 mutable TypeStringCache TSC;
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006599public:
Stephen Hines651f13c2014-04-23 16:59:28 -07006600 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton276c2892013-08-19 09:46:39 +00006601 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006602 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6603 CodeGen::CodeGenModule &M) const override;
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006604};
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006605
Robert Lytton645e6fd2013-10-11 10:29:34 +00006606} // End anonymous namespace.
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006607
Robert Lytton276c2892013-08-19 09:46:39 +00006608llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6609 CodeGenFunction &CGF) const {
Robert Lytton276c2892013-08-19 09:46:39 +00006610 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton276c2892013-08-19 09:46:39 +00006611
Robert Lytton645e6fd2013-10-11 10:29:34 +00006612 // Get the VAList.
Robert Lytton276c2892013-08-19 09:46:39 +00006613 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6614 CGF.Int8PtrPtrTy);
6615 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton276c2892013-08-19 09:46:39 +00006616
Robert Lytton645e6fd2013-10-11 10:29:34 +00006617 // Handle the argument.
6618 ABIArgInfo AI = classifyArgumentType(Ty);
6619 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6620 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6621 AI.setCoerceToType(ArgTy);
Robert Lytton276c2892013-08-19 09:46:39 +00006622 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton645e6fd2013-10-11 10:29:34 +00006623 llvm::Value *Val;
Andy Gibbsed9967e2013-10-14 07:02:04 +00006624 uint64_t ArgSize = 0;
Robert Lytton276c2892013-08-19 09:46:39 +00006625 switch (AI.getKind()) {
Robert Lytton276c2892013-08-19 09:46:39 +00006626 case ABIArgInfo::Expand:
Stephen Hines651f13c2014-04-23 16:59:28 -07006627 case ABIArgInfo::InAlloca:
Robert Lytton276c2892013-08-19 09:46:39 +00006628 llvm_unreachable("Unsupported ABI kind for va_arg");
6629 case ABIArgInfo::Ignore:
Robert Lytton645e6fd2013-10-11 10:29:34 +00006630 Val = llvm::UndefValue::get(ArgPtrTy);
6631 ArgSize = 0;
6632 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006633 case ABIArgInfo::Extend:
6634 case ABIArgInfo::Direct:
Robert Lytton645e6fd2013-10-11 10:29:34 +00006635 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6636 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6637 if (ArgSize < 4)
6638 ArgSize = 4;
6639 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006640 case ABIArgInfo::Indirect:
6641 llvm::Value *ArgAddr;
6642 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6643 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton645e6fd2013-10-11 10:29:34 +00006644 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6645 ArgSize = 4;
6646 break;
Robert Lytton276c2892013-08-19 09:46:39 +00006647 }
Robert Lytton645e6fd2013-10-11 10:29:34 +00006648
6649 // Increment the VAList.
6650 if (ArgSize) {
6651 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6652 Builder.CreateStore(APN, VAListAddrAsBPP);
6653 }
6654 return Val;
Robert Lytton276c2892013-08-19 09:46:39 +00006655}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00006656
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006657/// During the expansion of a RecordType, an incomplete TypeString is placed
6658/// into the cache as a means to identify and break recursion.
6659/// If there is a Recursive encoding in the cache, it is swapped out and will
6660/// be reinserted by removeIncomplete().
6661/// All other types of encoding should have been used rather than arriving here.
6662void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6663 std::string StubEnc) {
6664 if (!ID)
6665 return;
6666 Entry &E = Map[ID];
6667 assert( (E.Str.empty() || E.State == Recursive) &&
6668 "Incorrectly use of addIncomplete");
6669 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6670 E.Swapped.swap(E.Str); // swap out the Recursive
6671 E.Str.swap(StubEnc);
6672 E.State = Incomplete;
6673 ++IncompleteCount;
6674}
6675
6676/// Once the RecordType has been expanded, the temporary incomplete TypeString
6677/// must be removed from the cache.
6678/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6679/// Returns true if the RecordType was defined recursively.
6680bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6681 if (!ID)
6682 return false;
6683 auto I = Map.find(ID);
6684 assert(I != Map.end() && "Entry not present");
6685 Entry &E = I->second;
6686 assert( (E.State == Incomplete ||
6687 E.State == IncompleteUsed) &&
6688 "Entry must be an incomplete type");
6689 bool IsRecursive = false;
6690 if (E.State == IncompleteUsed) {
6691 // We made use of our Incomplete encoding, thus we are recursive.
6692 IsRecursive = true;
6693 --IncompleteUsedCount;
6694 }
6695 if (E.Swapped.empty())
6696 Map.erase(I);
6697 else {
6698 // Swap the Recursive back.
6699 E.Swapped.swap(E.Str);
6700 E.Swapped.clear();
6701 E.State = Recursive;
6702 }
6703 --IncompleteCount;
6704 return IsRecursive;
6705}
6706
6707/// Add the encoded TypeString to the cache only if it is NonRecursive or
6708/// Recursive (viz: all sub-members were expanded as fully as possible).
6709void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6710 bool IsRecursive) {
6711 if (!ID || IncompleteUsedCount)
6712 return; // No key or it is is an incomplete sub-type so don't add.
6713 Entry &E = Map[ID];
6714 if (IsRecursive && !E.Str.empty()) {
6715 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6716 "This is not the same Recursive entry");
6717 // The parent container was not recursive after all, so we could have used
6718 // this Recursive sub-member entry after all, but we assumed the worse when
6719 // we started viz: IncompleteCount!=0.
6720 return;
6721 }
6722 assert(E.Str.empty() && "Entry already present");
6723 E.Str = Str.str();
6724 E.State = IsRecursive? Recursive : NonRecursive;
6725}
6726
6727/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6728/// are recursively expanding a type (IncompleteCount != 0) and the cached
6729/// encoding is Recursive, return an empty StringRef.
6730StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6731 if (!ID)
6732 return StringRef(); // We have no key.
6733 auto I = Map.find(ID);
6734 if (I == Map.end())
6735 return StringRef(); // We have no encoding.
6736 Entry &E = I->second;
6737 if (E.State == Recursive && IncompleteCount)
6738 return StringRef(); // We don't use Recursive encodings for member types.
6739
6740 if (E.State == Incomplete) {
6741 // The incomplete type is being used to break out of recursion.
6742 E.State = IncompleteUsed;
6743 ++IncompleteUsedCount;
6744 }
6745 return E.Str.c_str();
6746}
6747
6748/// The XCore ABI includes a type information section that communicates symbol
6749/// type information to the linker. The linker uses this information to verify
6750/// safety/correctness of things such as array bound and pointers et al.
6751/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6752/// This type information (TypeString) is emitted into meta data for all global
6753/// symbols: definitions, declarations, functions & variables.
6754///
6755/// The TypeString carries type, qualifier, name, size & value details.
6756/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6757/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6758/// The output is tested by test/CodeGen/xcore-stringtype.c.
6759///
6760static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6761 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6762
6763/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6764void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6765 CodeGen::CodeGenModule &CGM) const {
6766 SmallStringEnc Enc;
6767 if (getTypeString(Enc, D, CGM, TSC)) {
6768 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6769 llvm::SmallVector<llvm::Value *, 2> MDVals;
6770 MDVals.push_back(GV);
6771 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6772 llvm::NamedMDNode *MD =
6773 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6774 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6775 }
6776}
6777
6778static bool appendType(SmallStringEnc &Enc, QualType QType,
6779 const CodeGen::CodeGenModule &CGM,
6780 TypeStringCache &TSC);
6781
6782/// Helper function for appendRecordType().
6783/// Builds a SmallVector containing the encoded field types in declaration order.
6784static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6785 const RecordDecl *RD,
6786 const CodeGen::CodeGenModule &CGM,
6787 TypeStringCache &TSC) {
Stephen Hines176edba2014-12-01 14:53:08 -08006788 for (const auto *Field : RD->fields()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006789 SmallStringEnc Enc;
6790 Enc += "m(";
Stephen Hines176edba2014-12-01 14:53:08 -08006791 Enc += Field->getName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006792 Enc += "){";
Stephen Hines176edba2014-12-01 14:53:08 -08006793 if (Field->isBitField()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006794 Enc += "b(";
6795 llvm::raw_svector_ostream OS(Enc);
6796 OS.resync();
Stephen Hines176edba2014-12-01 14:53:08 -08006797 OS << Field->getBitWidthValue(CGM.getContext());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006798 OS.flush();
6799 Enc += ':';
6800 }
Stephen Hines176edba2014-12-01 14:53:08 -08006801 if (!appendType(Enc, Field->getType(), CGM, TSC))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006802 return false;
Stephen Hines176edba2014-12-01 14:53:08 -08006803 if (Field->isBitField())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006804 Enc += ')';
6805 Enc += '}';
Stephen Hines176edba2014-12-01 14:53:08 -08006806 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006807 }
6808 return true;
6809}
6810
6811/// Appends structure and union types to Enc and adds encoding to cache.
6812/// Recursively calls appendType (via extractFieldType) for each field.
6813/// Union types have their fields ordered according to the ABI.
6814static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6815 const CodeGen::CodeGenModule &CGM,
6816 TypeStringCache &TSC, const IdentifierInfo *ID) {
6817 // Append the cached TypeString if we have one.
6818 StringRef TypeString = TSC.lookupStr(ID);
6819 if (!TypeString.empty()) {
6820 Enc += TypeString;
6821 return true;
6822 }
6823
6824 // Start to emit an incomplete TypeString.
6825 size_t Start = Enc.size();
6826 Enc += (RT->isUnionType()? 'u' : 's');
6827 Enc += '(';
6828 if (ID)
6829 Enc += ID->getName();
6830 Enc += "){";
6831
6832 // We collect all encoded fields and order as necessary.
6833 bool IsRecursive = false;
6834 const RecordDecl *RD = RT->getDecl()->getDefinition();
6835 if (RD && !RD->field_empty()) {
6836 // An incomplete TypeString stub is placed in the cache for this RecordType
6837 // so that recursive calls to this RecordType will use it whilst building a
6838 // complete TypeString for this RecordType.
6839 SmallVector<FieldEncoding, 16> FE;
6840 std::string StubEnc(Enc.substr(Start).str());
6841 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6842 TSC.addIncomplete(ID, std::move(StubEnc));
6843 if (!extractFieldType(FE, RD, CGM, TSC)) {
6844 (void) TSC.removeIncomplete(ID);
6845 return false;
6846 }
6847 IsRecursive = TSC.removeIncomplete(ID);
6848 // The ABI requires unions to be sorted but not structures.
6849 // See FieldEncoding::operator< for sort algorithm.
6850 if (RT->isUnionType())
6851 std::sort(FE.begin(), FE.end());
6852 // We can now complete the TypeString.
6853 unsigned E = FE.size();
6854 for (unsigned I = 0; I != E; ++I) {
6855 if (I)
6856 Enc += ',';
6857 Enc += FE[I].str();
6858 }
6859 }
6860 Enc += '}';
6861 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6862 return true;
6863}
6864
6865/// Appends enum types to Enc and adds the encoding to the cache.
6866static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6867 TypeStringCache &TSC,
6868 const IdentifierInfo *ID) {
6869 // Append the cached TypeString if we have one.
6870 StringRef TypeString = TSC.lookupStr(ID);
6871 if (!TypeString.empty()) {
6872 Enc += TypeString;
6873 return true;
6874 }
6875
6876 size_t Start = Enc.size();
6877 Enc += "e(";
6878 if (ID)
6879 Enc += ID->getName();
6880 Enc += "){";
6881
6882 // We collect all encoded enumerations and order them alphanumerically.
6883 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
6884 SmallVector<FieldEncoding, 16> FE;
6885 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6886 ++I) {
6887 SmallStringEnc EnumEnc;
6888 EnumEnc += "m(";
6889 EnumEnc += I->getName();
6890 EnumEnc += "){";
6891 I->getInitVal().toString(EnumEnc);
6892 EnumEnc += '}';
6893 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6894 }
6895 std::sort(FE.begin(), FE.end());
6896 unsigned E = FE.size();
6897 for (unsigned I = 0; I != E; ++I) {
6898 if (I)
6899 Enc += ',';
6900 Enc += FE[I].str();
6901 }
6902 }
6903 Enc += '}';
6904 TSC.addIfComplete(ID, Enc.substr(Start), false);
6905 return true;
6906}
6907
6908/// Appends type's qualifier to Enc.
6909/// This is done prior to appending the type's encoding.
6910static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6911 // Qualifiers are emitted in alphabetical order.
6912 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6913 int Lookup = 0;
6914 if (QT.isConstQualified())
6915 Lookup += 1<<0;
6916 if (QT.isRestrictQualified())
6917 Lookup += 1<<1;
6918 if (QT.isVolatileQualified())
6919 Lookup += 1<<2;
6920 Enc += Table[Lookup];
6921}
6922
6923/// Appends built-in types to Enc.
6924static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6925 const char *EncType;
6926 switch (BT->getKind()) {
6927 case BuiltinType::Void:
6928 EncType = "0";
6929 break;
6930 case BuiltinType::Bool:
6931 EncType = "b";
6932 break;
6933 case BuiltinType::Char_U:
6934 EncType = "uc";
6935 break;
6936 case BuiltinType::UChar:
6937 EncType = "uc";
6938 break;
6939 case BuiltinType::SChar:
6940 EncType = "sc";
6941 break;
6942 case BuiltinType::UShort:
6943 EncType = "us";
6944 break;
6945 case BuiltinType::Short:
6946 EncType = "ss";
6947 break;
6948 case BuiltinType::UInt:
6949 EncType = "ui";
6950 break;
6951 case BuiltinType::Int:
6952 EncType = "si";
6953 break;
6954 case BuiltinType::ULong:
6955 EncType = "ul";
6956 break;
6957 case BuiltinType::Long:
6958 EncType = "sl";
6959 break;
6960 case BuiltinType::ULongLong:
6961 EncType = "ull";
6962 break;
6963 case BuiltinType::LongLong:
6964 EncType = "sll";
6965 break;
6966 case BuiltinType::Float:
6967 EncType = "ft";
6968 break;
6969 case BuiltinType::Double:
6970 EncType = "d";
6971 break;
6972 case BuiltinType::LongDouble:
6973 EncType = "ld";
6974 break;
6975 default:
6976 return false;
6977 }
6978 Enc += EncType;
6979 return true;
6980}
6981
6982/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6983static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6984 const CodeGen::CodeGenModule &CGM,
6985 TypeStringCache &TSC) {
6986 Enc += "p(";
6987 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6988 return false;
6989 Enc += ')';
6990 return true;
6991}
6992
6993/// Appends array encoding to Enc before calling appendType for the element.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006994static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6995 const ArrayType *AT,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006996 const CodeGen::CodeGenModule &CGM,
6997 TypeStringCache &TSC, StringRef NoSizeEnc) {
6998 if (AT->getSizeModifier() != ArrayType::Normal)
6999 return false;
7000 Enc += "a(";
7001 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7002 CAT->getSize().toStringUnsigned(Enc);
7003 else
7004 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7005 Enc += ':';
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007006 // The Qualifiers should be attached to the type rather than the array.
7007 appendQualifier(Enc, QT);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007008 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7009 return false;
7010 Enc += ')';
7011 return true;
7012}
7013
7014/// Appends a function encoding to Enc, calling appendType for the return type
7015/// and the arguments.
7016static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7017 const CodeGen::CodeGenModule &CGM,
7018 TypeStringCache &TSC) {
7019 Enc += "f{";
7020 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7021 return false;
7022 Enc += "}(";
7023 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7024 // N.B. we are only interested in the adjusted param types.
7025 auto I = FPT->param_type_begin();
7026 auto E = FPT->param_type_end();
7027 if (I != E) {
7028 do {
7029 if (!appendType(Enc, *I, CGM, TSC))
7030 return false;
7031 ++I;
7032 if (I != E)
7033 Enc += ',';
7034 } while (I != E);
7035 if (FPT->isVariadic())
7036 Enc += ",va";
7037 } else {
7038 if (FPT->isVariadic())
7039 Enc += "va";
7040 else
7041 Enc += '0';
7042 }
7043 }
7044 Enc += ')';
7045 return true;
7046}
7047
7048/// Handles the type's qualifier before dispatching a call to handle specific
7049/// type encodings.
7050static bool appendType(SmallStringEnc &Enc, QualType QType,
7051 const CodeGen::CodeGenModule &CGM,
7052 TypeStringCache &TSC) {
7053
7054 QualType QT = QType.getCanonicalType();
7055
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007056 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7057 // The Qualifiers should be attached to the type rather than the array.
7058 // Thus we don't call appendQualifier() here.
7059 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7060
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007061 appendQualifier(Enc, QT);
7062
7063 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7064 return appendBuiltinType(Enc, BT);
7065
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007066 if (const PointerType *PT = QT->getAs<PointerType>())
7067 return appendPointerType(Enc, PT, CGM, TSC);
7068
7069 if (const EnumType *ET = QT->getAs<EnumType>())
7070 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7071
7072 if (const RecordType *RT = QT->getAsStructureType())
7073 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7074
7075 if (const RecordType *RT = QT->getAsUnionType())
7076 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7077
7078 if (const FunctionType *FT = QT->getAs<FunctionType>())
7079 return appendFunctionType(Enc, FT, CGM, TSC);
7080
7081 return false;
7082}
7083
7084static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7085 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7086 if (!D)
7087 return false;
7088
7089 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7090 if (FD->getLanguageLinkage() != CLanguageLinkage)
7091 return false;
7092 return appendType(Enc, FD->getType(), CGM, TSC);
7093 }
7094
7095 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7096 if (VD->getLanguageLinkage() != CLanguageLinkage)
7097 return false;
7098 QualType QT = VD->getType().getCanonicalType();
7099 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7100 // Global ArrayTypes are given a size of '*' if the size is unknown.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007101 // The Qualifiers should be attached to the type rather than the array.
7102 // Thus we don't call appendQualifier() here.
7103 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007104 }
7105 return appendType(Enc, QT, CGM, TSC);
7106 }
7107 return false;
7108}
7109
7110
Robert Lytton5f15f4d2013-08-13 09:43:10 +00007111//===----------------------------------------------------------------------===//
7112// Driver code
7113//===----------------------------------------------------------------------===//
7114
Stephen Hines176edba2014-12-01 14:53:08 -08007115const llvm::Triple &CodeGenModule::getTriple() const {
7116 return getTarget().getTriple();
7117}
7118
7119bool CodeGenModule::supportsCOMDAT() const {
7120 return !getTriple().isOSBinFormatMachO();
7121}
7122
Chris Lattnerea044322010-07-29 02:01:43 +00007123const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00007124 if (TheTargetCodeGenInfo)
7125 return *TheTargetCodeGenInfo;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00007126
John McCall64aa4b32013-04-16 22:48:15 +00007127 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar1752ee42009-08-24 09:10:05 +00007128 switch (Triple.getArch()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00007129 default:
Chris Lattnerea044322010-07-29 02:01:43 +00007130 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00007131
Derek Schuff9ed63f82012-09-06 17:37:28 +00007132 case llvm::Triple::le32:
7133 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCallaeeb7012010-05-27 06:19:26 +00007134 case llvm::Triple::mips:
7135 case llvm::Triple::mipsel:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00007136 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
John McCallaeeb7012010-05-27 06:19:26 +00007137
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00007138 case llvm::Triple::mips64:
7139 case llvm::Triple::mips64el:
Akira Hatanakac0e3b662011-11-02 23:14:57 +00007140 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00007141
Tim Northoverc264e162013-01-31 12:13:10 +00007142 case llvm::Triple::aarch64:
Stephen Hines176edba2014-12-01 14:53:08 -08007143 case llvm::Triple::aarch64_be: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007144 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007145 if (getTarget().getABI() == "darwinpcs")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007146 Kind = AArch64ABIInfo::DarwinPCS;
7147
7148 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
7149 }
Tim Northoverc264e162013-01-31 12:13:10 +00007150
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00007151 case llvm::Triple::arm:
Stephen Hines651f13c2014-04-23 16:59:28 -07007152 case llvm::Triple::armeb:
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00007153 case llvm::Triple::thumb:
Stephen Hines651f13c2014-04-23 16:59:28 -07007154 case llvm::Triple::thumbeb:
Sandeep Patel34c1af82011-04-05 00:23:47 +00007155 {
7156 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007157 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel34c1af82011-04-05 00:23:47 +00007158 Kind = ARMABIInfo::APCS;
David Tweedb16abb12012-10-25 13:33:01 +00007159 else if (CodeGenOpts.FloatABI == "hard" ||
John McCall64aa4b32013-04-16 22:48:15 +00007160 (CodeGenOpts.FloatABI != "soft" &&
7161 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel34c1af82011-04-05 00:23:47 +00007162 Kind = ARMABIInfo::AAPCS_VFP;
7163
Derek Schuff263366f2012-10-16 22:30:41 +00007164 switch (Triple.getOS()) {
Eli Bendersky441d9f72012-12-04 18:38:10 +00007165 case llvm::Triple::NaCl:
Derek Schuff263366f2012-10-16 22:30:41 +00007166 return *(TheTargetCodeGenInfo =
7167 new NaClARMTargetCodeGenInfo(Types, Kind));
7168 default:
7169 return *(TheTargetCodeGenInfo =
7170 new ARMTargetCodeGenInfo(Types, Kind));
7171 }
Sandeep Patel34c1af82011-04-05 00:23:47 +00007172 }
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00007173
John McCallec853ba2010-03-11 00:10:12 +00007174 case llvm::Triple::ppc:
Chris Lattnerea044322010-07-29 02:01:43 +00007175 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divacky0fbc4b92012-05-09 18:22:46 +00007176 case llvm::Triple::ppc64:
Stephen Hines176edba2014-12-01 14:53:08 -08007177 if (Triple.isOSBinFormatELF()) {
7178 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
7179 if (getTarget().getABI() == "elfv2")
7180 Kind = PPC64_SVR4_ABIInfo::ELFv2;
7181
7182 return *(TheTargetCodeGenInfo =
7183 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7184 } else
Bill Schmidt2fc107f2012-10-03 19:18:57 +00007185 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Stephen Hines176edba2014-12-01 14:53:08 -08007186 case llvm::Triple::ppc64le: {
Bill Schmidtea7fb0c2013-07-26 01:36:11 +00007187 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Stephen Hines176edba2014-12-01 14:53:08 -08007188 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
7189 if (getTarget().getABI() == "elfv1")
7190 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7191
7192 return *(TheTargetCodeGenInfo =
7193 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7194 }
John McCallec853ba2010-03-11 00:10:12 +00007195
Peter Collingbourneedb66f32012-05-20 23:28:41 +00007196 case llvm::Triple::nvptx:
7197 case llvm::Triple::nvptx64:
Justin Holewinski2c585b92012-05-24 17:43:12 +00007198 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinski0259c3a2011-04-22 11:10:38 +00007199
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00007200 case llvm::Triple::msp430:
Chris Lattnerea044322010-07-29 02:01:43 +00007201 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00007202
Ulrich Weigandb8409212013-05-06 16:26:41 +00007203 case llvm::Triple::systemz:
7204 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7205
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00007206 case llvm::Triple::tce:
7207 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7208
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00007209 case llvm::Triple::x86: {
John McCallb8b52972013-06-18 02:46:29 +00007210 bool IsDarwinVectorABI = Triple.isOSDarwin();
7211 bool IsSmallStructInRegABI =
7212 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Stephen Hines651f13c2014-04-23 16:59:28 -07007213 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00007214
John McCallb8b52972013-06-18 02:46:29 +00007215 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedman55fc7e22012-01-25 22:46:34 +00007216 return *(TheTargetCodeGenInfo =
Reid Kleckner3190ca92013-05-08 13:44:39 +00007217 new WinX86_32TargetCodeGenInfo(Types,
John McCallb8b52972013-06-18 02:46:29 +00007218 IsDarwinVectorABI, IsSmallStructInRegABI,
7219 IsWin32FloatStructABI,
Reid Kleckner3190ca92013-05-08 13:44:39 +00007220 CodeGenOpts.NumRegisterParameters));
John McCallb8b52972013-06-18 02:46:29 +00007221 } else {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00007222 return *(TheTargetCodeGenInfo =
John McCallb8b52972013-06-18 02:46:29 +00007223 new X86_32TargetCodeGenInfo(Types,
7224 IsDarwinVectorABI, IsSmallStructInRegABI,
7225 IsWin32FloatStructABI,
Rafael Espindolab48280b2012-07-31 02:44:24 +00007226 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00007227 }
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00007228 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00007229
Eli Friedmanee1ad992011-12-02 00:11:43 +00007230 case llvm::Triple::x86_64: {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07007231 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanee1ad992011-12-02 00:11:43 +00007232
Chris Lattnerf13721d2010-08-31 16:44:54 +00007233 switch (Triple.getOS()) {
7234 case llvm::Triple::Win32:
Stephen Hines176edba2014-12-01 14:53:08 -08007235 return *(TheTargetCodeGenInfo =
7236 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Eli Bendersky441d9f72012-12-04 18:38:10 +00007237 case llvm::Triple::NaCl:
Stephen Hines176edba2014-12-01 14:53:08 -08007238 return *(TheTargetCodeGenInfo =
7239 new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00007240 default:
Stephen Hines176edba2014-12-01 14:53:08 -08007241 return *(TheTargetCodeGenInfo =
7242 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00007243 }
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00007244 }
Tony Linthicum96319392011-12-12 21:14:55 +00007245 case llvm::Triple::hexagon:
7246 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00007247 case llvm::Triple::sparcv9:
7248 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton5f15f4d2013-08-13 09:43:10 +00007249 case llvm::Triple::xcore:
Stephen Hines651f13c2014-04-23 16:59:28 -07007250 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanee1ad992011-12-02 00:11:43 +00007251 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00007252}