blob: 9bf1dbbd0d8c58d677476db631a60f9e2bc9ebbc [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000023#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000026#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000027
28#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
40 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
41 Builder.CreateStore(Value, Cell);
42 }
43}
44
John McCalla1dee5302010-08-22 10:59:02 +000045static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000046 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000047 T->isMemberFunctionPointerType();
48}
49
Anton Korobeynikov244360d2009-06-05 22:08:42 +000050ABIInfo::~ABIInfo() {}
51
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000052static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000053 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000054 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
55 if (!RD)
56 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000057 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000058}
59
60static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000061 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000062 const RecordType *RT = T->getAs<RecordType>();
63 if (!RT)
64 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000065 return getRecordArgABI(RT, CXXABI);
66}
67
68CGCXXABI &ABIInfo::getCXXABI() const {
69 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000070}
71
Chris Lattner2b037972010-07-29 02:01:43 +000072ASTContext &ABIInfo::getContext() const {
73 return CGT.getContext();
74}
75
76llvm::LLVMContext &ABIInfo::getVMContext() const {
77 return CGT.getLLVMContext();
78}
79
Micah Villmowdd31ca12012-10-08 16:25:52 +000080const llvm::DataLayout &ABIInfo::getDataLayout() const {
81 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000082}
83
John McCallc8e01702013-04-16 22:48:15 +000084const TargetInfo &ABIInfo::getTarget() const {
85 return CGT.getTarget();
86}
Chris Lattner2b037972010-07-29 02:01:43 +000087
Anton Korobeynikov244360d2009-06-05 22:08:42 +000088void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000089 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +000090 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +000091 switch (TheKind) {
92 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +000093 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +000094 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +000095 Ty->print(OS);
96 else
97 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +000098 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +000099 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000100 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000101 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000102 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000103 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000104 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000105 case InAlloca:
106 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
107 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000108 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000109 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000110 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000111 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000112 break;
113 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000114 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000115 break;
116 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000117 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000118}
119
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000120TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
121
John McCall3480ef22011-08-30 01:42:09 +0000122// If someone can figure out a general rule for this, that would be great.
123// It's probably just doomed to be platform-dependent, though.
124unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
125 // Verified for:
126 // x86-64 FreeBSD, Linux, Darwin
127 // x86-32 FreeBSD, Linux, Darwin
128 // PowerPC Linux, Darwin
129 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000130 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000131 return 32;
132}
133
John McCalla729c622012-02-17 03:33:10 +0000134bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
135 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000136 // The following conventions are known to require this to be false:
137 // x86_stdcall
138 // MIPS
139 // For everything else, we just prefer false unless we opt out.
140 return false;
141}
142
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000143void
144TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
145 llvm::SmallString<24> &Opt) const {
146 // This assumes the user is passing a library name like "rt" instead of a
147 // filename like "librt.a/so", and that they don't care whether it's static or
148 // dynamic.
149 Opt = "-l";
150 Opt += Lib;
151}
152
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000153static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000154
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000155/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000156/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000157static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
158 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000159 if (FD->isUnnamedBitfield())
160 return true;
161
162 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163
Eli Friedman0b3f2012011-11-18 03:47:20 +0000164 // Constant arrays of empty records count as empty, strip them off.
165 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000166 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000167 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
168 if (AT->getSize() == 0)
169 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000170 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000171 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000172
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000173 const RecordType *RT = FT->getAs<RecordType>();
174 if (!RT)
175 return false;
176
177 // C++ record fields are never empty, at least in the Itanium ABI.
178 //
179 // FIXME: We should use a predicate for whether this behavior is true in the
180 // current ABI.
181 if (isa<CXXRecordDecl>(RT->getDecl()))
182 return false;
183
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000184 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000185}
186
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000187/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000188/// fields. Note that a structure with a flexible array member is not
189/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000190static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000191 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000192 if (!RT)
193 return 0;
194 const RecordDecl *RD = RT->getDecl();
195 if (RD->hasFlexibleArrayMember())
196 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000197
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000198 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000199 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000200 for (const auto &I : CXXRD->bases())
201 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000202 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000203
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000204 for (const auto *I : RD->fields())
205 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000206 return false;
207 return true;
208}
209
210/// isSingleElementStruct - Determine if a structure is a "single
211/// element struct", i.e. it has exactly one non-empty field or
212/// exactly one field which is itself a single element
213/// struct. Structures with flexible array members are never
214/// considered single element structs.
215///
216/// \return The field declaration for the single non-empty field, if
217/// it exists.
218static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
219 const RecordType *RT = T->getAsStructureType();
220 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000221 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000222
223 const RecordDecl *RD = RT->getDecl();
224 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000225 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000226
Craig Topper8a13c412014-05-21 05:09:00 +0000227 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000228
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000229 // If this is a C++ record, check the bases first.
230 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000231 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000232 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000233 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000234 continue;
235
236 // If we already found an element then this isn't a single-element struct.
237 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000238 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000239
240 // If this is non-empty and not a single element struct, the composite
241 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000242 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000243 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000244 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000245 }
246 }
247
248 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000249 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000250 QualType FT = FD->getType();
251
252 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000253 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000254 continue;
255
256 // If we already found an element then this isn't a single-element
257 // struct.
258 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000259 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000260
261 // Treat single element arrays as the element.
262 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
263 if (AT->getSize().getZExtValue() != 1)
264 break;
265 FT = AT->getElementType();
266 }
267
John McCalla1dee5302010-08-22 10:59:02 +0000268 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000269 Found = FT.getTypePtr();
270 } else {
271 Found = isSingleElementStruct(FT, Context);
272 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000273 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000274 }
275 }
276
Eli Friedmanee945342011-11-18 01:25:50 +0000277 // We don't consider a struct a single-element struct if it has
278 // padding beyond the element type.
279 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000280 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000281
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000282 return Found;
283}
284
285static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000286 // Treat complex types as the element type.
287 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
288 Ty = CTy->getElementType();
289
290 // Check for a type which we know has a simple scalar argument-passing
291 // convention without any padding. (We're specifically looking for 32
292 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000293 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000294 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000295 return false;
296
297 uint64_t Size = Context.getTypeSize(Ty);
298 return Size == 32 || Size == 64;
299}
300
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000301/// canExpandIndirectArgument - Test whether an argument type which is to be
302/// passed indirectly (on the stack) would have the equivalent layout if it was
303/// expanded into separate arguments. If so, we prefer to do the latter to avoid
304/// inhibiting optimizations.
305///
306// FIXME: This predicate is missing many cases, currently it just follows
307// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
308// should probably make this smarter, or better yet make the LLVM backend
309// capable of handling it.
310static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
311 // We can only expand structure types.
312 const RecordType *RT = Ty->getAs<RecordType>();
313 if (!RT)
314 return false;
315
316 // We can only expand (C) structures.
317 //
318 // FIXME: This needs to be generalized to handle classes as well.
319 const RecordDecl *RD = RT->getDecl();
320 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
321 return false;
322
Eli Friedmane5c85622011-11-18 01:32:26 +0000323 uint64_t Size = 0;
324
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000325 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000326 if (!is32Or64BitBasicType(FD->getType(), Context))
327 return false;
328
329 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
330 // how to expand them yet, and the predicate for telling if a bitfield still
331 // counts as "basic" is more complicated than what we were doing previously.
332 if (FD->isBitField())
333 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000334
335 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000336 }
337
Eli Friedmane5c85622011-11-18 01:32:26 +0000338 // Make sure there are not any holes in the struct.
339 if (Size != Context.getTypeSize(Ty))
340 return false;
341
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000342 return true;
343}
344
345namespace {
346/// DefaultABIInfo - The default implementation for ABI specific
347/// details. This implementation provides information which results in
348/// self-consistent and sensible LLVM IR generation, but does not
349/// conform to any particular ABI.
350class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000351public:
352 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000353
Chris Lattner458b2aa2010-07-29 02:16:43 +0000354 ABIArgInfo classifyReturnType(QualType RetTy) const;
355 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000356
Craig Topper4f12f102014-03-12 06:41:41 +0000357 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000358 if (!getCXXABI().classifyReturnType(FI))
359 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000360 for (auto &I : FI.arguments())
361 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000362 }
363
Craig Topper4f12f102014-03-12 06:41:41 +0000364 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
365 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000366};
367
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000368class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
369public:
Chris Lattner2b037972010-07-29 02:01:43 +0000370 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
371 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000372};
373
374llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
375 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000376 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000377}
378
Chris Lattner458b2aa2010-07-29 02:16:43 +0000379ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000380 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000381 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000382
Chris Lattner9723d6c2010-03-11 18:19:55 +0000383 // Treat an enum type as its underlying type.
384 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
385 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000386
Chris Lattner9723d6c2010-03-11 18:19:55 +0000387 return (Ty->isPromotableIntegerType() ?
388 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000389}
390
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000391ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
392 if (RetTy->isVoidType())
393 return ABIArgInfo::getIgnore();
394
395 if (isAggregateTypeForABI(RetTy))
396 return ABIArgInfo::getIndirect(0);
397
398 // Treat an enum type as its underlying type.
399 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
400 RetTy = EnumTy->getDecl()->getIntegerType();
401
402 return (RetTy->isPromotableIntegerType() ?
403 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
404}
405
Derek Schuff09338a22012-09-06 17:37:28 +0000406//===----------------------------------------------------------------------===//
407// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000408//
409// This is a simplified version of the x86_32 ABI. Arguments and return values
410// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000411//===----------------------------------------------------------------------===//
412
413class PNaClABIInfo : public ABIInfo {
414 public:
415 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
416
417 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000418 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000419
Craig Topper4f12f102014-03-12 06:41:41 +0000420 void computeInfo(CGFunctionInfo &FI) const override;
421 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
422 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000423};
424
425class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
426 public:
427 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
428 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
429};
430
431void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000432 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000433 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
434
Reid Kleckner40ca9132014-05-13 22:05:45 +0000435 for (auto &I : FI.arguments())
436 I.info = classifyArgumentType(I.type);
437}
Derek Schuff09338a22012-09-06 17:37:28 +0000438
439llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
440 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000441 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000442}
443
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000444/// \brief Classify argument of given type \p Ty.
445ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000446 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000447 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000448 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000449 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000450 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
451 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000452 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000453 } else if (Ty->isFloatingType()) {
454 // Floating-point types don't go inreg.
455 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000456 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000457
458 return (Ty->isPromotableIntegerType() ?
459 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000460}
461
462ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
463 if (RetTy->isVoidType())
464 return ABIArgInfo::getIgnore();
465
Eli Benderskye20dad62013-04-04 22:49:35 +0000466 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000467 if (isAggregateTypeForABI(RetTy))
468 return ABIArgInfo::getIndirect(0);
469
470 // Treat an enum type as its underlying type.
471 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
472 RetTy = EnumTy->getDecl()->getIntegerType();
473
474 return (RetTy->isPromotableIntegerType() ?
475 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
476}
477
Chad Rosier651c1832013-03-25 21:00:27 +0000478/// IsX86_MMXType - Return true if this is an MMX type.
479bool IsX86_MMXType(llvm::Type *IRType) {
480 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000481 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
482 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
483 IRType->getScalarSizeInBits() != 64;
484}
485
Jay Foad7c57be32011-07-11 09:56:20 +0000486static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000488 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000489 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
490 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
491 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000492 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000493 }
494
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000495 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000496 }
497
498 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000499 return Ty;
500}
501
Chris Lattner0cf24192010-06-28 20:05:43 +0000502//===----------------------------------------------------------------------===//
503// X86-32 ABI Implementation
504//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000505
Reid Kleckner661f35b2014-01-18 01:12:41 +0000506/// \brief Similar to llvm::CCState, but for Clang.
507struct CCState {
508 CCState(unsigned CC) : CC(CC), FreeRegs(0) {}
509
510 unsigned CC;
511 unsigned FreeRegs;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000512 unsigned StackOffset;
513 bool UseInAlloca;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000514};
515
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000516/// X86_32ABIInfo - The X86-32 ABI information.
517class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000518 enum Class {
519 Integer,
520 Float
521 };
522
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000523 static const unsigned MinABIStackAlignInBytes = 4;
524
David Chisnallde3a0692009-08-17 23:08:21 +0000525 bool IsDarwinVectorABI;
526 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000527 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000528 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000529
530 static bool isRegisterSize(unsigned Size) {
531 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
532 }
533
Reid Kleckner40ca9132014-05-13 22:05:45 +0000534 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000535
Daniel Dunbar557893d2010-04-21 19:10:51 +0000536 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
537 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000538 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
539
540 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000541
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000542 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000543 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000544
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000545 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000546 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000547 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
548 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000549
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000550 /// \brief Rewrite the function info so that all memory arguments use
551 /// inalloca.
552 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
553
554 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
555 unsigned &StackOffset, ABIArgInfo &Info,
556 QualType Type) const;
557
Rafael Espindola75419dc2012-07-23 23:30:29 +0000558public:
559
Craig Topper4f12f102014-03-12 06:41:41 +0000560 void computeInfo(CGFunctionInfo &FI) const override;
561 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
562 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000563
Chad Rosier651c1832013-03-25 21:00:27 +0000564 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000565 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000566 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000567 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000568};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000569
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000570class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
571public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000572 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000573 bool d, bool p, bool w, unsigned r)
574 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000575
John McCall1fe2a8c2013-06-18 02:46:29 +0000576 static bool isStructReturnInRegABI(
577 const llvm::Triple &Triple, const CodeGenOptions &Opts);
578
Charles Davis4ea31ab2010-02-13 15:54:06 +0000579 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000580 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000581
Craig Topper4f12f102014-03-12 06:41:41 +0000582 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000583 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000584 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000585 return 4;
586 }
587
588 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000589 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000590
Jay Foad7c57be32011-07-11 09:56:20 +0000591 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000592 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000593 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000594 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
595 }
596
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000597 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
598 std::string &Constraints,
599 std::vector<llvm::Type *> &ResultRegTypes,
600 std::vector<llvm::Type *> &ResultTruncRegTypes,
601 std::vector<LValue> &ResultRegDests,
602 std::string &AsmString,
603 unsigned NumOutputs) const override;
604
Craig Topper4f12f102014-03-12 06:41:41 +0000605 llvm::Constant *
606 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000607 unsigned Sig = (0xeb << 0) | // jmp rel8
608 (0x06 << 8) | // .+0x08
609 ('F' << 16) |
610 ('T' << 24);
611 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
612 }
613
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000614};
615
616}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000617
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000618/// Rewrite input constraint references after adding some output constraints.
619/// In the case where there is one output and one input and we add one output,
620/// we need to replace all operand references greater than or equal to 1:
621/// mov $0, $1
622/// mov eax, $1
623/// The result will be:
624/// mov $0, $2
625/// mov eax, $2
626static void rewriteInputConstraintReferences(unsigned FirstIn,
627 unsigned NumNewOuts,
628 std::string &AsmString) {
629 std::string Buf;
630 llvm::raw_string_ostream OS(Buf);
631 size_t Pos = 0;
632 while (Pos < AsmString.size()) {
633 size_t DollarStart = AsmString.find('$', Pos);
634 if (DollarStart == std::string::npos)
635 DollarStart = AsmString.size();
636 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
637 if (DollarEnd == std::string::npos)
638 DollarEnd = AsmString.size();
639 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
640 Pos = DollarEnd;
641 size_t NumDollars = DollarEnd - DollarStart;
642 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
643 // We have an operand reference.
644 size_t DigitStart = Pos;
645 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
646 if (DigitEnd == std::string::npos)
647 DigitEnd = AsmString.size();
648 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
649 unsigned OperandIndex;
650 if (!OperandStr.getAsInteger(10, OperandIndex)) {
651 if (OperandIndex >= FirstIn)
652 OperandIndex += NumNewOuts;
653 OS << OperandIndex;
654 } else {
655 OS << OperandStr;
656 }
657 Pos = DigitEnd;
658 }
659 }
660 AsmString = std::move(OS.str());
661}
662
663/// Add output constraints for EAX:EDX because they are return registers.
664void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
665 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
666 std::vector<llvm::Type *> &ResultRegTypes,
667 std::vector<llvm::Type *> &ResultTruncRegTypes,
668 std::vector<LValue> &ResultRegDests, std::string &AsmString,
669 unsigned NumOutputs) const {
670 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
671
672 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
673 // larger.
674 if (!Constraints.empty())
675 Constraints += ',';
676 if (RetWidth <= 32) {
677 Constraints += "={eax}";
678 ResultRegTypes.push_back(CGF.Int32Ty);
679 } else {
680 // Use the 'A' constraint for EAX:EDX.
681 Constraints += "=A";
682 ResultRegTypes.push_back(CGF.Int64Ty);
683 }
684
685 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
686 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
687 ResultTruncRegTypes.push_back(CoerceTy);
688
689 // Coerce the integer by bitcasting the return slot pointer.
690 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
691 CoerceTy->getPointerTo()));
692 ResultRegDests.push_back(ReturnSlot);
693
694 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
695}
696
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000697/// shouldReturnTypeInRegister - Determine if the given type should be
698/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000699bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
700 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000701 uint64_t Size = Context.getTypeSize(Ty);
702
703 // Type must be register sized.
704 if (!isRegisterSize(Size))
705 return false;
706
707 if (Ty->isVectorType()) {
708 // 64- and 128- bit vectors inside structures are not returned in
709 // registers.
710 if (Size == 64 || Size == 128)
711 return false;
712
713 return true;
714 }
715
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000716 // If this is a builtin, pointer, enum, complex type, member pointer, or
717 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000718 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000719 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000720 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000721 return true;
722
723 // Arrays are treated like records.
724 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000725 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000726
727 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000728 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000729 if (!RT) return false;
730
Anders Carlsson40446e82010-01-27 03:25:19 +0000731 // FIXME: Traverse bases here too.
732
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000733 // Structure types are passed in register if all fields would be
734 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000735 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000736 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000737 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000738 continue;
739
740 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000741 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000742 return false;
743 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000744 return true;
745}
746
Reid Kleckner661f35b2014-01-18 01:12:41 +0000747ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
748 // If the return value is indirect, then the hidden argument is consuming one
749 // integer register.
750 if (State.FreeRegs) {
751 --State.FreeRegs;
752 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
753 }
754 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
755}
756
Reid Kleckner40ca9132014-05-13 22:05:45 +0000757ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000758 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000759 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000760
Chris Lattner458b2aa2010-07-29 02:16:43 +0000761 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000762 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000763 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000764 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000765
766 // 128-bit vectors are a special case; they are returned in
767 // registers and we need to make sure to pick a type the LLVM
768 // backend will like.
769 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000770 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000771 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000772
773 // Always return in register if it fits in a general purpose
774 // register, or if it is 64 bits and has a single element.
775 if ((Size == 8 || Size == 16 || Size == 32) ||
776 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000777 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000778 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000779
Reid Kleckner661f35b2014-01-18 01:12:41 +0000780 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000781 }
782
783 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000784 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000785
John McCalla1dee5302010-08-22 10:59:02 +0000786 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000787 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000788 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000789 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000790 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000791 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000792
David Chisnallde3a0692009-08-17 23:08:21 +0000793 // If specified, structs and unions are always indirect.
794 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000795 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000796
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000797 // Small structures which are register sized are generally returned
798 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000799 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000800 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000801
802 // As a special-case, if the struct is a "single-element" struct, and
803 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000804 // floating-point register. (MSVC does not apply this special case.)
805 // We apply a similar transformation for pointer types to improve the
806 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000807 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000808 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000809 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000810 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
811
812 // FIXME: We should be able to narrow this integer in cases with dead
813 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000814 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000815 }
816
Reid Kleckner661f35b2014-01-18 01:12:41 +0000817 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000818 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000819
Chris Lattner458b2aa2010-07-29 02:16:43 +0000820 // Treat an enum type as its underlying type.
821 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
822 RetTy = EnumTy->getDecl()->getIntegerType();
823
824 return (RetTy->isPromotableIntegerType() ?
825 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000826}
827
Eli Friedman7919bea2012-06-05 19:40:46 +0000828static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
829 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
830}
831
Daniel Dunbared23de32010-09-16 20:42:00 +0000832static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
833 const RecordType *RT = Ty->getAs<RecordType>();
834 if (!RT)
835 return 0;
836 const RecordDecl *RD = RT->getDecl();
837
838 // If this is a C++ record, check the bases first.
839 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000840 for (const auto &I : CXXRD->bases())
841 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000842 return false;
843
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000844 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000845 QualType FT = i->getType();
846
Eli Friedman7919bea2012-06-05 19:40:46 +0000847 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000848 return true;
849
850 if (isRecordWithSSEVectorType(Context, FT))
851 return true;
852 }
853
854 return false;
855}
856
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000857unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
858 unsigned Align) const {
859 // Otherwise, if the alignment is less than or equal to the minimum ABI
860 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000861 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000862 return 0; // Use default alignment.
863
864 // On non-Darwin, the stack type alignment is always 4.
865 if (!IsDarwinVectorABI) {
866 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000867 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000868 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000869
Daniel Dunbared23de32010-09-16 20:42:00 +0000870 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000871 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
872 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000873 return 16;
874
875 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000876}
877
Rafael Espindola703c47f2012-10-19 05:04:37 +0000878ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000879 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000880 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000881 if (State.FreeRegs) {
882 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000883 return ABIArgInfo::getIndirectInReg(0, false);
884 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000885 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000886 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000887
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000888 // Compute the byval alignment.
889 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
890 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
891 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000892 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000893
894 // If the stack alignment is less than the type alignment, realign the
895 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000896 bool Realign = TypeAlign > StackAlign;
897 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000898}
899
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000900X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
901 const Type *T = isSingleElementStruct(Ty, getContext());
902 if (!T)
903 T = Ty.getTypePtr();
904
905 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
906 BuiltinType::Kind K = BT->getKind();
907 if (K == BuiltinType::Float || K == BuiltinType::Double)
908 return Float;
909 }
910 return Integer;
911}
912
Reid Kleckner661f35b2014-01-18 01:12:41 +0000913bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
914 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000915 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000916 Class C = classify(Ty);
917 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000918 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000919
Rafael Espindola077dd592012-10-24 01:58:58 +0000920 unsigned Size = getContext().getTypeSize(Ty);
921 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000922
923 if (SizeInRegs == 0)
924 return false;
925
Reid Kleckner661f35b2014-01-18 01:12:41 +0000926 if (SizeInRegs > State.FreeRegs) {
927 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000928 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000929 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000930
Reid Kleckner661f35b2014-01-18 01:12:41 +0000931 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000932
Reid Kleckner661f35b2014-01-18 01:12:41 +0000933 if (State.CC == llvm::CallingConv::X86_FastCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000934 if (Size > 32)
935 return false;
936
937 if (Ty->isIntegralOrEnumerationType())
938 return true;
939
940 if (Ty->isPointerType())
941 return true;
942
943 if (Ty->isReferenceType())
944 return true;
945
Reid Kleckner661f35b2014-01-18 01:12:41 +0000946 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +0000947 NeedsPadding = true;
948
Rafael Espindola077dd592012-10-24 01:58:58 +0000949 return false;
950 }
951
Rafael Espindola703c47f2012-10-19 05:04:37 +0000952 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000953}
954
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000955ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
956 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000957 // FIXME: Set alignment on indirect arguments.
John McCalla1dee5302010-08-22 10:59:02 +0000958 if (isAggregateTypeForABI(Ty)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000959 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000960 // Check with the C++ ABI first.
961 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
962 if (RAA == CGCXXABI::RAA_Indirect) {
963 return getIndirectResult(Ty, false, State);
964 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
965 // The field index doesn't matter, we'll fix it up later.
966 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
967 }
968
969 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000970 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +0000971 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000972
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000973 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000974 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000975 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +0000976 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000977
Eli Friedman9f061a32011-11-18 00:28:11 +0000978 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +0000979 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980 return ABIArgInfo::getIgnore();
981
Rafael Espindolafad28de2012-10-24 01:59:00 +0000982 llvm::LLVMContext &LLVMContext = getVMContext();
983 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
984 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000985 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000986 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +0000987 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000988 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
989 return ABIArgInfo::getDirectInReg(Result);
990 }
Craig Topper8a13c412014-05-21 05:09:00 +0000991 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000992
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000993 // Expand small (<= 128-bit) record types when we know that the stack layout
994 // of those arguments will match the struct. This is important because the
995 // LLVM backend isn't smart enough to remove byval, which inhibits many
996 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +0000997 if (getContext().getTypeSize(Ty) <= 4*32 &&
998 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +0000999 return ABIArgInfo::getExpandWithPadding(
1000 State.CC == llvm::CallingConv::X86_FastCall, PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001001
Reid Kleckner661f35b2014-01-18 01:12:41 +00001002 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001003 }
1004
Chris Lattnerd774ae92010-08-26 20:05:13 +00001005 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001006 // On Darwin, some vectors are passed in memory, we handle this by passing
1007 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001008 if (IsDarwinVectorABI) {
1009 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001010 if ((Size == 8 || Size == 16 || Size == 32) ||
1011 (Size == 64 && VT->getNumElements() == 1))
1012 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1013 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001014 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001015
Chad Rosier651c1832013-03-25 21:00:27 +00001016 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1017 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001018
Chris Lattnerd774ae92010-08-26 20:05:13 +00001019 return ABIArgInfo::getDirect();
1020 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001021
1022
Chris Lattner458b2aa2010-07-29 02:16:43 +00001023 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1024 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001025
Rafael Espindolafad28de2012-10-24 01:59:00 +00001026 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001027 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001028
1029 if (Ty->isPromotableIntegerType()) {
1030 if (InReg)
1031 return ABIArgInfo::getExtendInReg();
1032 return ABIArgInfo::getExtend();
1033 }
1034 if (InReg)
1035 return ABIArgInfo::getDirectInReg();
1036 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001037}
1038
Rafael Espindolaa6472962012-07-24 00:01:07 +00001039void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001040 CCState State(FI.getCallingConvention());
1041 if (State.CC == llvm::CallingConv::X86_FastCall)
1042 State.FreeRegs = 2;
Rafael Espindola077dd592012-10-24 01:58:58 +00001043 else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001044 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001045 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001046 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001047
Reid Kleckner677539d2014-07-10 01:58:55 +00001048 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001049 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001050 } else if (FI.getReturnInfo().isIndirect()) {
1051 // The C++ ABI is not aware of register usage, so we have to check if the
1052 // return value was sret and put it in a register ourselves if appropriate.
1053 if (State.FreeRegs) {
1054 --State.FreeRegs; // The sret parameter consumes a register.
1055 FI.getReturnInfo().setInReg(true);
1056 }
1057 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001058
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001059 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001060 for (auto &I : FI.arguments()) {
1061 I.info = classifyArgumentType(I.type, State);
1062 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001063 }
1064
1065 // If we needed to use inalloca for any argument, do a second pass and rewrite
1066 // all the memory arguments to use inalloca.
1067 if (UsedInAlloca)
1068 rewriteWithInAlloca(FI);
1069}
1070
1071void
1072X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1073 unsigned &StackOffset,
1074 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001075 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1076 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1077 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1078 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1079
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001080 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1081 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001082 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001083 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001084 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001085 unsigned NumBytes = StackOffset - OldOffset;
1086 assert(NumBytes);
1087 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1088 Ty = llvm::ArrayType::get(Ty, NumBytes);
1089 FrameFields.push_back(Ty);
1090 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001091}
1092
Reid Kleckner852361d2014-07-26 00:12:26 +00001093static bool isArgInAlloca(const ABIArgInfo &Info) {
1094 // Leave ignored and inreg arguments alone.
1095 switch (Info.getKind()) {
1096 case ABIArgInfo::InAlloca:
1097 return true;
1098 case ABIArgInfo::Indirect:
1099 assert(Info.getIndirectByVal());
1100 return true;
1101 case ABIArgInfo::Ignore:
1102 return false;
1103 case ABIArgInfo::Direct:
1104 case ABIArgInfo::Extend:
1105 case ABIArgInfo::Expand:
1106 if (Info.getInReg())
1107 return false;
1108 return true;
1109 }
1110 llvm_unreachable("invalid enum");
1111}
1112
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001113void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1114 assert(IsWin32StructABI && "inalloca only supported on win32");
1115
1116 // Build a packed struct type for all of the arguments in memory.
1117 SmallVector<llvm::Type *, 6> FrameFields;
1118
1119 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001120 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1121
1122 // Put 'this' into the struct before 'sret', if necessary.
1123 bool IsThisCall =
1124 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1125 ABIArgInfo &Ret = FI.getReturnInfo();
1126 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1127 isArgInAlloca(I->info)) {
1128 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1129 ++I;
1130 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001131
1132 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001133 if (Ret.isIndirect() && !Ret.getInReg()) {
1134 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1135 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001136 // On Windows, the hidden sret parameter is always returned in eax.
1137 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001138 }
1139
1140 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001141 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001142 ++I;
1143
1144 // Put arguments passed in memory into the struct.
1145 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001146 if (isArgInAlloca(I->info))
1147 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001148 }
1149
1150 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1151 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001152}
1153
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001154llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1155 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001156 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001157
1158 CGBuilderTy &Builder = CGF.Builder;
1159 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1160 "ap");
1161 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001162
1163 // Compute if the address needs to be aligned
1164 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1165 Align = getTypeStackAlignInBytes(Ty, Align);
1166 Align = std::max(Align, 4U);
1167 if (Align > 4) {
1168 // addr = (addr + align - 1) & -align;
1169 llvm::Value *Offset =
1170 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1171 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1172 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1173 CGF.Int32Ty);
1174 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1175 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1176 Addr->getType(),
1177 "ap.cur.aligned");
1178 }
1179
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001180 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001181 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001182 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1183
1184 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001185 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001186 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001187 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001188 "ap.next");
1189 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1190
1191 return AddrTyped;
1192}
1193
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001194bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1195 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1196 assert(Triple.getArch() == llvm::Triple::x86);
1197
1198 switch (Opts.getStructReturnConvention()) {
1199 case CodeGenOptions::SRCK_Default:
1200 break;
1201 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1202 return false;
1203 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1204 return true;
1205 }
1206
1207 if (Triple.isOSDarwin())
1208 return true;
1209
1210 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001211 case llvm::Triple::DragonFly:
1212 case llvm::Triple::FreeBSD:
1213 case llvm::Triple::OpenBSD:
1214 case llvm::Triple::Bitrig:
1215 return true;
1216 case llvm::Triple::Win32:
1217 switch (Triple.getEnvironment()) {
1218 case llvm::Triple::UnknownEnvironment:
1219 case llvm::Triple::Cygnus:
1220 case llvm::Triple::GNU:
1221 case llvm::Triple::MSVC:
1222 return true;
1223 default:
1224 return false;
1225 }
1226 default:
1227 return false;
1228 }
1229}
1230
Charles Davis4ea31ab2010-02-13 15:54:06 +00001231void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1232 llvm::GlobalValue *GV,
1233 CodeGen::CodeGenModule &CGM) const {
1234 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1235 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1236 // Get the LLVM function.
1237 llvm::Function *Fn = cast<llvm::Function>(GV);
1238
1239 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001240 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001241 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001242 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1243 llvm::AttributeSet::get(CGM.getLLVMContext(),
1244 llvm::AttributeSet::FunctionIndex,
1245 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001246 }
1247 }
1248}
1249
John McCallbeec5a02010-03-06 00:35:14 +00001250bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1251 CodeGen::CodeGenFunction &CGF,
1252 llvm::Value *Address) const {
1253 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001254
Chris Lattnerece04092012-02-07 00:39:47 +00001255 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001256
John McCallbeec5a02010-03-06 00:35:14 +00001257 // 0-7 are the eight integer registers; the order is different
1258 // on Darwin (for EH), but the range is the same.
1259 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001260 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001261
John McCallc8e01702013-04-16 22:48:15 +00001262 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001263 // 12-16 are st(0..4). Not sure why we stop at 4.
1264 // These have size 16, which is sizeof(long double) on
1265 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001266 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001267 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001268
John McCallbeec5a02010-03-06 00:35:14 +00001269 } else {
1270 // 9 is %eflags, which doesn't get a size on Darwin for some
1271 // reason.
1272 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1273
1274 // 11-16 are st(0..5). Not sure why we stop at 5.
1275 // These have size 12, which is sizeof(long double) on
1276 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001277 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001278 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1279 }
John McCallbeec5a02010-03-06 00:35:14 +00001280
1281 return false;
1282}
1283
Chris Lattner0cf24192010-06-28 20:05:43 +00001284//===----------------------------------------------------------------------===//
1285// X86-64 ABI Implementation
1286//===----------------------------------------------------------------------===//
1287
1288
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001289namespace {
1290/// X86_64ABIInfo - The X86_64 ABI information.
1291class X86_64ABIInfo : public ABIInfo {
1292 enum Class {
1293 Integer = 0,
1294 SSE,
1295 SSEUp,
1296 X87,
1297 X87Up,
1298 ComplexX87,
1299 NoClass,
1300 Memory
1301 };
1302
1303 /// merge - Implement the X86_64 ABI merging algorithm.
1304 ///
1305 /// Merge an accumulating classification \arg Accum with a field
1306 /// classification \arg Field.
1307 ///
1308 /// \param Accum - The accumulating classification. This should
1309 /// always be either NoClass or the result of a previous merge
1310 /// call. In addition, this should never be Memory (the caller
1311 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001312 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001313
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001314 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1315 ///
1316 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1317 /// final MEMORY or SSE classes when necessary.
1318 ///
1319 /// \param AggregateSize - The size of the current aggregate in
1320 /// the classification process.
1321 ///
1322 /// \param Lo - The classification for the parts of the type
1323 /// residing in the low word of the containing object.
1324 ///
1325 /// \param Hi - The classification for the parts of the type
1326 /// residing in the higher words of the containing object.
1327 ///
1328 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1329
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001330 /// classify - Determine the x86_64 register classes in which the
1331 /// given type T should be passed.
1332 ///
1333 /// \param Lo - The classification for the parts of the type
1334 /// residing in the low word of the containing object.
1335 ///
1336 /// \param Hi - The classification for the parts of the type
1337 /// residing in the high word of the containing object.
1338 ///
1339 /// \param OffsetBase - The bit offset of this type in the
1340 /// containing object. Some parameters are classified different
1341 /// depending on whether they straddle an eightbyte boundary.
1342 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001343 /// \param isNamedArg - Whether the argument in question is a "named"
1344 /// argument, as used in AMD64-ABI 3.5.7.
1345 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001346 /// If a word is unused its result will be NoClass; if a type should
1347 /// be passed in Memory then at least the classification of \arg Lo
1348 /// will be Memory.
1349 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001350 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001351 ///
1352 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1353 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001354 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1355 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001356
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001357 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001358 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1359 unsigned IROffset, QualType SourceTy,
1360 unsigned SourceOffset) const;
1361 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1362 unsigned IROffset, QualType SourceTy,
1363 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001364
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001365 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001366 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001367 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001368
1369 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001370 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001371 ///
1372 /// \param freeIntRegs - The number of free integer registers remaining
1373 /// available.
1374 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001375
Chris Lattner458b2aa2010-07-29 02:16:43 +00001376 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001377
Bill Wendling5cd41c42010-10-18 03:41:31 +00001378 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001379 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001380 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001381 unsigned &neededSSE,
1382 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001383
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001384 bool IsIllegalVectorType(QualType Ty) const;
1385
John McCalle0fda732011-04-21 01:20:55 +00001386 /// The 0.98 ABI revision clarified a lot of ambiguities,
1387 /// unfortunately in ways that were not always consistent with
1388 /// certain previous compilers. In particular, platforms which
1389 /// required strict binary compatibility with older versions of GCC
1390 /// may need to exempt themselves.
1391 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001392 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001393 }
1394
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001395 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001396 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1397 // 64-bit hardware.
1398 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001399
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001401 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001402 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001403 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001404 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001405
John McCalla729c622012-02-17 03:33:10 +00001406 bool isPassedUsingAVXType(QualType type) const {
1407 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001408 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001409 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1410 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001411 if (info.isDirect()) {
1412 llvm::Type *ty = info.getCoerceToType();
1413 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1414 return (vectorTy->getBitWidth() > 128);
1415 }
1416 return false;
1417 }
1418
Craig Topper4f12f102014-03-12 06:41:41 +00001419 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001420
Craig Topper4f12f102014-03-12 06:41:41 +00001421 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1422 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001423};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001424
Chris Lattner04dc9572010-08-31 16:44:54 +00001425/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001426class WinX86_64ABIInfo : public ABIInfo {
1427
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001428 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001429
Chris Lattner04dc9572010-08-31 16:44:54 +00001430public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001431 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1432
Craig Topper4f12f102014-03-12 06:41:41 +00001433 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001434
Craig Topper4f12f102014-03-12 06:41:41 +00001435 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1436 CodeGenFunction &CGF) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001437};
1438
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001439class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1440public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001441 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffc7dd7222012-10-11 15:52:22 +00001442 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001443
John McCalla729c622012-02-17 03:33:10 +00001444 const X86_64ABIInfo &getABIInfo() const {
1445 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1446 }
1447
Craig Topper4f12f102014-03-12 06:41:41 +00001448 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001449 return 7;
1450 }
1451
1452 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001453 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001454 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001455
John McCall943fae92010-05-27 06:19:26 +00001456 // 0-15 are the 16 integer registers.
1457 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001458 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001459 return false;
1460 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001461
Jay Foad7c57be32011-07-11 09:56:20 +00001462 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001463 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001464 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001465 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1466 }
1467
John McCalla729c622012-02-17 03:33:10 +00001468 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001469 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001470 // The default CC on x86-64 sets %al to the number of SSA
1471 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001472 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001473 // that when AVX types are involved: the ABI explicitly states it is
1474 // undefined, and it doesn't work in practice because of how the ABI
1475 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001476 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001477 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001478 for (CallArgList::const_iterator
1479 it = args.begin(), ie = args.end(); it != ie; ++it) {
1480 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1481 HasAVXType = true;
1482 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001483 }
1484 }
John McCalla729c622012-02-17 03:33:10 +00001485
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001486 if (!HasAVXType)
1487 return true;
1488 }
John McCallcbc038a2011-09-21 08:08:30 +00001489
John McCalla729c622012-02-17 03:33:10 +00001490 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001491 }
1492
Craig Topper4f12f102014-03-12 06:41:41 +00001493 llvm::Constant *
1494 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001495 unsigned Sig = (0xeb << 0) | // jmp rel8
1496 (0x0a << 8) | // .+0x0c
1497 ('F' << 16) |
1498 ('T' << 24);
1499 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1500 }
1501
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001502};
1503
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001504static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1505 // If the argument does not end in .lib, automatically add the suffix. This
1506 // matches the behavior of MSVC.
1507 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001508 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001509 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001510 return ArgStr;
1511}
1512
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001513class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1514public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001515 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1516 bool d, bool p, bool w, unsigned RegParms)
1517 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001518
1519 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001520 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001521 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001522 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001523 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001524
1525 void getDetectMismatchOption(llvm::StringRef Name,
1526 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001527 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001528 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001529 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001530};
1531
Chris Lattner04dc9572010-08-31 16:44:54 +00001532class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1533public:
1534 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1535 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1536
Craig Topper4f12f102014-03-12 06:41:41 +00001537 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001538 return 7;
1539 }
1540
1541 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001542 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001543 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001544
Chris Lattner04dc9572010-08-31 16:44:54 +00001545 // 0-15 are the 16 integer registers.
1546 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001547 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001548 return false;
1549 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001550
1551 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001552 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001553 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001554 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001555 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001556
1557 void getDetectMismatchOption(llvm::StringRef Name,
1558 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001559 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001560 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001561 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001562};
1563
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001564}
1565
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001566void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1567 Class &Hi) const {
1568 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1569 //
1570 // (a) If one of the classes is Memory, the whole argument is passed in
1571 // memory.
1572 //
1573 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1574 // memory.
1575 //
1576 // (c) If the size of the aggregate exceeds two eightbytes and the first
1577 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1578 // argument is passed in memory. NOTE: This is necessary to keep the
1579 // ABI working for processors that don't support the __m256 type.
1580 //
1581 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1582 //
1583 // Some of these are enforced by the merging logic. Others can arise
1584 // only with unions; for example:
1585 // union { _Complex double; unsigned; }
1586 //
1587 // Note that clauses (b) and (c) were added in 0.98.
1588 //
1589 if (Hi == Memory)
1590 Lo = Memory;
1591 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1592 Lo = Memory;
1593 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1594 Lo = Memory;
1595 if (Hi == SSEUp && Lo != SSE)
1596 Hi = SSE;
1597}
1598
Chris Lattnerd776fb12010-06-28 21:43:59 +00001599X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001600 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1601 // classified recursively so that always two fields are
1602 // considered. The resulting class is calculated according to
1603 // the classes of the fields in the eightbyte:
1604 //
1605 // (a) If both classes are equal, this is the resulting class.
1606 //
1607 // (b) If one of the classes is NO_CLASS, the resulting class is
1608 // the other class.
1609 //
1610 // (c) If one of the classes is MEMORY, the result is the MEMORY
1611 // class.
1612 //
1613 // (d) If one of the classes is INTEGER, the result is the
1614 // INTEGER.
1615 //
1616 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1617 // MEMORY is used as class.
1618 //
1619 // (f) Otherwise class SSE is used.
1620
1621 // Accum should never be memory (we should have returned) or
1622 // ComplexX87 (because this cannot be passed in a structure).
1623 assert((Accum != Memory && Accum != ComplexX87) &&
1624 "Invalid accumulated classification during merge.");
1625 if (Accum == Field || Field == NoClass)
1626 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001627 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001628 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001629 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001630 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001631 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001632 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001633 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1634 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001635 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001636 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001637}
1638
Chris Lattner5c740f12010-06-30 19:14:05 +00001639void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001640 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001641 // FIXME: This code can be simplified by introducing a simple value class for
1642 // Class pairs with appropriate constructor methods for the various
1643 // situations.
1644
1645 // FIXME: Some of the split computations are wrong; unaligned vectors
1646 // shouldn't be passed in registers for example, so there is no chance they
1647 // can straddle an eightbyte. Verify & simplify.
1648
1649 Lo = Hi = NoClass;
1650
1651 Class &Current = OffsetBase < 64 ? Lo : Hi;
1652 Current = Memory;
1653
John McCall9dd450b2009-09-21 23:43:11 +00001654 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001655 BuiltinType::Kind k = BT->getKind();
1656
1657 if (k == BuiltinType::Void) {
1658 Current = NoClass;
1659 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1660 Lo = Integer;
1661 Hi = Integer;
1662 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1663 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001664 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1665 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001666 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001667 Current = SSE;
1668 } else if (k == BuiltinType::LongDouble) {
1669 Lo = X87;
1670 Hi = X87Up;
1671 }
1672 // FIXME: _Decimal32 and _Decimal64 are SSE.
1673 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001674 return;
1675 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001676
Chris Lattnerd776fb12010-06-28 21:43:59 +00001677 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001678 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001679 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001680 return;
1681 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001682
Chris Lattnerd776fb12010-06-28 21:43:59 +00001683 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001684 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001685 return;
1686 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001687
Chris Lattnerd776fb12010-06-28 21:43:59 +00001688 if (Ty->isMemberPointerType()) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001689 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001690 Lo = Hi = Integer;
1691 else
1692 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001693 return;
1694 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001695
Chris Lattnerd776fb12010-06-28 21:43:59 +00001696 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001697 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001698 if (Size == 32) {
1699 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1700 // float> as integer.
1701 Current = Integer;
1702
1703 // If this type crosses an eightbyte boundary, it should be
1704 // split.
1705 uint64_t EB_Real = (OffsetBase) / 64;
1706 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1707 if (EB_Real != EB_Imag)
1708 Hi = Lo;
1709 } else if (Size == 64) {
1710 // gcc passes <1 x double> in memory. :(
1711 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1712 return;
1713
1714 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001715 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001716 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1717 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1718 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001719 Current = Integer;
1720 else
1721 Current = SSE;
1722
1723 // If this type crosses an eightbyte boundary, it should be
1724 // split.
1725 if (OffsetBase && OffsetBase != 64)
1726 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001727 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001728 // Arguments of 256-bits are split into four eightbyte chunks. The
1729 // least significant one belongs to class SSE and all the others to class
1730 // SSEUP. The original Lo and Hi design considers that types can't be
1731 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1732 // This design isn't correct for 256-bits, but since there're no cases
1733 // where the upper parts would need to be inspected, avoid adding
1734 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001735 //
1736 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1737 // registers if they are "named", i.e. not part of the "..." of a
1738 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001739 Lo = SSE;
1740 Hi = SSEUp;
1741 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001742 return;
1743 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001744
Chris Lattnerd776fb12010-06-28 21:43:59 +00001745 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001746 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001747
Chris Lattner2b037972010-07-29 02:01:43 +00001748 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001749 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001750 if (Size <= 64)
1751 Current = Integer;
1752 else if (Size <= 128)
1753 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001754 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001755 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001756 else if (ET == getContext().DoubleTy ||
1757 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001758 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001759 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001760 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001761 Current = ComplexX87;
1762
1763 // If this complex type crosses an eightbyte boundary then it
1764 // should be split.
1765 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001766 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001767 if (Hi == NoClass && EB_Real != EB_Imag)
1768 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001769
Chris Lattnerd776fb12010-06-28 21:43:59 +00001770 return;
1771 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001772
Chris Lattner2b037972010-07-29 02:01:43 +00001773 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001774 // Arrays are treated like structures.
1775
Chris Lattner2b037972010-07-29 02:01:43 +00001776 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001777
1778 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001779 // than four eightbytes, ..., it has class MEMORY.
1780 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001781 return;
1782
1783 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1784 // fields, it has class MEMORY.
1785 //
1786 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001787 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001788 return;
1789
1790 // Otherwise implement simplified merge. We could be smarter about
1791 // this, but it isn't worth it and would be harder to verify.
1792 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001793 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001794 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001795
1796 // The only case a 256-bit wide vector could be used is when the array
1797 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1798 // to work for sizes wider than 128, early check and fallback to memory.
1799 if (Size > 128 && EltSize != 256)
1800 return;
1801
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001802 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1803 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001804 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001805 Lo = merge(Lo, FieldLo);
1806 Hi = merge(Hi, FieldHi);
1807 if (Lo == Memory || Hi == Memory)
1808 break;
1809 }
1810
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001811 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001812 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001813 return;
1814 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001815
Chris Lattnerd776fb12010-06-28 21:43:59 +00001816 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001817 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001818
1819 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001820 // than four eightbytes, ..., it has class MEMORY.
1821 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001822 return;
1823
Anders Carlsson20759ad2009-09-16 15:53:40 +00001824 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1825 // copy constructor or a non-trivial destructor, it is passed by invisible
1826 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001827 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001828 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001829
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001830 const RecordDecl *RD = RT->getDecl();
1831
1832 // Assume variable sized types are passed in memory.
1833 if (RD->hasFlexibleArrayMember())
1834 return;
1835
Chris Lattner2b037972010-07-29 02:01:43 +00001836 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001837
1838 // Reset Lo class, this will be recomputed.
1839 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001840
1841 // If this is a C++ record, classify the bases first.
1842 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001843 for (const auto &I : CXXRD->bases()) {
1844 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001845 "Unexpected base class!");
1846 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001847 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001848
1849 // Classify this field.
1850 //
1851 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1852 // single eightbyte, each is classified separately. Each eightbyte gets
1853 // initialized to class NO_CLASS.
1854 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001855 uint64_t Offset =
1856 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001857 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001858 Lo = merge(Lo, FieldLo);
1859 Hi = merge(Hi, FieldHi);
1860 if (Lo == Memory || Hi == Memory)
1861 break;
1862 }
1863 }
1864
1865 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001866 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001867 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001868 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001869 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1870 bool BitField = i->isBitField();
1871
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001872 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1873 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001874 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001875 // The only case a 256-bit wide vector could be used is when the struct
1876 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1877 // to work for sizes wider than 128, early check and fallback to memory.
1878 //
1879 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1880 Lo = Memory;
1881 return;
1882 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001883 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00001884 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001885 Lo = Memory;
1886 return;
1887 }
1888
1889 // Classify this field.
1890 //
1891 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1892 // exceeds a single eightbyte, each is classified
1893 // separately. Each eightbyte gets initialized to class
1894 // NO_CLASS.
1895 Class FieldLo, FieldHi;
1896
1897 // Bit-fields require special handling, they do not force the
1898 // structure to be passed in memory even if unaligned, and
1899 // therefore they can straddle an eightbyte.
1900 if (BitField) {
1901 // Ignore padding bit-fields.
1902 if (i->isUnnamedBitfield())
1903 continue;
1904
1905 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00001906 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001907
1908 uint64_t EB_Lo = Offset / 64;
1909 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00001910
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001911 if (EB_Lo) {
1912 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1913 FieldLo = NoClass;
1914 FieldHi = Integer;
1915 } else {
1916 FieldLo = Integer;
1917 FieldHi = EB_Hi ? Integer : NoClass;
1918 }
1919 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00001920 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001921 Lo = merge(Lo, FieldLo);
1922 Hi = merge(Hi, FieldHi);
1923 if (Lo == Memory || Hi == Memory)
1924 break;
1925 }
1926
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001927 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001928 }
1929}
1930
Chris Lattner22a931e2010-06-29 06:01:59 +00001931ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001932 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1933 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00001934 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00001935 // Treat an enum type as its underlying type.
1936 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1937 Ty = EnumTy->getDecl()->getIntegerType();
1938
1939 return (Ty->isPromotableIntegerType() ?
1940 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1941 }
1942
1943 return ABIArgInfo::getIndirect(0);
1944}
1945
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001946bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1947 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1948 uint64_t Size = getContext().getTypeSize(VecTy);
1949 unsigned LargestVector = HasAVX ? 256 : 128;
1950 if (Size <= 64 || Size > LargestVector)
1951 return true;
1952 }
1953
1954 return false;
1955}
1956
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001957ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1958 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001959 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1960 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001961 //
1962 // This assumption is optimistic, as there could be free registers available
1963 // when we need to pass this argument in memory, and LLVM could try to pass
1964 // the argument in the free register. This does not seem to happen currently,
1965 // but this code would be much safer if we could mark the argument with
1966 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001967 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00001968 // Treat an enum type as its underlying type.
1969 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1970 Ty = EnumTy->getDecl()->getIntegerType();
1971
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00001972 return (Ty->isPromotableIntegerType() ?
1973 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00001974 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001975
Mark Lacey3825e832013-10-06 01:33:34 +00001976 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001977 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00001978
Chris Lattner44c2b902011-05-22 23:21:23 +00001979 // Compute the byval alignment. We specify the alignment of the byval in all
1980 // cases so that the mid-level optimizer knows the alignment of the byval.
1981 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001982
1983 // Attempt to avoid passing indirect results using byval when possible. This
1984 // is important for good codegen.
1985 //
1986 // We do this by coercing the value into a scalar type which the backend can
1987 // handle naturally (i.e., without using byval).
1988 //
1989 // For simplicity, we currently only do this when we have exhausted all of the
1990 // free integer registers. Doing this when there are free integer registers
1991 // would require more care, as we would have to ensure that the coerced value
1992 // did not claim the unused register. That would require either reording the
1993 // arguments to the function (so that any subsequent inreg values came first),
1994 // or only doing this optimization when there were no following arguments that
1995 // might be inreg.
1996 //
1997 // We currently expect it to be rare (particularly in well written code) for
1998 // arguments to be passed on the stack when there are still free integer
1999 // registers available (this would typically imply large structs being passed
2000 // by value), so this seems like a fair tradeoff for now.
2001 //
2002 // We can revisit this if the backend grows support for 'onstack' parameter
2003 // attributes. See PR12193.
2004 if (freeIntRegs == 0) {
2005 uint64_t Size = getContext().getTypeSize(Ty);
2006
2007 // If this type fits in an eightbyte, coerce it into the matching integral
2008 // type, which will end up on the stack (with alignment 8).
2009 if (Align == 8 && Size <= 64)
2010 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2011 Size));
2012 }
2013
Chris Lattner44c2b902011-05-22 23:21:23 +00002014 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002015}
2016
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002017/// GetByteVectorType - The ABI specifies that a value should be passed in an
2018/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00002019/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002020llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002021 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002022
Chris Lattner9fa15c32010-07-29 05:02:29 +00002023 // Wrapper structs that just contain vectors are passed just like vectors,
2024 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002025 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00002026 while (STy && STy->getNumElements() == 1) {
2027 IRType = STy->getElementType(0);
2028 STy = dyn_cast<llvm::StructType>(IRType);
2029 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002030
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00002031 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002032 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2033 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002034 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00002035 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00002036 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2037 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2038 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2039 EltTy->isIntegerTy(128)))
2040 return VT;
2041 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002042
Chris Lattner4200fe42010-07-29 04:56:46 +00002043 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2044}
2045
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002046/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2047/// is known to either be off the end of the specified type or being in
2048/// alignment padding. The user type specified is known to be at most 128 bits
2049/// in size, and have passed through X86_64ABIInfo::classify with a successful
2050/// classification that put one of the two halves in the INTEGER class.
2051///
2052/// It is conservatively correct to return false.
2053static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2054 unsigned EndBit, ASTContext &Context) {
2055 // If the bytes being queried are off the end of the type, there is no user
2056 // data hiding here. This handles analysis of builtins, vectors and other
2057 // types that don't contain interesting padding.
2058 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2059 if (TySize <= StartBit)
2060 return true;
2061
Chris Lattner98076a22010-07-29 07:43:55 +00002062 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2063 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2064 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2065
2066 // Check each element to see if the element overlaps with the queried range.
2067 for (unsigned i = 0; i != NumElts; ++i) {
2068 // If the element is after the span we care about, then we're done..
2069 unsigned EltOffset = i*EltSize;
2070 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002071
Chris Lattner98076a22010-07-29 07:43:55 +00002072 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2073 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2074 EndBit-EltOffset, Context))
2075 return false;
2076 }
2077 // If it overlaps no elements, then it is safe to process as padding.
2078 return true;
2079 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002080
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002081 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2082 const RecordDecl *RD = RT->getDecl();
2083 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002084
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002085 // If this is a C++ record, check the bases first.
2086 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002087 for (const auto &I : CXXRD->bases()) {
2088 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002089 "Unexpected base class!");
2090 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002091 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002092
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002093 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002094 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002095 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002096
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002097 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002098 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002099 EndBit-BaseOffset, Context))
2100 return false;
2101 }
2102 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002103
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002104 // Verify that no field has data that overlaps the region of interest. Yes
2105 // this could be sped up a lot by being smarter about queried fields,
2106 // however we're only looking at structs up to 16 bytes, so we don't care
2107 // much.
2108 unsigned idx = 0;
2109 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2110 i != e; ++i, ++idx) {
2111 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002112
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002113 // If we found a field after the region we care about, then we're done.
2114 if (FieldOffset >= EndBit) break;
2115
2116 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2117 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2118 Context))
2119 return false;
2120 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002121
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002122 // If nothing in this record overlapped the area of interest, then we're
2123 // clean.
2124 return true;
2125 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002126
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002127 return false;
2128}
2129
Chris Lattnere556a712010-07-29 18:39:32 +00002130/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2131/// float member at the specified offset. For example, {int,{float}} has a
2132/// float at offset 4. It is conservatively correct for this routine to return
2133/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002134static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002135 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002136 // Base case if we find a float.
2137 if (IROffset == 0 && IRType->isFloatTy())
2138 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002139
Chris Lattnere556a712010-07-29 18:39:32 +00002140 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002141 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002142 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2143 unsigned Elt = SL->getElementContainingOffset(IROffset);
2144 IROffset -= SL->getElementOffset(Elt);
2145 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2146 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002147
Chris Lattnere556a712010-07-29 18:39:32 +00002148 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002149 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2150 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002151 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2152 IROffset -= IROffset/EltSize*EltSize;
2153 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2154 }
2155
2156 return false;
2157}
2158
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002159
2160/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2161/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002162llvm::Type *X86_64ABIInfo::
2163GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002164 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002165 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002166 // pass as float if the last 4 bytes is just padding. This happens for
2167 // structs that contain 3 floats.
2168 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2169 SourceOffset*8+64, getContext()))
2170 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002171
Chris Lattnere556a712010-07-29 18:39:32 +00002172 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2173 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2174 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002175 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2176 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002177 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002178
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002179 return llvm::Type::getDoubleTy(getVMContext());
2180}
2181
2182
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002183/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2184/// an 8-byte GPR. This means that we either have a scalar or we are talking
2185/// about the high or low part of an up-to-16-byte struct. This routine picks
2186/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002187/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2188/// etc).
2189///
2190/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2191/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2192/// the 8-byte value references. PrefType may be null.
2193///
Alp Toker9907f082014-07-09 14:06:35 +00002194/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002195/// an offset into this that we're processing (which is always either 0 or 8).
2196///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002197llvm::Type *X86_64ABIInfo::
2198GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002199 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002200 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2201 // returning an 8-byte unit starting with it. See if we can safely use it.
2202 if (IROffset == 0) {
2203 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002204 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2205 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002206 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002207
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002208 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2209 // goodness in the source type is just tail padding. This is allowed to
2210 // kick in for struct {double,int} on the int, but not on
2211 // struct{double,int,int} because we wouldn't return the second int. We
2212 // have to do this analysis on the source type because we can't depend on
2213 // unions being lowered a specific way etc.
2214 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002215 IRType->isIntegerTy(32) ||
2216 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2217 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2218 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002219
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002220 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2221 SourceOffset*8+64, getContext()))
2222 return IRType;
2223 }
2224 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002225
Chris Lattner2192fe52011-07-18 04:24:23 +00002226 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002227 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002228 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002229 if (IROffset < SL->getSizeInBytes()) {
2230 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2231 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002232
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002233 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2234 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002235 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002236 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002237
Chris Lattner2192fe52011-07-18 04:24:23 +00002238 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002239 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002240 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002241 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002242 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2243 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002244 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002245
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002246 // Okay, we don't have any better idea of what to pass, so we pass this in an
2247 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002248 unsigned TySizeInBytes =
2249 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002250
Chris Lattner3f763422010-07-29 17:34:39 +00002251 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002252
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002253 // It is always safe to classify this as an integer type up to i64 that
2254 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002255 return llvm::IntegerType::get(getVMContext(),
2256 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002257}
2258
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002259
2260/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2261/// be used as elements of a two register pair to pass or return, return a
2262/// first class aggregate to represent them. For example, if the low part of
2263/// a by-value argument should be passed as i32* and the high part as float,
2264/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002265static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002266GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002267 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002268 // In order to correctly satisfy the ABI, we need to the high part to start
2269 // at offset 8. If the high and low parts we inferred are both 4-byte types
2270 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2271 // the second element at offset 8. Check for this:
2272 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2273 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmowdd31ca12012-10-08 16:25:52 +00002274 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002275 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002276
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002277 // To handle this, we have to increase the size of the low part so that the
2278 // second element will start at an 8 byte offset. We can't increase the size
2279 // of the second element because it might make us access off the end of the
2280 // struct.
2281 if (HiStart != 8) {
2282 // There are only two sorts of types the ABI generation code can produce for
2283 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2284 // Promote these to a larger type.
2285 if (Lo->isFloatTy())
2286 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2287 else {
2288 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2289 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2290 }
2291 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002292
Chris Lattnera5f58b02011-07-09 17:41:47 +00002293 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002294
2295
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002296 // Verify that the second element is at an 8-byte offset.
2297 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2298 "Invalid x86-64 argument pair!");
2299 return Result;
2300}
2301
Chris Lattner31faff52010-07-28 23:06:14 +00002302ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002303classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002304 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2305 // classification algorithm.
2306 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002307 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002308
2309 // Check some invariants.
2310 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002311 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2312
Craig Topper8a13c412014-05-21 05:09:00 +00002313 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002314 switch (Lo) {
2315 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002316 if (Hi == NoClass)
2317 return ABIArgInfo::getIgnore();
2318 // If the low part is just padding, it takes no register, leave ResType
2319 // null.
2320 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2321 "Unknown missing lo part");
2322 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002323
2324 case SSEUp:
2325 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002326 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002327
2328 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2329 // hidden argument.
2330 case Memory:
2331 return getIndirectReturnResult(RetTy);
2332
2333 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2334 // available register of the sequence %rax, %rdx is used.
2335 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002336 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002337
Chris Lattner1f3a0632010-07-29 21:42:50 +00002338 // If we have a sign or zero extended integer, make sure to return Extend
2339 // so that the parameter gets the right LLVM IR attributes.
2340 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2341 // Treat an enum type as its underlying type.
2342 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2343 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002344
Chris Lattner1f3a0632010-07-29 21:42:50 +00002345 if (RetTy->isIntegralOrEnumerationType() &&
2346 RetTy->isPromotableIntegerType())
2347 return ABIArgInfo::getExtend();
2348 }
Chris Lattner31faff52010-07-28 23:06:14 +00002349 break;
2350
2351 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2352 // available SSE register of the sequence %xmm0, %xmm1 is used.
2353 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002354 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002355 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002356
2357 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2358 // returned on the X87 stack in %st0 as 80-bit x87 number.
2359 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002360 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002361 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002362
2363 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2364 // part of the value is returned in %st0 and the imaginary part in
2365 // %st1.
2366 case ComplexX87:
2367 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002368 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002369 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner31faff52010-07-28 23:06:14 +00002370 NULL);
2371 break;
2372 }
2373
Craig Topper8a13c412014-05-21 05:09:00 +00002374 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002375 switch (Hi) {
2376 // Memory was handled previously and X87 should
2377 // never occur as a hi class.
2378 case Memory:
2379 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002380 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002381
2382 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002383 case NoClass:
2384 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002385
Chris Lattner52b3c132010-09-01 00:20:33 +00002386 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002387 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002388 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2389 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002390 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002391 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002392 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002393 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2394 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002395 break;
2396
2397 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002398 // is passed in the next available eightbyte chunk if the last used
2399 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002400 //
Chris Lattner57540c52011-04-15 05:22:18 +00002401 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002402 case SSEUp:
2403 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002404 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002405 break;
2406
2407 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2408 // returned together with the previous X87 value in %st0.
2409 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002410 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002411 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002412 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002413 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002414 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002415 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002416 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2417 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002418 }
Chris Lattner31faff52010-07-28 23:06:14 +00002419 break;
2420 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002421
Chris Lattner52b3c132010-09-01 00:20:33 +00002422 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002423 // known to pass in the high eightbyte of the result. We do this by forming a
2424 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002425 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002426 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002427
Chris Lattner1f3a0632010-07-29 21:42:50 +00002428 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002429}
2430
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002431ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002432 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2433 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002434 const
2435{
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002436 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002437 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002438
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002439 // Check some invariants.
2440 // FIXME: Enforce these by construction.
2441 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002442 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2443
2444 neededInt = 0;
2445 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002446 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002447 switch (Lo) {
2448 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002449 if (Hi == NoClass)
2450 return ABIArgInfo::getIgnore();
2451 // If the low part is just padding, it takes no register, leave ResType
2452 // null.
2453 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2454 "Unknown missing lo part");
2455 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002456
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002457 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2458 // on the stack.
2459 case Memory:
2460
2461 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2462 // COMPLEX_X87, it is passed in memory.
2463 case X87:
2464 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002465 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002466 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002467 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468
2469 case SSEUp:
2470 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002471 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002472
2473 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2474 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2475 // and %r9 is used.
2476 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002477 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002478
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002479 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002480 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002481
2482 // If we have a sign or zero extended integer, make sure to return Extend
2483 // so that the parameter gets the right LLVM IR attributes.
2484 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2485 // Treat an enum type as its underlying type.
2486 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2487 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002488
Chris Lattner1f3a0632010-07-29 21:42:50 +00002489 if (Ty->isIntegralOrEnumerationType() &&
2490 Ty->isPromotableIntegerType())
2491 return ABIArgInfo::getExtend();
2492 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002493
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002494 break;
2495
2496 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2497 // available SSE register is used, the registers are taken in the
2498 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002499 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002500 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002501 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002502 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002503 break;
2504 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002505 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002506
Craig Topper8a13c412014-05-21 05:09:00 +00002507 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002508 switch (Hi) {
2509 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002510 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002511 // which is passed in memory.
2512 case Memory:
2513 case X87:
2514 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002515 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002516
2517 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002518
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002519 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002520 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002521 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002522 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002523
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002524 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2525 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002526 break;
2527
2528 // X87Up generally doesn't occur here (long double is passed in
2529 // memory), except in situations involving unions.
2530 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002531 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002532 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002533
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002534 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2535 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002536
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537 ++neededSSE;
2538 break;
2539
2540 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2541 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002542 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002543 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002544 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002545 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002546 break;
2547 }
2548
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002549 // If a high part was specified, merge it together with the low part. It is
2550 // known to pass in the high eightbyte of the result. We do this by forming a
2551 // first class struct aggregate with the high and low part: {low, high}
2552 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002553 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002554
Chris Lattner1f3a0632010-07-29 21:42:50 +00002555 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002556}
2557
Chris Lattner22326a12010-07-29 02:31:05 +00002558void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002559
Reid Kleckner40ca9132014-05-13 22:05:45 +00002560 if (!getCXXABI().classifyReturnType(FI))
2561 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002562
2563 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002564 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002565
2566 // If the return value is indirect, then the hidden argument is consuming one
2567 // integer register.
2568 if (FI.getReturnInfo().isIndirect())
2569 --freeIntRegs;
2570
Eli Friedman96fd2642013-06-12 00:13:45 +00002571 bool isVariadic = FI.isVariadic();
2572 unsigned numRequiredArgs = 0;
2573 if (isVariadic)
2574 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2575
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002576 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2577 // get assigned (in left-to-right order) for passing as follows...
2578 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2579 it != ie; ++it) {
Eli Friedman96fd2642013-06-12 00:13:45 +00002580 bool isNamedArg = true;
2581 if (isVariadic)
Aaron Ballman6a302642013-06-12 15:03:45 +00002582 isNamedArg = (it - FI.arg_begin()) <
2583 static_cast<signed>(numRequiredArgs);
Eli Friedman96fd2642013-06-12 00:13:45 +00002584
Bill Wendling9987c0e2010-10-18 23:51:38 +00002585 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002586 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00002587 neededSSE, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002588
2589 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2590 // eightbyte of an argument, the whole argument is passed on the
2591 // stack. If registers have already been assigned for some
2592 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002593 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002594 freeIntRegs -= neededInt;
2595 freeSSERegs -= neededSSE;
2596 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002597 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002598 }
2599 }
2600}
2601
2602static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2603 QualType Ty,
2604 CodeGenFunction &CGF) {
2605 llvm::Value *overflow_arg_area_p =
2606 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2607 llvm::Value *overflow_arg_area =
2608 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2609
2610 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2611 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002612 // It isn't stated explicitly in the standard, but in practice we use
2613 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002614 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2615 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002616 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002617 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002618 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002619 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2620 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002621 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002622 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002623 overflow_arg_area =
2624 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2625 overflow_arg_area->getType(),
2626 "overflow_arg_area.align");
2627 }
2628
2629 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002630 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002631 llvm::Value *Res =
2632 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002633 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002634
2635 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2636 // l->overflow_arg_area + sizeof(type).
2637 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2638 // an 8 byte boundary.
2639
2640 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002641 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002642 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002643 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2644 "overflow_arg_area.next");
2645 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2646
2647 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2648 return Res;
2649}
2650
2651llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2652 CodeGenFunction &CGF) const {
2653 // Assume that va_list type is correct; should be pointer to LLVM type:
2654 // struct {
2655 // i32 gp_offset;
2656 // i32 fp_offset;
2657 // i8* overflow_arg_area;
2658 // i8* reg_save_area;
2659 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002660 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002661
Chris Lattner9723d6c2010-03-11 18:19:55 +00002662 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002663 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2664 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002665
2666 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2667 // in the registers. If not go to step 7.
2668 if (!neededInt && !neededSSE)
2669 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2670
2671 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2672 // general purpose registers needed to pass type and num_fp to hold
2673 // the number of floating point registers needed.
2674
2675 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2676 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2677 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2678 //
2679 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2680 // register save space).
2681
Craig Topper8a13c412014-05-21 05:09:00 +00002682 llvm::Value *InRegs = nullptr;
2683 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2684 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685 if (neededInt) {
2686 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2687 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002688 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2689 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 }
2691
2692 if (neededSSE) {
2693 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2694 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2695 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002696 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2697 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2699 }
2700
2701 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2702 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2703 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2704 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2705
2706 // Emit code to load the value if it was passed in registers.
2707
2708 CGF.EmitBlock(InRegBlock);
2709
2710 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2711 // an offset of l->gp_offset and/or l->fp_offset. This may require
2712 // copying to a temporary location in case the parameter is passed
2713 // in different register classes or requires an alignment greater
2714 // than 8 for general purpose registers and 16 for XMM registers.
2715 //
2716 // FIXME: This really results in shameful code when we end up needing to
2717 // collect arguments from different places; often what should result in a
2718 // simple assembling of a structure from scattered addresses has many more
2719 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002720 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002721 llvm::Value *RegAddr =
2722 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2723 "reg_save_area");
2724 if (neededInt && neededSSE) {
2725 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002726 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002727 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002728 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2729 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002730 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002731 llvm::Type *TyLo = ST->getElementType(0);
2732 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002733 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002734 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002735 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2736 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002737 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2738 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002739 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2740 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002741 llvm::Value *V =
2742 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2743 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2744 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2745 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2746
Owen Anderson170229f2009-07-14 23:10:40 +00002747 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002748 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002749 } else if (neededInt) {
2750 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2751 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002752 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002753
2754 // Copy to a temporary if necessary to ensure the appropriate alignment.
2755 std::pair<CharUnits, CharUnits> SizeAlign =
2756 CGF.getContext().getTypeInfoInChars(Ty);
2757 uint64_t TySize = SizeAlign.first.getQuantity();
2758 unsigned TyAlign = SizeAlign.second.getQuantity();
2759 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002760 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2761 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2762 RegAddr = Tmp;
2763 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002764 } else if (neededSSE == 1) {
2765 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2766 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2767 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002768 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002769 assert(neededSSE == 2 && "Invalid number of needed registers!");
2770 // SSE registers are spaced 16 bytes apart in the register save
2771 // area, we need to collect the two eightbytes together.
2772 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002773 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002774 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002775 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002776 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002777 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2778 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2779 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002780 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2781 DblPtrTy));
2782 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2783 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2784 DblPtrTy));
2785 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2786 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2787 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002788 }
2789
2790 // AMD64-ABI 3.5.7p5: Step 5. Set:
2791 // l->gp_offset = l->gp_offset + num_gp * 8
2792 // l->fp_offset = l->fp_offset + num_fp * 16.
2793 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002794 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002795 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2796 gp_offset_p);
2797 }
2798 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002799 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002800 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2801 fp_offset_p);
2802 }
2803 CGF.EmitBranch(ContBlock);
2804
2805 // Emit code to load the value if it was passed in memory.
2806
2807 CGF.EmitBlock(InMemBlock);
2808 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2809
2810 // Return the appropriate result.
2811
2812 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002813 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002814 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002815 ResAddr->addIncoming(RegAddr, InRegBlock);
2816 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002817 return ResAddr;
2818}
2819
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002820ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002821
2822 if (Ty->isVoidType())
2823 return ABIArgInfo::getIgnore();
2824
2825 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2826 Ty = EnumTy->getDecl()->getIntegerType();
2827
2828 uint64_t Size = getContext().getTypeSize(Ty);
2829
Reid Kleckner9005f412014-05-02 00:51:20 +00002830 const RecordType *RT = Ty->getAs<RecordType>();
2831 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002832 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002833 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002834 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2835 }
2836
2837 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002838 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2839
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002840 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00002841 if (Size == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002842 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2843 Size));
Reid Kleckner9005f412014-05-02 00:51:20 +00002844 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002845
Reid Klecknerec87fec2014-05-02 01:17:12 +00002846 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002847 // If the member pointer is represented by an LLVM int or ptr, pass it
2848 // directly.
2849 llvm::Type *LLTy = CGT.ConvertType(Ty);
2850 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2851 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002852 }
2853
2854 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002855 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2856 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner9005f412014-05-02 00:51:20 +00002857 if (Size > 64 || !llvm::isPowerOf2_64(Size))
2858 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002859
Reid Kleckner9005f412014-05-02 00:51:20 +00002860 // Otherwise, coerce it to a small integer.
2861 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002862 }
2863
Julien Lerouge10dcff82014-08-27 00:36:55 +00002864 // Bool type is always extended to the ABI, other builtin types are not
2865 // extended.
2866 const BuiltinType *BT = Ty->getAs<BuiltinType>();
2867 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00002868 return ABIArgInfo::getExtend();
2869
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002870 return ABIArgInfo::getDirect();
2871}
2872
2873void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002874 if (!getCXXABI().classifyReturnType(FI))
2875 FI.getReturnInfo() = classify(FI.getReturnType(), true);
Reid Kleckner37abaca2014-05-09 22:46:15 +00002876
Aaron Ballmanec47bc22014-03-17 18:10:01 +00002877 for (auto &I : FI.arguments())
2878 I.info = classify(I.type, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002879}
2880
Chris Lattner04dc9572010-08-31 16:44:54 +00002881llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2882 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00002883 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00002884
Chris Lattner04dc9572010-08-31 16:44:54 +00002885 CGBuilderTy &Builder = CGF.Builder;
2886 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2887 "ap");
2888 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2889 llvm::Type *PTy =
2890 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2891 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2892
2893 uint64_t Offset =
2894 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2895 llvm::Value *NextAddr =
2896 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2897 "ap.next");
2898 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2899
2900 return AddrTyped;
2901}
Chris Lattner0cf24192010-06-28 20:05:43 +00002902
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002903namespace {
2904
Derek Schuffa2020962012-10-16 22:30:41 +00002905class NaClX86_64ABIInfo : public ABIInfo {
2906 public:
2907 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2908 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00002909 void computeInfo(CGFunctionInfo &FI) const override;
2910 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2911 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00002912 private:
2913 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2914 X86_64ABIInfo NInfo; // Used for everything else.
2915};
2916
2917class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2918 public:
2919 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2920 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2921};
2922
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00002923}
2924
Derek Schuffa2020962012-10-16 22:30:41 +00002925void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2926 if (FI.getASTCallingConvention() == CC_PnaclCall)
2927 PInfo.computeInfo(FI);
2928 else
2929 NInfo.computeInfo(FI);
2930}
2931
2932llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2933 CodeGenFunction &CGF) const {
2934 // Always use the native convention; calling pnacl-style varargs functions
2935 // is unuspported.
2936 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2937}
2938
2939
John McCallea8d8bb2010-03-11 00:10:12 +00002940// PowerPC-32
2941
2942namespace {
2943class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2944public:
Chris Lattner2b037972010-07-29 02:01:43 +00002945 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002946
Craig Topper4f12f102014-03-12 06:41:41 +00002947 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00002948 // This is recovered from gcc output.
2949 return 1; // r1 is the dedicated stack pointer
2950 }
2951
2952 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002953 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00002954};
2955
2956}
2957
2958bool
2959PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2960 llvm::Value *Address) const {
2961 // This is calculated from the LLVM and GCC tables and verified
2962 // against gcc output. AFAIK all ABIs use the same encoding.
2963
2964 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00002965
Chris Lattnerece04092012-02-07 00:39:47 +00002966 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00002967 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2968 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2969 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2970
2971 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00002972 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00002973
2974 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00002975 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00002976
2977 // 64-76 are various 4-byte special-purpose registers:
2978 // 64: mq
2979 // 65: lr
2980 // 66: ctr
2981 // 67: ap
2982 // 68-75 cr0-7
2983 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00002984 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00002985
2986 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00002987 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00002988
2989 // 109: vrsave
2990 // 110: vscr
2991 // 111: spe_acc
2992 // 112: spefscr
2993 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00002994 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00002995
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002996 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00002997}
2998
Roman Divackyd966e722012-05-09 18:22:46 +00002999// PowerPC-64
3000
3001namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003002/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3003class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003004public:
3005 enum ABIKind {
3006 ELFv1 = 0,
3007 ELFv2
3008 };
3009
3010private:
3011 static const unsigned GPRBits = 64;
3012 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003013
3014public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003015 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3016 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003017
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003018 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003019 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003020 bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3021 uint64_t &Members) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003022
3023 ABIArgInfo classifyReturnType(QualType RetTy) const;
3024 ABIArgInfo classifyArgumentType(QualType Ty) const;
3025
Bill Schmidt84d37792012-10-12 19:26:17 +00003026 // TODO: We can add more logic to computeInfo to improve performance.
3027 // Example: For aggregate arguments that fit in a register, we could
3028 // use getDirectInReg (as is done below for structs containing a single
3029 // floating-point value) to avoid pushing them to memory on function
3030 // entry. This would require changing the logic in PPCISelLowering
3031 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003032 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003033 if (!getCXXABI().classifyReturnType(FI))
3034 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003035 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003036 // We rely on the default argument classification for the most part.
3037 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003038 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003039 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003040 if (T) {
3041 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003042 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3043 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003044 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003045 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003046 continue;
3047 }
3048 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003049 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003050 }
3051 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003052
Craig Topper4f12f102014-03-12 06:41:41 +00003053 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3054 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003055};
3056
3057class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3058public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003059 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3060 PPC64_SVR4_ABIInfo::ABIKind Kind)
3061 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003062
Craig Topper4f12f102014-03-12 06:41:41 +00003063 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003064 // This is recovered from gcc output.
3065 return 1; // r1 is the dedicated stack pointer
3066 }
3067
3068 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003069 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003070};
3071
Roman Divackyd966e722012-05-09 18:22:46 +00003072class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3073public:
3074 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3075
Craig Topper4f12f102014-03-12 06:41:41 +00003076 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003077 // This is recovered from gcc output.
3078 return 1; // r1 is the dedicated stack pointer
3079 }
3080
3081 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003082 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003083};
3084
3085}
3086
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003087// Return true if the ABI requires Ty to be passed sign- or zero-
3088// extended to 64 bits.
3089bool
3090PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3091 // Treat an enum type as its underlying type.
3092 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3093 Ty = EnumTy->getDecl()->getIntegerType();
3094
3095 // Promotable integer types are required to be promoted by the ABI.
3096 if (Ty->isPromotableIntegerType())
3097 return true;
3098
3099 // In addition to the usual promotable integer types, we also need to
3100 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3101 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3102 switch (BT->getKind()) {
3103 case BuiltinType::Int:
3104 case BuiltinType::UInt:
3105 return true;
3106 default:
3107 break;
3108 }
3109
3110 return false;
3111}
3112
Ulrich Weigand581badc2014-07-10 17:20:07 +00003113/// isAlignedParamType - Determine whether a type requires 16-byte
3114/// alignment in the parameter area.
3115bool
3116PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3117 // Complex types are passed just like their elements.
3118 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3119 Ty = CTy->getElementType();
3120
3121 // Only vector types of size 16 bytes need alignment (larger types are
3122 // passed via reference, smaller types are not aligned).
3123 if (Ty->isVectorType())
3124 return getContext().getTypeSize(Ty) == 128;
3125
3126 // For single-element float/vector structs, we consider the whole type
3127 // to have the same alignment requirements as its single element.
3128 const Type *AlignAsType = nullptr;
3129 const Type *EltType = isSingleElementStruct(Ty, getContext());
3130 if (EltType) {
3131 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3132 if ((EltType->isVectorType() &&
3133 getContext().getTypeSize(EltType) == 128) ||
3134 (BT && BT->isFloatingPoint()))
3135 AlignAsType = EltType;
3136 }
3137
Ulrich Weigandb7122372014-07-21 00:48:09 +00003138 // Likewise for ELFv2 homogeneous aggregates.
3139 const Type *Base = nullptr;
3140 uint64_t Members = 0;
3141 if (!AlignAsType && Kind == ELFv2 &&
3142 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3143 AlignAsType = Base;
3144
Ulrich Weigand581badc2014-07-10 17:20:07 +00003145 // With special case aggregates, only vector base types need alignment.
3146 if (AlignAsType)
3147 return AlignAsType->isVectorType();
3148
3149 // Otherwise, we only need alignment for any aggregate type that
3150 // has an alignment requirement of >= 16 bytes.
3151 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3152 return true;
3153
3154 return false;
3155}
3156
Ulrich Weigandb7122372014-07-21 00:48:09 +00003157/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3158/// aggregate. Base is set to the base element type, and Members is set
3159/// to the number of base elements.
3160bool
3161PPC64_SVR4_ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3162 uint64_t &Members) const {
3163 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3164 uint64_t NElements = AT->getSize().getZExtValue();
3165 if (NElements == 0)
3166 return false;
3167 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3168 return false;
3169 Members *= NElements;
3170 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3171 const RecordDecl *RD = RT->getDecl();
3172 if (RD->hasFlexibleArrayMember())
3173 return false;
3174
3175 Members = 0;
3176 for (const auto *FD : RD->fields()) {
3177 // Ignore (non-zero arrays of) empty records.
3178 QualType FT = FD->getType();
3179 while (const ConstantArrayType *AT =
3180 getContext().getAsConstantArrayType(FT)) {
3181 if (AT->getSize().getZExtValue() == 0)
3182 return false;
3183 FT = AT->getElementType();
3184 }
3185 if (isEmptyRecord(getContext(), FT, true))
3186 continue;
3187
3188 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3189 if (getContext().getLangOpts().CPlusPlus &&
3190 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3191 continue;
3192
3193 uint64_t FldMembers;
3194 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3195 return false;
3196
3197 Members = (RD->isUnion() ?
3198 std::max(Members, FldMembers) : Members + FldMembers);
3199 }
3200
3201 if (!Base)
3202 return false;
3203
3204 // Ensure there is no padding.
3205 if (getContext().getTypeSize(Base) * Members !=
3206 getContext().getTypeSize(Ty))
3207 return false;
3208 } else {
3209 Members = 1;
3210 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3211 Members = 2;
3212 Ty = CT->getElementType();
3213 }
3214
3215 // Homogeneous aggregates for ELFv2 must have base types of float,
3216 // double, long double, or 128-bit vectors.
3217 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3218 if (BT->getKind() != BuiltinType::Float &&
3219 BT->getKind() != BuiltinType::Double &&
3220 BT->getKind() != BuiltinType::LongDouble)
3221 return false;
3222 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3223 if (getContext().getTypeSize(VT) != 128)
3224 return false;
3225 } else {
3226 return false;
3227 }
3228
3229 // The base type must be the same for all members. Types that
3230 // agree in both total size and mode (float vs. vector) are
3231 // treated as being equivalent here.
3232 const Type *TyPtr = Ty.getTypePtr();
3233 if (!Base)
3234 Base = TyPtr;
3235
3236 if (Base->isVectorType() != TyPtr->isVectorType() ||
3237 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3238 return false;
3239 }
3240
3241 // Vector types require one register, floating point types require one
3242 // or two registers depending on their size.
3243 uint32_t NumRegs = Base->isVectorType() ? 1 :
3244 (getContext().getTypeSize(Base) + 63) / 64;
3245
3246 // Homogeneous Aggregates may occupy at most 8 registers.
3247 return (Members > 0 && Members * NumRegs <= 8);
3248}
3249
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003250ABIArgInfo
3251PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidt90b22c92012-11-27 02:46:43 +00003252 if (Ty->isAnyComplexType())
3253 return ABIArgInfo::getDirect();
3254
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003255 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3256 // or via reference (larger than 16 bytes).
3257 if (Ty->isVectorType()) {
3258 uint64_t Size = getContext().getTypeSize(Ty);
3259 if (Size > 128)
3260 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3261 else if (Size < 128) {
3262 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3263 return ABIArgInfo::getDirect(CoerceTy);
3264 }
3265 }
3266
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003267 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003268 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003269 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003270
Ulrich Weigand581badc2014-07-10 17:20:07 +00003271 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3272 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003273
3274 // ELFv2 homogeneous aggregates are passed as array types.
3275 const Type *Base = nullptr;
3276 uint64_t Members = 0;
3277 if (Kind == ELFv2 &&
3278 isHomogeneousAggregate(Ty, Base, Members)) {
3279 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3280 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3281 return ABIArgInfo::getDirect(CoerceTy);
3282 }
3283
Ulrich Weigand601957f2014-07-21 00:56:36 +00003284 // If an aggregate may end up fully in registers, we do not
3285 // use the ByVal method, but pass the aggregate as array.
3286 // This is usually beneficial since we avoid forcing the
3287 // back-end to store the argument to memory.
3288 uint64_t Bits = getContext().getTypeSize(Ty);
3289 if (Bits > 0 && Bits <= 8 * GPRBits) {
3290 llvm::Type *CoerceTy;
3291
3292 // Types up to 8 bytes are passed as integer type (which will be
3293 // properly aligned in the argument save area doubleword).
3294 if (Bits <= GPRBits)
3295 CoerceTy = llvm::IntegerType::get(getVMContext(),
3296 llvm::RoundUpToAlignment(Bits, 8));
3297 // Larger types are passed as arrays, with the base type selected
3298 // according to the required alignment in the save area.
3299 else {
3300 uint64_t RegBits = ABIAlign * 8;
3301 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3302 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3303 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3304 }
3305
3306 return ABIArgInfo::getDirect(CoerceTy);
3307 }
3308
Ulrich Weigandb7122372014-07-21 00:48:09 +00003309 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003310 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3311 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003312 }
3313
3314 return (isPromotableTypeForABI(Ty) ?
3315 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3316}
3317
3318ABIArgInfo
3319PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3320 if (RetTy->isVoidType())
3321 return ABIArgInfo::getIgnore();
3322
Bill Schmidta3d121c2012-12-17 04:20:17 +00003323 if (RetTy->isAnyComplexType())
3324 return ABIArgInfo::getDirect();
3325
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003326 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3327 // or via reference (larger than 16 bytes).
3328 if (RetTy->isVectorType()) {
3329 uint64_t Size = getContext().getTypeSize(RetTy);
3330 if (Size > 128)
3331 return ABIArgInfo::getIndirect(0);
3332 else if (Size < 128) {
3333 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3334 return ABIArgInfo::getDirect(CoerceTy);
3335 }
3336 }
3337
Ulrich Weigandb7122372014-07-21 00:48:09 +00003338 if (isAggregateTypeForABI(RetTy)) {
3339 // ELFv2 homogeneous aggregates are returned as array types.
3340 const Type *Base = nullptr;
3341 uint64_t Members = 0;
3342 if (Kind == ELFv2 &&
3343 isHomogeneousAggregate(RetTy, Base, Members)) {
3344 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3345 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3346 return ABIArgInfo::getDirect(CoerceTy);
3347 }
3348
3349 // ELFv2 small aggregates are returned in up to two registers.
3350 uint64_t Bits = getContext().getTypeSize(RetTy);
3351 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3352 if (Bits == 0)
3353 return ABIArgInfo::getIgnore();
3354
3355 llvm::Type *CoerceTy;
3356 if (Bits > GPRBits) {
3357 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
3358 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, NULL);
3359 } else
3360 CoerceTy = llvm::IntegerType::get(getVMContext(),
3361 llvm::RoundUpToAlignment(Bits, 8));
3362 return ABIArgInfo::getDirect(CoerceTy);
3363 }
3364
3365 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003366 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003367 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003368
3369 return (isPromotableTypeForABI(RetTy) ?
3370 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3371}
3372
Bill Schmidt25cb3492012-10-03 19:18:57 +00003373// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3374llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3375 QualType Ty,
3376 CodeGenFunction &CGF) const {
3377 llvm::Type *BP = CGF.Int8PtrTy;
3378 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3379
3380 CGBuilderTy &Builder = CGF.Builder;
3381 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3382 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3383
Ulrich Weigand581badc2014-07-10 17:20:07 +00003384 // Handle types that require 16-byte alignment in the parameter save area.
3385 if (isAlignedParamType(Ty)) {
3386 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3387 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3388 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3389 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3390 }
3391
Bill Schmidt924c4782013-01-14 17:45:36 +00003392 // Update the va_list pointer. The pointer should be bumped by the
3393 // size of the object. We can trust getTypeSize() except for a complex
3394 // type whose base type is smaller than a doubleword. For these, the
3395 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003396 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003397 QualType BaseTy;
3398 unsigned CplxBaseSize = 0;
3399
3400 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3401 BaseTy = CTy->getElementType();
3402 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3403 if (CplxBaseSize < 8)
3404 SizeInBytes = 16;
3405 }
3406
Bill Schmidt25cb3492012-10-03 19:18:57 +00003407 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3408 llvm::Value *NextAddr =
3409 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3410 "ap.next");
3411 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3412
Bill Schmidt924c4782013-01-14 17:45:36 +00003413 // If we have a complex type and the base type is smaller than 8 bytes,
3414 // the ABI calls for the real and imaginary parts to be right-adjusted
3415 // in separate doublewords. However, Clang expects us to produce a
3416 // pointer to a structure with the two parts packed tightly. So generate
3417 // loads of the real and imaginary parts relative to the va_list pointer,
3418 // and store them to a temporary structure.
3419 if (CplxBaseSize && CplxBaseSize < 8) {
3420 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3421 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003422 if (CGF.CGM.getDataLayout().isBigEndian()) {
3423 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3424 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3425 } else {
3426 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3427 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003428 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3429 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3430 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3431 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3432 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3433 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3434 "vacplx");
3435 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3436 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3437 Builder.CreateStore(Real, RealPtr, false);
3438 Builder.CreateStore(Imag, ImagPtr, false);
3439 return Ptr;
3440 }
3441
Bill Schmidt25cb3492012-10-03 19:18:57 +00003442 // If the argument is smaller than 8 bytes, it is right-adjusted in
3443 // its doubleword slot. Adjust the pointer to pick it up from the
3444 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003445 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003446 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3447 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3448 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3449 }
3450
3451 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3452 return Builder.CreateBitCast(Addr, PTy);
3453}
3454
3455static bool
3456PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3457 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003458 // This is calculated from the LLVM and GCC tables and verified
3459 // against gcc output. AFAIK all ABIs use the same encoding.
3460
3461 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3462
3463 llvm::IntegerType *i8 = CGF.Int8Ty;
3464 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3465 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3466 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3467
3468 // 0-31: r0-31, the 8-byte general-purpose registers
3469 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3470
3471 // 32-63: fp0-31, the 8-byte floating-point registers
3472 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3473
3474 // 64-76 are various 4-byte special-purpose registers:
3475 // 64: mq
3476 // 65: lr
3477 // 66: ctr
3478 // 67: ap
3479 // 68-75 cr0-7
3480 // 76: xer
3481 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3482
3483 // 77-108: v0-31, the 16-byte vector registers
3484 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3485
3486 // 109: vrsave
3487 // 110: vscr
3488 // 111: spe_acc
3489 // 112: spefscr
3490 // 113: sfp
3491 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3492
3493 return false;
3494}
John McCallea8d8bb2010-03-11 00:10:12 +00003495
Bill Schmidt25cb3492012-10-03 19:18:57 +00003496bool
3497PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3498 CodeGen::CodeGenFunction &CGF,
3499 llvm::Value *Address) const {
3500
3501 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3502}
3503
3504bool
3505PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3506 llvm::Value *Address) const {
3507
3508 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3509}
3510
Chris Lattner0cf24192010-06-28 20:05:43 +00003511//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003512// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003513//===----------------------------------------------------------------------===//
3514
3515namespace {
3516
Tim Northover573cbee2014-05-24 12:52:07 +00003517class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003518public:
3519 enum ABIKind {
3520 AAPCS = 0,
3521 DarwinPCS
3522 };
3523
3524private:
3525 ABIKind Kind;
3526
3527public:
Tim Northover573cbee2014-05-24 12:52:07 +00003528 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003529
3530private:
3531 ABIKind getABIKind() const { return Kind; }
3532 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3533
3534 ABIArgInfo classifyReturnType(QualType RetTy) const;
3535 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &AllocatedVFP,
3536 bool &IsHA, unsigned &AllocatedGPR,
Bob Wilson373af732014-04-21 01:23:39 +00003537 bool &IsSmallAggr, bool IsNamedArg) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00003538 bool isIllegalVectorType(QualType Ty) const;
3539
3540 virtual void computeInfo(CGFunctionInfo &FI) const {
3541 // To correctly handle Homogeneous Aggregate, we need to keep track of the
3542 // number of SIMD and Floating-point registers allocated so far.
3543 // If the argument is an HFA or an HVA and there are sufficient unallocated
3544 // SIMD and Floating-point registers, then the argument is allocated to SIMD
3545 // and Floating-point Registers (with one register per member of the HFA or
3546 // HVA). Otherwise, the NSRN is set to 8.
3547 unsigned AllocatedVFP = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003548
Tim Northovera2ee4332014-03-29 15:09:45 +00003549 // To correctly handle small aggregates, we need to keep track of the number
3550 // of GPRs allocated so far. If the small aggregate can't all fit into
3551 // registers, it will be on stack. We don't allow the aggregate to be
3552 // partially in registers.
3553 unsigned AllocatedGPR = 0;
Bob Wilson373af732014-04-21 01:23:39 +00003554
3555 // Find the number of named arguments. Variadic arguments get special
3556 // treatment with the Darwin ABI.
3557 unsigned NumRequiredArgs = (FI.isVariadic() ?
3558 FI.getRequiredArgs().getNumRequiredArgs() :
3559 FI.arg_size());
3560
Reid Kleckner40ca9132014-05-13 22:05:45 +00003561 if (!getCXXABI().classifyReturnType(FI))
3562 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northovera2ee4332014-03-29 15:09:45 +00003563 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3564 it != ie; ++it) {
3565 unsigned PreAllocation = AllocatedVFP, PreGPR = AllocatedGPR;
3566 bool IsHA = false, IsSmallAggr = false;
3567 const unsigned NumVFPs = 8;
3568 const unsigned NumGPRs = 8;
Bob Wilson373af732014-04-21 01:23:39 +00003569 bool IsNamedArg = ((it - FI.arg_begin()) <
3570 static_cast<signed>(NumRequiredArgs));
Tim Northovera2ee4332014-03-29 15:09:45 +00003571 it->info = classifyArgumentType(it->type, AllocatedVFP, IsHA,
Bob Wilson373af732014-04-21 01:23:39 +00003572 AllocatedGPR, IsSmallAggr, IsNamedArg);
Tim Northover5ffc0922014-04-17 10:20:38 +00003573
3574 // Under AAPCS the 64-bit stack slot alignment means we can't pass HAs
3575 // as sequences of floats since they'll get "holes" inserted as
3576 // padding by the back end.
Tim Northover07f16242014-04-18 10:47:44 +00003577 if (IsHA && AllocatedVFP > NumVFPs && !isDarwinPCS() &&
3578 getContext().getTypeAlign(it->type) < 64) {
3579 uint32_t NumStackSlots = getContext().getTypeSize(it->type);
3580 NumStackSlots = llvm::RoundUpToAlignment(NumStackSlots, 64) / 64;
Tim Northover5ffc0922014-04-17 10:20:38 +00003581
Tim Northover07f16242014-04-18 10:47:44 +00003582 llvm::Type *CoerceTy = llvm::ArrayType::get(
3583 llvm::Type::getDoubleTy(getVMContext()), NumStackSlots);
3584 it->info = ABIArgInfo::getDirect(CoerceTy);
Tim Northover5ffc0922014-04-17 10:20:38 +00003585 }
3586
Tim Northovera2ee4332014-03-29 15:09:45 +00003587 // If we do not have enough VFP registers for the HA, any VFP registers
3588 // that are unallocated are marked as unavailable. To achieve this, we add
3589 // padding of (NumVFPs - PreAllocation) floats.
3590 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3591 llvm::Type *PaddingTy = llvm::ArrayType::get(
3592 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
Tim Northover5ffc0922014-04-17 10:20:38 +00003593 it->info.setPaddingType(PaddingTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00003594 }
Tim Northover5ffc0922014-04-17 10:20:38 +00003595
Tim Northovera2ee4332014-03-29 15:09:45 +00003596 // If we do not have enough GPRs for the small aggregate, any GPR regs
3597 // that are unallocated are marked as unavailable.
3598 if (IsSmallAggr && AllocatedGPR > NumGPRs && PreGPR < NumGPRs) {
3599 llvm::Type *PaddingTy = llvm::ArrayType::get(
3600 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreGPR);
3601 it->info =
3602 ABIArgInfo::getDirect(it->info.getCoerceToType(), 0, PaddingTy);
3603 }
3604 }
3605 }
3606
3607 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3608 CodeGenFunction &CGF) const;
3609
3610 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3611 CodeGenFunction &CGF) const;
3612
3613 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3614 CodeGenFunction &CGF) const {
3615 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3616 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3617 }
3618};
3619
Tim Northover573cbee2014-05-24 12:52:07 +00003620class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003621public:
Tim Northover573cbee2014-05-24 12:52:07 +00003622 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3623 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003624
3625 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3626 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3627 }
3628
3629 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3630
3631 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3632};
3633}
3634
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003635static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
Tim Northovera2ee4332014-03-29 15:09:45 +00003636 ASTContext &Context,
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003637 bool isAArch64,
Craig Topper8a13c412014-05-21 05:09:00 +00003638 uint64_t *HAMembers = nullptr);
Tim Northovera2ee4332014-03-29 15:09:45 +00003639
Tim Northover573cbee2014-05-24 12:52:07 +00003640ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty,
3641 unsigned &AllocatedVFP,
3642 bool &IsHA,
3643 unsigned &AllocatedGPR,
3644 bool &IsSmallAggr,
3645 bool IsNamedArg) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003646 // Handle illegal vector types here.
3647 if (isIllegalVectorType(Ty)) {
3648 uint64_t Size = getContext().getTypeSize(Ty);
3649 if (Size <= 32) {
3650 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
3651 AllocatedGPR++;
3652 return ABIArgInfo::getDirect(ResType);
3653 }
3654 if (Size == 64) {
3655 llvm::Type *ResType =
3656 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
3657 AllocatedVFP++;
3658 return ABIArgInfo::getDirect(ResType);
3659 }
3660 if (Size == 128) {
3661 llvm::Type *ResType =
3662 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
3663 AllocatedVFP++;
3664 return ABIArgInfo::getDirect(ResType);
3665 }
3666 AllocatedGPR++;
3667 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3668 }
3669 if (Ty->isVectorType())
3670 // Size of a legal vector should be either 64 or 128.
3671 AllocatedVFP++;
3672 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3673 if (BT->getKind() == BuiltinType::Half ||
3674 BT->getKind() == BuiltinType::Float ||
3675 BT->getKind() == BuiltinType::Double ||
3676 BT->getKind() == BuiltinType::LongDouble)
3677 AllocatedVFP++;
3678 }
3679
3680 if (!isAggregateTypeForABI(Ty)) {
3681 // Treat an enum type as its underlying type.
3682 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3683 Ty = EnumTy->getDecl()->getIntegerType();
3684
3685 if (!Ty->isFloatingType() && !Ty->isVectorType()) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003686 unsigned Alignment = getContext().getTypeAlign(Ty);
3687 if (!isDarwinPCS() && Alignment > 64)
3688 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3689
Tim Northovera2ee4332014-03-29 15:09:45 +00003690 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3691 AllocatedGPR += RegsNeeded;
3692 }
3693 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3694 ? ABIArgInfo::getExtend()
3695 : ABIArgInfo::getDirect());
3696 }
3697
3698 // Structures with either a non-trivial destructor or a non-trivial
3699 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003700 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003701 AllocatedGPR++;
Reid Kleckner40ca9132014-05-13 22:05:45 +00003702 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
3703 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003704 }
3705
3706 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3707 // elsewhere for GNU compatibility.
3708 if (isEmptyRecord(getContext(), Ty, true)) {
3709 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3710 return ABIArgInfo::getIgnore();
3711
3712 ++AllocatedGPR;
3713 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3714 }
3715
3716 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003717 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003718 uint64_t Members = 0;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003719 if (isARMHomogeneousAggregate(Ty, Base, getContext(), true, &Members)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003720 IsHA = true;
Bob Wilson373af732014-04-21 01:23:39 +00003721 if (!IsNamedArg && isDarwinPCS()) {
3722 // With the Darwin ABI, variadic arguments are always passed on the stack
3723 // and should not be expanded. Treat variadic HFAs as arrays of doubles.
3724 uint64_t Size = getContext().getTypeSize(Ty);
3725 llvm::Type *BaseTy = llvm::Type::getDoubleTy(getVMContext());
3726 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3727 }
3728 AllocatedVFP += Members;
Tim Northovera2ee4332014-03-29 15:09:45 +00003729 return ABIArgInfo::getExpand();
3730 }
3731
3732 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3733 uint64_t Size = getContext().getTypeSize(Ty);
3734 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003735 unsigned Alignment = getContext().getTypeAlign(Ty);
3736 if (!isDarwinPCS() && Alignment > 64)
3737 AllocatedGPR = llvm::RoundUpToAlignment(AllocatedGPR, Alignment / 64);
3738
Tim Northovera2ee4332014-03-29 15:09:45 +00003739 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3740 AllocatedGPR += Size / 64;
3741 IsSmallAggr = true;
3742 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3743 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003744 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003745 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3746 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3747 }
3748 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3749 }
3750
3751 AllocatedGPR++;
3752 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3753}
3754
Tim Northover573cbee2014-05-24 12:52:07 +00003755ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003756 if (RetTy->isVoidType())
3757 return ABIArgInfo::getIgnore();
3758
3759 // Large vector types should be returned via memory.
3760 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3761 return ABIArgInfo::getIndirect(0);
3762
3763 if (!isAggregateTypeForABI(RetTy)) {
3764 // Treat an enum type as its underlying type.
3765 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3766 RetTy = EnumTy->getDecl()->getIntegerType();
3767
Tim Northover4dab6982014-04-18 13:46:08 +00003768 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3769 ? ABIArgInfo::getExtend()
3770 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003771 }
3772
Tim Northovera2ee4332014-03-29 15:09:45 +00003773 if (isEmptyRecord(getContext(), RetTy, true))
3774 return ABIArgInfo::getIgnore();
3775
Craig Topper8a13c412014-05-21 05:09:00 +00003776 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003777 if (isARMHomogeneousAggregate(RetTy, Base, getContext(), true))
Tim Northovera2ee4332014-03-29 15:09:45 +00003778 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3779 return ABIArgInfo::getDirect();
3780
3781 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3782 uint64_t Size = getContext().getTypeSize(RetTy);
3783 if (Size <= 128) {
3784 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3785 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3786 }
3787
3788 return ABIArgInfo::getIndirect(0);
3789}
3790
Tim Northover573cbee2014-05-24 12:52:07 +00003791/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3792bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003793 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3794 // Check whether VT is legal.
3795 unsigned NumElements = VT->getNumElements();
3796 uint64_t Size = getContext().getTypeSize(VT);
3797 // NumElements should be power of 2 between 1 and 16.
3798 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3799 return true;
3800 return Size != 64 && (Size != 128 || NumElements == 1);
3801 }
3802 return false;
3803}
3804
3805static llvm::Value *EmitAArch64VAArg(llvm::Value *VAListAddr, QualType Ty,
3806 int AllocatedGPR, int AllocatedVFP,
3807 bool IsIndirect, CodeGenFunction &CGF) {
3808 // The AArch64 va_list type and handling is specified in the Procedure Call
3809 // Standard, section B.4:
3810 //
3811 // struct {
3812 // void *__stack;
3813 // void *__gr_top;
3814 // void *__vr_top;
3815 // int __gr_offs;
3816 // int __vr_offs;
3817 // };
3818
3819 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3820 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3821 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3822 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3823 auto &Ctx = CGF.getContext();
3824
Craig Topper8a13c412014-05-21 05:09:00 +00003825 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003826 int reg_top_index;
3827 int RegSize;
3828 if (AllocatedGPR) {
3829 assert(!AllocatedVFP && "Arguments never split between int & VFP regs");
3830 // 3 is the field number of __gr_offs
3831 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3832 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3833 reg_top_index = 1; // field number for __gr_top
3834 RegSize = 8 * AllocatedGPR;
3835 } else {
3836 assert(!AllocatedGPR && "Argument must go in VFP or int regs");
3837 // 4 is the field number of __vr_offs.
3838 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
3839 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
3840 reg_top_index = 2; // field number for __vr_top
3841 RegSize = 16 * AllocatedVFP;
3842 }
3843
3844 //=======================================
3845 // Find out where argument was passed
3846 //=======================================
3847
3848 // If reg_offs >= 0 we're already using the stack for this type of
3849 // argument. We don't want to keep updating reg_offs (in case it overflows,
3850 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
3851 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00003852 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003853 UsingStack = CGF.Builder.CreateICmpSGE(
3854 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
3855
3856 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
3857
3858 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00003859 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00003860 CGF.EmitBlock(MaybeRegBlock);
3861
3862 // Integer arguments may need to correct register alignment (for example a
3863 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
3864 // align __gr_offs to calculate the potential address.
3865 if (AllocatedGPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3866 int Align = Ctx.getTypeAlign(Ty) / 8;
3867
3868 reg_offs = CGF.Builder.CreateAdd(
3869 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
3870 "align_regoffs");
3871 reg_offs = CGF.Builder.CreateAnd(
3872 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
3873 "aligned_regoffs");
3874 }
3875
3876 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00003877 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003878 NewOffset = CGF.Builder.CreateAdd(
3879 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
3880 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
3881
3882 // Now we're in a position to decide whether this argument really was in
3883 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00003884 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003885 InRegs = CGF.Builder.CreateICmpSLE(
3886 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
3887
3888 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
3889
3890 //=======================================
3891 // Argument was in registers
3892 //=======================================
3893
3894 // Now we emit the code for if the argument was originally passed in
3895 // registers. First start the appropriate block:
3896 CGF.EmitBlock(InRegBlock);
3897
Craig Topper8a13c412014-05-21 05:09:00 +00003898 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003899 reg_top_p =
3900 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
3901 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
3902 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00003903 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003904 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
3905
3906 if (IsIndirect) {
3907 // If it's been passed indirectly (actually a struct), whatever we find from
3908 // stored registers or on the stack will actually be a struct **.
3909 MemTy = llvm::PointerType::getUnqual(MemTy);
3910 }
3911
Craig Topper8a13c412014-05-21 05:09:00 +00003912 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003913 uint64_t NumMembers;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00003914 bool IsHFA = isARMHomogeneousAggregate(Ty, Base, Ctx, true, &NumMembers);
James Molloy467be602014-05-07 14:45:55 +00003915 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003916 // Homogeneous aggregates passed in registers will have their elements split
3917 // and stored 16-bytes apart regardless of size (they're notionally in qN,
3918 // qN+1, ...). We reload and store into a temporary local variable
3919 // contiguously.
3920 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
3921 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
3922 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
3923 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
3924 int Offset = 0;
3925
3926 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
3927 Offset = 16 - Ctx.getTypeSize(Base) / 8;
3928 for (unsigned i = 0; i < NumMembers; ++i) {
3929 llvm::Value *BaseOffset =
3930 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
3931 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
3932 LoadAddr = CGF.Builder.CreateBitCast(
3933 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
3934 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
3935
3936 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
3937 CGF.Builder.CreateStore(Elem, StoreAddr);
3938 }
3939
3940 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
3941 } else {
3942 // Otherwise the object is contiguous in memory
3943 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00003944 if (CGF.CGM.getDataLayout().isBigEndian() &&
3945 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00003946 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
3947 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
3948 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
3949
3950 BaseAddr = CGF.Builder.CreateAdd(
3951 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
3952
3953 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
3954 }
3955
3956 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
3957 }
3958
3959 CGF.EmitBranch(ContBlock);
3960
3961 //=======================================
3962 // Argument was on the stack
3963 //=======================================
3964 CGF.EmitBlock(OnStackBlock);
3965
Craig Topper8a13c412014-05-21 05:09:00 +00003966 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003967 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
3968 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
3969
3970 // Again, stack arguments may need realigmnent. In this case both integer and
3971 // floating-point ones might be affected.
3972 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
3973 int Align = Ctx.getTypeAlign(Ty) / 8;
3974
3975 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
3976
3977 OnStackAddr = CGF.Builder.CreateAdd(
3978 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
3979 "align_stack");
3980 OnStackAddr = CGF.Builder.CreateAnd(
3981 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
3982 "align_stack");
3983
3984 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
3985 }
3986
3987 uint64_t StackSize;
3988 if (IsIndirect)
3989 StackSize = 8;
3990 else
3991 StackSize = Ctx.getTypeSize(Ty) / 8;
3992
3993 // All stack slots are 8 bytes
3994 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
3995
3996 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
3997 llvm::Value *NewStack =
3998 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
3999
4000 // Write the new value of __stack for the next call to va_arg
4001 CGF.Builder.CreateStore(NewStack, stack_p);
4002
4003 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4004 Ctx.getTypeSize(Ty) < 64) {
4005 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4006 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4007
4008 OnStackAddr = CGF.Builder.CreateAdd(
4009 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4010
4011 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4012 }
4013
4014 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4015
4016 CGF.EmitBranch(ContBlock);
4017
4018 //=======================================
4019 // Tidy up
4020 //=======================================
4021 CGF.EmitBlock(ContBlock);
4022
4023 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4024 ResAddr->addIncoming(RegAddr, InRegBlock);
4025 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4026
4027 if (IsIndirect)
4028 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4029
4030 return ResAddr;
4031}
4032
Tim Northover573cbee2014-05-24 12:52:07 +00004033llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004034 CodeGenFunction &CGF) const {
4035
4036 unsigned AllocatedGPR = 0, AllocatedVFP = 0;
4037 bool IsHA = false, IsSmallAggr = false;
Bob Wilson373af732014-04-21 01:23:39 +00004038 ABIArgInfo AI = classifyArgumentType(Ty, AllocatedVFP, IsHA, AllocatedGPR,
4039 IsSmallAggr, false /*IsNamedArg*/);
Tim Northovera2ee4332014-03-29 15:09:45 +00004040
4041 return EmitAArch64VAArg(VAListAddr, Ty, AllocatedGPR, AllocatedVFP,
4042 AI.isIndirect(), CGF);
4043}
4044
Tim Northover573cbee2014-05-24 12:52:07 +00004045llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004046 CodeGenFunction &CGF) const {
4047 // We do not support va_arg for aggregates or illegal vector types.
4048 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4049 // other cases.
4050 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004051 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004052
4053 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4054 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4055
Craig Topper8a13c412014-05-21 05:09:00 +00004056 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004057 bool isHA = isARMHomogeneousAggregate(Ty, Base, getContext(), true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004058
4059 bool isIndirect = false;
4060 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4061 // be passed indirectly.
4062 if (Size > 16 && !isHA) {
4063 isIndirect = true;
4064 Size = 8;
4065 Align = 8;
4066 }
4067
4068 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4069 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4070
4071 CGBuilderTy &Builder = CGF.Builder;
4072 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4073 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4074
4075 if (isEmptyRecord(getContext(), Ty, true)) {
4076 // These are ignored for parameter passing purposes.
4077 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4078 return Builder.CreateBitCast(Addr, PTy);
4079 }
4080
4081 const uint64_t MinABIAlign = 8;
4082 if (Align > MinABIAlign) {
4083 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4084 Addr = Builder.CreateGEP(Addr, Offset);
4085 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4086 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4087 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4088 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4089 }
4090
4091 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4092 llvm::Value *NextAddr = Builder.CreateGEP(
4093 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4094 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4095
4096 if (isIndirect)
4097 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4098 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4099 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4100
4101 return AddrTyped;
4102}
4103
4104//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004105// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004106//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004107
4108namespace {
4109
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004110class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004111public:
4112 enum ABIKind {
4113 APCS = 0,
4114 AAPCS = 1,
4115 AAPCS_VFP
4116 };
4117
4118private:
4119 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004120 mutable int VFPRegs[16];
4121 const unsigned NumVFPs;
4122 const unsigned NumGPRs;
4123 mutable unsigned AllocatedGPRs;
4124 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004125
4126public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004127 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4128 NumVFPs(16), NumGPRs(4) {
John McCall882987f2013-02-28 19:01:20 +00004129 setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004130 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004131 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004132
John McCall3480ef22011-08-30 01:42:09 +00004133 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004134 switch (getTarget().getTriple().getEnvironment()) {
4135 case llvm::Triple::Android:
4136 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004137 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004138 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004139 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004140 return true;
4141 default:
4142 return false;
4143 }
John McCall3480ef22011-08-30 01:42:09 +00004144 }
4145
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004146 bool isEABIHF() const {
4147 switch (getTarget().getTriple().getEnvironment()) {
4148 case llvm::Triple::EABIHF:
4149 case llvm::Triple::GNUEABIHF:
4150 return true;
4151 default:
4152 return false;
4153 }
4154 }
4155
Daniel Dunbar020daa92009-09-12 01:00:39 +00004156 ABIKind getABIKind() const { return Kind; }
4157
Tim Northovera484bc02013-10-01 14:34:25 +00004158private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004159 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004160 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004161 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004162 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004163
Craig Topper4f12f102014-03-12 06:41:41 +00004164 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004165
Craig Topper4f12f102014-03-12 06:41:41 +00004166 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4167 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004168
4169 llvm::CallingConv::ID getLLVMDefaultCC() const;
4170 llvm::CallingConv::ID getABIDefaultCC() const;
4171 void setRuntimeCC();
Oliver Stannard405bded2014-02-11 09:25:50 +00004172
4173 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4174 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4175 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004176};
4177
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004178class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4179public:
Chris Lattner2b037972010-07-29 02:01:43 +00004180 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4181 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004182
John McCall3480ef22011-08-30 01:42:09 +00004183 const ARMABIInfo &getABIInfo() const {
4184 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4185 }
4186
Craig Topper4f12f102014-03-12 06:41:41 +00004187 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004188 return 13;
4189 }
Roman Divackyc1617352011-05-18 19:36:54 +00004190
Craig Topper4f12f102014-03-12 06:41:41 +00004191 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004192 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4193 }
4194
Roman Divackyc1617352011-05-18 19:36:54 +00004195 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004196 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004197 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004198
4199 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004200 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004201 return false;
4202 }
John McCall3480ef22011-08-30 01:42:09 +00004203
Craig Topper4f12f102014-03-12 06:41:41 +00004204 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004205 if (getABIInfo().isEABI()) return 88;
4206 return TargetCodeGenInfo::getSizeOfUnwindException();
4207 }
Tim Northovera484bc02013-10-01 14:34:25 +00004208
4209 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004210 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004211 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4212 if (!FD)
4213 return;
4214
4215 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4216 if (!Attr)
4217 return;
4218
4219 const char *Kind;
4220 switch (Attr->getInterrupt()) {
4221 case ARMInterruptAttr::Generic: Kind = ""; break;
4222 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4223 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4224 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4225 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4226 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4227 }
4228
4229 llvm::Function *Fn = cast<llvm::Function>(GV);
4230
4231 Fn->addFnAttr("interrupt", Kind);
4232
4233 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4234 return;
4235
4236 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4237 // however this is not necessarily true on taking any interrupt. Instruct
4238 // the backend to perform a realignment as part of the function prologue.
4239 llvm::AttrBuilder B;
4240 B.addStackAlignmentAttr(8);
4241 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4242 llvm::AttributeSet::get(CGM.getLLVMContext(),
4243 llvm::AttributeSet::FunctionIndex,
4244 B));
4245 }
4246
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004247};
4248
Daniel Dunbard59655c2009-09-12 00:59:49 +00004249}
4250
Chris Lattner22326a12010-07-29 02:31:05 +00004251void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004252 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004253 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004254 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4255 // VFP registers of the appropriate type unallocated then the argument is
4256 // allocated to the lowest-numbered sequence of such registers.
4257 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4258 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004259 resetAllocatedRegs();
4260
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004261 const bool isAAPCS_VFP =
4262 getABIKind() == ARMABIInfo::AAPCS_VFP && !FI.isVariadic();
4263
Reid Kleckner40ca9132014-05-13 22:05:45 +00004264 if (getCXXABI().classifyReturnType(FI)) {
4265 if (FI.getReturnInfo().isIndirect())
4266 markAllocatedGPRs(1, 1);
4267 } else {
4268 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4269 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004270 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004271 unsigned PreAllocationVFPs = AllocatedVFPs;
4272 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004273 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004274 // 6.1.2.3 There is one VFP co-processor register class using registers
4275 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004276 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004277
4278 // If we have allocated some arguments onto the stack (due to running
4279 // out of VFP registers), we cannot split an argument between GPRs and
4280 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004281 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004282 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4283 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004284 // We do not have to do this if the argument is being passed ByVal, as the
4285 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004286 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004287 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4288 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4289 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004290 llvm::Type *PaddingTy = llvm::ArrayType::get(
4291 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004292 if (I.info.canHaveCoerceToType()) {
4293 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004294 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004295 } else {
4296 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004297 PaddingTy, !isAAPCS_VFP);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004298 }
Manman Ren2a523d82012-10-30 23:21:41 +00004299 }
4300 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004301
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004302 // Always honor user-specified calling convention.
4303 if (FI.getCallingConvention() != llvm::CallingConv::C)
4304 return;
4305
John McCall882987f2013-02-28 19:01:20 +00004306 llvm::CallingConv::ID cc = getRuntimeCC();
4307 if (cc != llvm::CallingConv::C)
4308 FI.setEffectiveCallingConvention(cc);
4309}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004310
John McCall882987f2013-02-28 19:01:20 +00004311/// Return the default calling convention that LLVM will use.
4312llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4313 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004314 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004315 return llvm::CallingConv::ARM_AAPCS_VFP;
4316 else if (isEABI())
4317 return llvm::CallingConv::ARM_AAPCS;
4318 else
4319 return llvm::CallingConv::ARM_APCS;
4320}
4321
4322/// Return the calling convention that our ABI would like us to use
4323/// as the C calling convention.
4324llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004325 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004326 case APCS: return llvm::CallingConv::ARM_APCS;
4327 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4328 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004329 }
John McCall882987f2013-02-28 19:01:20 +00004330 llvm_unreachable("bad ABI kind");
4331}
4332
4333void ARMABIInfo::setRuntimeCC() {
4334 assert(getRuntimeCC() == llvm::CallingConv::C);
4335
4336 // Don't muddy up the IR with a ton of explicit annotations if
4337 // they'd just match what LLVM will infer from the triple.
4338 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4339 if (abiCC != getLLVMDefaultCC())
4340 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004341}
4342
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004343/// isARMHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
Bob Wilsone826a2a2011-08-03 05:58:22 +00004344/// aggregate. If HAMembers is non-null, the number of base elements
4345/// contained in the type is returned through it; this is used for the
4346/// recursive calls that check aggregate component types.
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004347static bool isARMHomogeneousAggregate(QualType Ty, const Type *&Base,
4348 ASTContext &Context, bool isAArch64,
4349 uint64_t *HAMembers) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004350 uint64_t Members = 0;
Bob Wilsone826a2a2011-08-03 05:58:22 +00004351 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004352 if (!isARMHomogeneousAggregate(AT->getElementType(), Base, Context, isAArch64, &Members))
Bob Wilsone826a2a2011-08-03 05:58:22 +00004353 return false;
4354 Members *= AT->getSize().getZExtValue();
4355 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4356 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004357 if (RD->hasFlexibleArrayMember())
Bob Wilsone826a2a2011-08-03 05:58:22 +00004358 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004359
Bob Wilsone826a2a2011-08-03 05:58:22 +00004360 Members = 0;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004361 for (const auto *FD : RD->fields()) {
Bob Wilsone826a2a2011-08-03 05:58:22 +00004362 uint64_t FldMembers;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004363 if (!isARMHomogeneousAggregate(FD->getType(), Base, Context, isAArch64, &FldMembers))
Bob Wilsone826a2a2011-08-03 05:58:22 +00004364 return false;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004365
4366 Members = (RD->isUnion() ?
4367 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004368 }
4369 } else {
4370 Members = 1;
4371 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4372 Members = 2;
4373 Ty = CT->getElementType();
4374 }
4375
4376 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004377 // double, or 64-bit or 128-bit vectors. "long double" has the same machine
4378 // type as double, so it is also allowed as a base type.
4379 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4380 // point type or a short-vector type. This is the same as the 32-bit ABI,
4381 // but with the difference that any floating-point type is allowed,
4382 // including __fp16.
Bob Wilsone826a2a2011-08-03 05:58:22 +00004383 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004384 if (isAArch64) {
4385 if (!BT->isFloatingPoint())
4386 return false;
4387 } else {
4388 if (BT->getKind() != BuiltinType::Float &&
4389 BT->getKind() != BuiltinType::Double &&
4390 BT->getKind() != BuiltinType::LongDouble)
4391 return false;
4392 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004393 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4394 unsigned VecSize = Context.getTypeSize(VT);
4395 if (VecSize != 64 && VecSize != 128)
4396 return false;
4397 } else {
4398 return false;
4399 }
4400
4401 // The base type must be the same for all members. Vector types of the
4402 // same total size are treated as being equivalent here.
4403 const Type *TyPtr = Ty.getTypePtr();
4404 if (!Base)
4405 Base = TyPtr;
Oliver Stannard5e8558f2014-02-07 11:25:57 +00004406
4407 if (Base != TyPtr) {
4408 // Homogeneous aggregates are defined as containing members with the
4409 // same machine type. There are two cases in which two members have
4410 // different TypePtrs but the same machine type:
4411
4412 // 1) Vectors of the same length, regardless of the type and number
4413 // of their members.
4414 const bool SameLengthVectors = Base->isVectorType() && TyPtr->isVectorType()
4415 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4416
4417 // 2) In the 32-bit AAPCS, `double' and `long double' have the same
4418 // machine type. This is not the case for the 64-bit AAPCS.
4419 const bool SameSizeDoubles =
4420 ( ( Base->isSpecificBuiltinType(BuiltinType::Double)
4421 && TyPtr->isSpecificBuiltinType(BuiltinType::LongDouble))
4422 || ( Base->isSpecificBuiltinType(BuiltinType::LongDouble)
4423 && TyPtr->isSpecificBuiltinType(BuiltinType::Double)))
4424 && (Context.getTypeSize(Base) == Context.getTypeSize(TyPtr));
4425
4426 if (!SameLengthVectors && !SameSizeDoubles)
4427 return false;
4428 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004429 }
4430
4431 // Homogeneous Aggregates can have at most 4 members of the base type.
4432 if (HAMembers)
4433 *HAMembers = Members;
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004434
4435 return (Members > 0 && Members <= 4);
Bob Wilsone826a2a2011-08-03 05:58:22 +00004436}
4437
Manman Renb505d332012-10-31 19:02:26 +00004438/// markAllocatedVFPs - update VFPRegs according to the alignment and
4439/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004440void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4441 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004442 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004443 if (AllocatedVFPs >= 16) {
4444 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4445 // the stack.
4446 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004447 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004448 }
Manman Renb505d332012-10-31 19:02:26 +00004449 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4450 // VFP registers of the appropriate type unallocated then the argument is
4451 // allocated to the lowest-numbered sequence of such registers.
4452 for (unsigned I = 0; I < 16; I += Alignment) {
4453 bool FoundSlot = true;
4454 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4455 if (J >= 16 || VFPRegs[J]) {
4456 FoundSlot = false;
4457 break;
4458 }
4459 if (FoundSlot) {
4460 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4461 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004462 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004463 return;
4464 }
4465 }
4466 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4467 // unallocated are marked as unavailable.
4468 for (unsigned I = 0; I < 16; I++)
4469 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004470 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004471}
4472
Oliver Stannard405bded2014-02-11 09:25:50 +00004473/// Update AllocatedGPRs to record the number of general purpose registers
4474/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4475/// this represents arguments being stored on the stack.
4476void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004477 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004478 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4479
4480 if (Alignment == 2 && AllocatedGPRs & 0x1)
4481 AllocatedGPRs += 1;
4482
4483 AllocatedGPRs += NumRequired;
4484}
4485
4486void ARMABIInfo::resetAllocatedRegs(void) const {
4487 AllocatedGPRs = 0;
4488 AllocatedVFPs = 0;
4489 for (unsigned i = 0; i < NumVFPs; ++i)
4490 VFPRegs[i] = 0;
4491}
4492
James Molloy6f244b62014-05-09 16:21:39 +00004493ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004494 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004495 // We update number of allocated VFPs according to
4496 // 6.1.2.1 The following argument types are VFP CPRCs:
4497 // A single-precision floating-point type (including promoted
4498 // half-precision types); A double-precision floating-point type;
4499 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4500 // with a Base Type of a single- or double-precision floating-point type,
4501 // 64-bit containerized vectors or 128-bit containerized vectors with one
4502 // to four Elements.
4503
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004504 const bool isAAPCS_VFP =
4505 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4506
Manman Renfef9e312012-10-16 19:18:39 +00004507 // Handle illegal vector types here.
4508 if (isIllegalVectorType(Ty)) {
4509 uint64_t Size = getContext().getTypeSize(Ty);
4510 if (Size <= 32) {
4511 llvm::Type *ResType =
4512 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004513 markAllocatedGPRs(1, 1);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004514 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004515 }
4516 if (Size == 64) {
4517 llvm::Type *ResType = llvm::VectorType::get(
4518 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004519 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4520 markAllocatedGPRs(2, 2);
4521 } else {
4522 markAllocatedVFPs(2, 2);
4523 IsCPRC = true;
4524 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004525 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004526 }
4527 if (Size == 128) {
4528 llvm::Type *ResType = llvm::VectorType::get(
4529 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004530 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4531 markAllocatedGPRs(2, 4);
4532 } else {
4533 markAllocatedVFPs(4, 4);
4534 IsCPRC = true;
4535 }
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004536 return ABIArgInfo::getDirect(ResType, 0, nullptr, !isAAPCS_VFP);
Manman Renfef9e312012-10-16 19:18:39 +00004537 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004538 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004539 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4540 }
Manman Renb505d332012-10-31 19:02:26 +00004541 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004542 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4543 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4544 uint64_t Size = getContext().getTypeSize(VT);
4545 // Size of a legal vector should be power of 2 and above 64.
4546 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4547 IsCPRC = true;
4548 }
Manman Ren2a523d82012-10-30 23:21:41 +00004549 }
Manman Renb505d332012-10-31 19:02:26 +00004550 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004551 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4552 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4553 if (BT->getKind() == BuiltinType::Half ||
4554 BT->getKind() == BuiltinType::Float) {
4555 markAllocatedVFPs(1, 1);
4556 IsCPRC = true;
4557 }
4558 if (BT->getKind() == BuiltinType::Double ||
4559 BT->getKind() == BuiltinType::LongDouble) {
4560 markAllocatedVFPs(2, 2);
4561 IsCPRC = true;
4562 }
4563 }
Manman Ren2a523d82012-10-30 23:21:41 +00004564 }
Manman Renfef9e312012-10-16 19:18:39 +00004565
John McCalla1dee5302010-08-22 10:59:02 +00004566 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004567 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004568 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004569 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004570 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004571
Oliver Stannard405bded2014-02-11 09:25:50 +00004572 unsigned Size = getContext().getTypeSize(Ty);
4573 if (!IsCPRC)
4574 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004575 return (Ty->isPromotableIntegerType()
4576 ? ABIArgInfo::getExtend()
4577 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004578 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004579
Oliver Stannard405bded2014-02-11 09:25:50 +00004580 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4581 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004582 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004583 }
Tim Northover1060eae2013-06-21 22:49:34 +00004584
Daniel Dunbar09d33622009-09-14 21:54:03 +00004585 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004586 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004587 return ABIArgInfo::getIgnore();
4588
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004589 if (isAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004590 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4591 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004592 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004593 uint64_t Members = 0;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004594 if (isARMHomogeneousAggregate(Ty, Base, getContext(), false, &Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004595 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004596 // Base can be a floating-point or a vector.
4597 if (Base->isVectorType()) {
4598 // ElementSize is in number of floats.
4599 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004600 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004601 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004602 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004603 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004604 else {
4605 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4606 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004607 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004608 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004609 IsCPRC = true;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004610 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004611 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004612 }
4613
Manman Ren6c30e132012-08-13 21:23:55 +00004614 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004615 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4616 // most 8-byte. We realign the indirect argument if type alignment is bigger
4617 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004618 uint64_t ABIAlign = 4;
4619 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4620 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4621 getABIKind() == ARMABIInfo::AAPCS)
4622 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004623 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004624 // Update Allocated GPRs. Since this is only used when the size of the
4625 // argument is greater than 64 bytes, this will always use up any available
4626 // registers (of which there are 4). We also don't care about getting the
4627 // alignment right, because general-purpose registers cannot be back-filled.
4628 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004629 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004630 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004631 }
4632
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004633 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004634 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004635 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004636 // FIXME: Try to match the types of the arguments more accurately where
4637 // we can.
4638 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004639 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4640 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004641 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004642 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004643 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4644 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004645 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004646 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004647
Chris Lattnera5f58b02011-07-09 17:41:47 +00004648 llvm::Type *STy =
Chris Lattner845511f2011-06-18 22:49:11 +00004649 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004650 return ABIArgInfo::getDirect(STy, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004651}
4652
Chris Lattner458b2aa2010-07-29 02:16:43 +00004653static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004654 llvm::LLVMContext &VMContext) {
4655 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4656 // is called integer-like if its size is less than or equal to one word, and
4657 // the offset of each of its addressable sub-fields is zero.
4658
4659 uint64_t Size = Context.getTypeSize(Ty);
4660
4661 // Check that the type fits in a word.
4662 if (Size > 32)
4663 return false;
4664
4665 // FIXME: Handle vector types!
4666 if (Ty->isVectorType())
4667 return false;
4668
Daniel Dunbard53bac72009-09-14 02:20:34 +00004669 // Float types are never treated as "integer like".
4670 if (Ty->isRealFloatingType())
4671 return false;
4672
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004673 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004674 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004675 return true;
4676
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004677 // Small complex integer types are "integer like".
4678 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4679 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004680
4681 // Single element and zero sized arrays should be allowed, by the definition
4682 // above, but they are not.
4683
4684 // Otherwise, it must be a record type.
4685 const RecordType *RT = Ty->getAs<RecordType>();
4686 if (!RT) return false;
4687
4688 // Ignore records with flexible arrays.
4689 const RecordDecl *RD = RT->getDecl();
4690 if (RD->hasFlexibleArrayMember())
4691 return false;
4692
4693 // Check that all sub-fields are at offset 0, and are themselves "integer
4694 // like".
4695 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4696
4697 bool HadField = false;
4698 unsigned idx = 0;
4699 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4700 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004701 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004702
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004703 // Bit-fields are not addressable, we only need to verify they are "integer
4704 // like". We still have to disallow a subsequent non-bitfield, for example:
4705 // struct { int : 0; int x }
4706 // is non-integer like according to gcc.
4707 if (FD->isBitField()) {
4708 if (!RD->isUnion())
4709 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004710
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004711 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4712 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004713
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004714 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004715 }
4716
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004717 // Check if this field is at offset 0.
4718 if (Layout.getFieldOffset(idx) != 0)
4719 return false;
4720
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004721 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4722 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004723
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004724 // Only allow at most one field in a structure. This doesn't match the
4725 // wording above, but follows gcc in situations with a field following an
4726 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004727 if (!RD->isUnion()) {
4728 if (HadField)
4729 return false;
4730
4731 HadField = true;
4732 }
4733 }
4734
4735 return true;
4736}
4737
Oliver Stannard405bded2014-02-11 09:25:50 +00004738ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4739 bool isVariadic) const {
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004740 const bool isAAPCS_VFP =
4741 getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic;
4742
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004743 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004744 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004745
Daniel Dunbar19964db2010-09-23 01:54:32 +00004746 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004747 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4748 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004749 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004750 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004751
John McCalla1dee5302010-08-22 10:59:02 +00004752 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004753 // Treat an enum type as its underlying type.
4754 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4755 RetTy = EnumTy->getDecl()->getIntegerType();
4756
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004757 return (RetTy->isPromotableIntegerType()
4758 ? ABIArgInfo::getExtend()
4759 : ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP));
Douglas Gregora71cc152010-02-02 20:10:50 +00004760 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004761
4762 // Are we following APCS?
4763 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004764 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004765 return ABIArgInfo::getIgnore();
4766
Daniel Dunbareedf1512010-02-01 23:31:19 +00004767 // Complex types are all returned as packed integers.
4768 //
4769 // FIXME: Consider using 2 x vector types if the back end handles them
4770 // correctly.
4771 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004772 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4773 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004774
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004775 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004776 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004777 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004778 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004779 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004780 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004781 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004782 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4783 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004784 }
4785
4786 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004787 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004788 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004789 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004790
4791 // Otherwise this is an AAPCS variant.
4792
Chris Lattner458b2aa2010-07-29 02:16:43 +00004793 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004794 return ABIArgInfo::getIgnore();
4795
Bob Wilson1d9269a2011-11-02 04:51:36 +00004796 // Check for homogeneous aggregates with AAPCS-VFP.
Amara Emerson9dc78782014-01-28 10:56:36 +00004797 if (getABIKind() == AAPCS_VFP && !isVariadic) {
Craig Topper8a13c412014-05-21 05:09:00 +00004798 const Type *Base = nullptr;
Oliver Stannarded8ecc82014-08-27 16:31:57 +00004799 if (isARMHomogeneousAggregate(RetTy, Base, getContext(), false)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004800 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004801 // Homogeneous Aggregates are returned directly.
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004802 return ABIArgInfo::getDirect(nullptr, 0, nullptr, !isAAPCS_VFP);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004803 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004804 }
4805
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004806 // Aggregates <= 4 bytes are returned in r0; other aggregates
4807 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004808 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004809 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004810 if (getDataLayout().isBigEndian())
4811 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004812 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4813 nullptr, !isAAPCS_VFP);
Christian Pirkerc3d32172014-07-03 09:28:12 +00004814
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004815 // Return in the smallest viable integer type.
4816 if (Size <= 8)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004817 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()), 0,
4818 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004819 if (Size <= 16)
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004820 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()), 0,
4821 nullptr, !isAAPCS_VFP);
4822 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()), 0,
4823 nullptr, !isAAPCS_VFP);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004824 }
4825
Oliver Stannard405bded2014-02-11 09:25:50 +00004826 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004827 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004828}
4829
Manman Renfef9e312012-10-16 19:18:39 +00004830/// isIllegalVector - check whether Ty is an illegal vector type.
4831bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4832 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4833 // Check whether VT is legal.
4834 unsigned NumElements = VT->getNumElements();
4835 uint64_t Size = getContext().getTypeSize(VT);
4836 // NumElements should be power of 2.
4837 if ((NumElements & (NumElements - 1)) != 0)
4838 return true;
4839 // Size should be greater than 32 bits.
4840 return Size <= 32;
4841 }
4842 return false;
4843}
4844
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004845llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004846 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004847 llvm::Type *BP = CGF.Int8PtrTy;
4848 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004849
4850 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004851 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004852 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004853
Tim Northover1711cc92013-06-21 23:05:33 +00004854 if (isEmptyRecord(getContext(), Ty, true)) {
4855 // These are ignored for parameter passing purposes.
4856 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4857 return Builder.CreateBitCast(Addr, PTy);
4858 }
4859
Manman Rencca54d02012-10-16 19:01:37 +00004860 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004861 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004862 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004863
4864 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4865 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004866 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4867 getABIKind() == ARMABIInfo::AAPCS)
4868 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4869 else
4870 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004871 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4872 if (isIllegalVectorType(Ty) && Size > 16) {
4873 IsIndirect = true;
4874 Size = 4;
4875 TyAlign = 4;
4876 }
Manman Rencca54d02012-10-16 19:01:37 +00004877
4878 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00004879 if (TyAlign > 4) {
4880 assert((TyAlign & (TyAlign - 1)) == 0 &&
4881 "Alignment is not power of 2!");
4882 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
4883 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
4884 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00004885 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00004886 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004887
4888 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00004889 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004890 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00004891 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004892 "ap.next");
4893 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4894
Manman Renfef9e312012-10-16 19:18:39 +00004895 if (IsIndirect)
4896 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00004897 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00004898 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
4899 // may not be correctly aligned for the vector type. We create an aligned
4900 // temporary space and copy the content over from ap.cur to the temporary
4901 // space. This is necessary if the natural alignment of the type is greater
4902 // than the ABI alignment.
4903 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
4904 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
4905 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
4906 "var.align");
4907 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
4908 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
4909 Builder.CreateMemCpy(Dst, Src,
4910 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
4911 TyAlign, false);
4912 Addr = AlignedTemp; //The content is in aligned location.
4913 }
4914 llvm::Type *PTy =
4915 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4916 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4917
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004918 return AddrTyped;
4919}
4920
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004921namespace {
4922
Derek Schuffa2020962012-10-16 22:30:41 +00004923class NaClARMABIInfo : public ABIInfo {
4924 public:
4925 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4926 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004927 void computeInfo(CGFunctionInfo &FI) const override;
4928 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4929 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00004930 private:
4931 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
4932 ARMABIInfo NInfo; // Used for everything else.
4933};
4934
4935class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
4936 public:
4937 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
4938 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
4939};
4940
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00004941}
4942
Derek Schuffa2020962012-10-16 22:30:41 +00004943void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
4944 if (FI.getASTCallingConvention() == CC_PnaclCall)
4945 PInfo.computeInfo(FI);
4946 else
4947 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
4948}
4949
4950llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4951 CodeGenFunction &CGF) const {
4952 // Always use the native convention; calling pnacl-style varargs functions
4953 // is unsupported.
4954 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
4955}
4956
Chris Lattner0cf24192010-06-28 20:05:43 +00004957//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00004958// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004959//===----------------------------------------------------------------------===//
4960
4961namespace {
4962
Justin Holewinski83e96682012-05-24 17:43:12 +00004963class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004964public:
Justin Holewinski36837432013-03-30 14:38:24 +00004965 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004966
4967 ABIArgInfo classifyReturnType(QualType RetTy) const;
4968 ABIArgInfo classifyArgumentType(QualType Ty) const;
4969
Craig Topper4f12f102014-03-12 06:41:41 +00004970 void computeInfo(CGFunctionInfo &FI) const override;
4971 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4972 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004973};
4974
Justin Holewinski83e96682012-05-24 17:43:12 +00004975class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004976public:
Justin Holewinski83e96682012-05-24 17:43:12 +00004977 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4978 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00004979
4980 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4981 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00004982private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00004983 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
4984 // resulting MDNode to the nvvm.annotations MDNode.
4985 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004986};
4987
Justin Holewinski83e96682012-05-24 17:43:12 +00004988ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00004989 if (RetTy->isVoidType())
4990 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00004991
4992 // note: this is different from default ABI
4993 if (!RetTy->isScalarType())
4994 return ABIArgInfo::getDirect();
4995
4996 // Treat an enum type as its underlying type.
4997 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4998 RetTy = EnumTy->getDecl()->getIntegerType();
4999
5000 return (RetTy->isPromotableIntegerType() ?
5001 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005002}
5003
Justin Holewinski83e96682012-05-24 17:43:12 +00005004ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005005 // Treat an enum type as its underlying type.
5006 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5007 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005008
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005009 return (Ty->isPromotableIntegerType() ?
5010 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005011}
5012
Justin Holewinski83e96682012-05-24 17:43:12 +00005013void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005014 if (!getCXXABI().classifyReturnType(FI))
5015 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005016 for (auto &I : FI.arguments())
5017 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005018
5019 // Always honor user-specified calling convention.
5020 if (FI.getCallingConvention() != llvm::CallingConv::C)
5021 return;
5022
John McCall882987f2013-02-28 19:01:20 +00005023 FI.setEffectiveCallingConvention(getRuntimeCC());
5024}
5025
Justin Holewinski83e96682012-05-24 17:43:12 +00005026llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5027 CodeGenFunction &CFG) const {
5028 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005029}
5030
Justin Holewinski83e96682012-05-24 17:43:12 +00005031void NVPTXTargetCodeGenInfo::
5032SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5033 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005034 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5035 if (!FD) return;
5036
5037 llvm::Function *F = cast<llvm::Function>(GV);
5038
5039 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005040 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005041 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005042 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005043 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005044 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005045 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5046 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005047 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005048 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005049 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005050 }
Justin Holewinski38031972011-10-05 17:58:44 +00005051
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005052 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005053 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005054 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005055 // __global__ functions cannot be called from the device, we do not
5056 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005057 if (FD->hasAttr<CUDAGlobalAttr>()) {
5058 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5059 addNVVMMetadata(F, "kernel", 1);
5060 }
5061 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5062 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5063 addNVVMMetadata(F, "maxntidx",
5064 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5065 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5066 // zero value from getMinBlocks either means it was not specified in
5067 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5068 // don't have to add a PTX directive.
5069 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5070 if (MinCTASM > 0) {
5071 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5072 addNVVMMetadata(F, "minctasm", MinCTASM);
5073 }
5074 }
Justin Holewinski38031972011-10-05 17:58:44 +00005075 }
5076}
5077
Eli Benderskye06a2c42014-04-15 16:57:05 +00005078void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5079 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005080 llvm::Module *M = F->getParent();
5081 llvm::LLVMContext &Ctx = M->getContext();
5082
5083 // Get "nvvm.annotations" metadata node
5084 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5085
Eli Benderskye1627b42014-04-15 17:19:26 +00005086 llvm::Value *MDVals[] = {
5087 F, llvm::MDString::get(Ctx, Name),
5088 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand)};
Justin Holewinski36837432013-03-30 14:38:24 +00005089 // Append metadata to nvvm.annotations
5090 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5091}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005092}
5093
5094//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005095// SystemZ ABI Implementation
5096//===----------------------------------------------------------------------===//
5097
5098namespace {
5099
5100class SystemZABIInfo : public ABIInfo {
5101public:
5102 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5103
5104 bool isPromotableIntegerType(QualType Ty) const;
5105 bool isCompoundType(QualType Ty) const;
5106 bool isFPArgumentType(QualType Ty) const;
5107
5108 ABIArgInfo classifyReturnType(QualType RetTy) const;
5109 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5110
Craig Topper4f12f102014-03-12 06:41:41 +00005111 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005112 if (!getCXXABI().classifyReturnType(FI))
5113 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005114 for (auto &I : FI.arguments())
5115 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005116 }
5117
Craig Topper4f12f102014-03-12 06:41:41 +00005118 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5119 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005120};
5121
5122class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5123public:
5124 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5125 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5126};
5127
5128}
5129
5130bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5131 // Treat an enum type as its underlying type.
5132 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5133 Ty = EnumTy->getDecl()->getIntegerType();
5134
5135 // Promotable integer types are required to be promoted by the ABI.
5136 if (Ty->isPromotableIntegerType())
5137 return true;
5138
5139 // 32-bit values must also be promoted.
5140 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5141 switch (BT->getKind()) {
5142 case BuiltinType::Int:
5143 case BuiltinType::UInt:
5144 return true;
5145 default:
5146 return false;
5147 }
5148 return false;
5149}
5150
5151bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5152 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5153}
5154
5155bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5156 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5157 switch (BT->getKind()) {
5158 case BuiltinType::Float:
5159 case BuiltinType::Double:
5160 return true;
5161 default:
5162 return false;
5163 }
5164
5165 if (const RecordType *RT = Ty->getAsStructureType()) {
5166 const RecordDecl *RD = RT->getDecl();
5167 bool Found = false;
5168
5169 // If this is a C++ record, check the bases first.
5170 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005171 for (const auto &I : CXXRD->bases()) {
5172 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005173
5174 // Empty bases don't affect things either way.
5175 if (isEmptyRecord(getContext(), Base, true))
5176 continue;
5177
5178 if (Found)
5179 return false;
5180 Found = isFPArgumentType(Base);
5181 if (!Found)
5182 return false;
5183 }
5184
5185 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005186 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005187 // Empty bitfields don't affect things either way.
5188 // Unlike isSingleElementStruct(), empty structure and array fields
5189 // do count. So do anonymous bitfields that aren't zero-sized.
5190 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5191 return true;
5192
5193 // Unlike isSingleElementStruct(), arrays do not count.
5194 // Nested isFPArgumentType structures still do though.
5195 if (Found)
5196 return false;
5197 Found = isFPArgumentType(FD->getType());
5198 if (!Found)
5199 return false;
5200 }
5201
5202 // Unlike isSingleElementStruct(), trailing padding is allowed.
5203 // An 8-byte aligned struct s { float f; } is passed as a double.
5204 return Found;
5205 }
5206
5207 return false;
5208}
5209
5210llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5211 CodeGenFunction &CGF) const {
5212 // Assume that va_list type is correct; should be pointer to LLVM type:
5213 // struct {
5214 // i64 __gpr;
5215 // i64 __fpr;
5216 // i8 *__overflow_arg_area;
5217 // i8 *__reg_save_area;
5218 // };
5219
5220 // Every argument occupies 8 bytes and is passed by preference in either
5221 // GPRs or FPRs.
5222 Ty = CGF.getContext().getCanonicalType(Ty);
5223 ABIArgInfo AI = classifyArgumentType(Ty);
5224 bool InFPRs = isFPArgumentType(Ty);
5225
5226 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5227 bool IsIndirect = AI.isIndirect();
5228 unsigned UnpaddedBitSize;
5229 if (IsIndirect) {
5230 APTy = llvm::PointerType::getUnqual(APTy);
5231 UnpaddedBitSize = 64;
5232 } else
5233 UnpaddedBitSize = getContext().getTypeSize(Ty);
5234 unsigned PaddedBitSize = 64;
5235 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5236
5237 unsigned PaddedSize = PaddedBitSize / 8;
5238 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5239
5240 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5241 if (InFPRs) {
5242 MaxRegs = 4; // Maximum of 4 FPR arguments
5243 RegCountField = 1; // __fpr
5244 RegSaveIndex = 16; // save offset for f0
5245 RegPadding = 0; // floats are passed in the high bits of an FPR
5246 } else {
5247 MaxRegs = 5; // Maximum of 5 GPR arguments
5248 RegCountField = 0; // __gpr
5249 RegSaveIndex = 2; // save offset for r2
5250 RegPadding = Padding; // values are passed in the low bits of a GPR
5251 }
5252
5253 llvm::Value *RegCountPtr =
5254 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5255 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5256 llvm::Type *IndexTy = RegCount->getType();
5257 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5258 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005259 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005260
5261 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5262 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5263 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5264 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5265
5266 // Emit code to load the value if it was passed in registers.
5267 CGF.EmitBlock(InRegBlock);
5268
5269 // Work out the address of an argument register.
5270 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5271 llvm::Value *ScaledRegCount =
5272 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5273 llvm::Value *RegBase =
5274 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5275 llvm::Value *RegOffset =
5276 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5277 llvm::Value *RegSaveAreaPtr =
5278 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5279 llvm::Value *RegSaveArea =
5280 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5281 llvm::Value *RawRegAddr =
5282 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5283 llvm::Value *RegAddr =
5284 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5285
5286 // Update the register count
5287 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5288 llvm::Value *NewRegCount =
5289 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5290 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5291 CGF.EmitBranch(ContBlock);
5292
5293 // Emit code to load the value if it was passed in memory.
5294 CGF.EmitBlock(InMemBlock);
5295
5296 // Work out the address of a stack argument.
5297 llvm::Value *OverflowArgAreaPtr =
5298 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5299 llvm::Value *OverflowArgArea =
5300 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5301 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5302 llvm::Value *RawMemAddr =
5303 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5304 llvm::Value *MemAddr =
5305 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5306
5307 // Update overflow_arg_area_ptr pointer
5308 llvm::Value *NewOverflowArgArea =
5309 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5310 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5311 CGF.EmitBranch(ContBlock);
5312
5313 // Return the appropriate result.
5314 CGF.EmitBlock(ContBlock);
5315 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5316 ResAddr->addIncoming(RegAddr, InRegBlock);
5317 ResAddr->addIncoming(MemAddr, InMemBlock);
5318
5319 if (IsIndirect)
5320 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5321
5322 return ResAddr;
5323}
5324
Ulrich Weigand47445072013-05-06 16:26:41 +00005325ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5326 if (RetTy->isVoidType())
5327 return ABIArgInfo::getIgnore();
5328 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5329 return ABIArgInfo::getIndirect(0);
5330 return (isPromotableIntegerType(RetTy) ?
5331 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5332}
5333
5334ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5335 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005336 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005337 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5338
5339 // Integers and enums are extended to full register width.
5340 if (isPromotableIntegerType(Ty))
5341 return ABIArgInfo::getExtend();
5342
5343 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5344 uint64_t Size = getContext().getTypeSize(Ty);
5345 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005346 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005347
5348 // Handle small structures.
5349 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5350 // Structures with flexible arrays have variable length, so really
5351 // fail the size test above.
5352 const RecordDecl *RD = RT->getDecl();
5353 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005354 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005355
5356 // The structure is passed as an unextended integer, a float, or a double.
5357 llvm::Type *PassTy;
5358 if (isFPArgumentType(Ty)) {
5359 assert(Size == 32 || Size == 64);
5360 if (Size == 32)
5361 PassTy = llvm::Type::getFloatTy(getVMContext());
5362 else
5363 PassTy = llvm::Type::getDoubleTy(getVMContext());
5364 } else
5365 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5366 return ABIArgInfo::getDirect(PassTy);
5367 }
5368
5369 // Non-structure compounds are passed indirectly.
5370 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005371 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005372
Craig Topper8a13c412014-05-21 05:09:00 +00005373 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005374}
5375
5376//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005377// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005378//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005379
5380namespace {
5381
5382class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5383public:
Chris Lattner2b037972010-07-29 02:01:43 +00005384 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5385 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005386 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005387 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005388};
5389
5390}
5391
5392void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5393 llvm::GlobalValue *GV,
5394 CodeGen::CodeGenModule &M) const {
5395 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5396 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5397 // Handle 'interrupt' attribute:
5398 llvm::Function *F = cast<llvm::Function>(GV);
5399
5400 // Step 1: Set ISR calling convention.
5401 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5402
5403 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005404 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005405
5406 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005407 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005408 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5409 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005410 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005411 }
5412}
5413
Chris Lattner0cf24192010-06-28 20:05:43 +00005414//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005415// MIPS ABI Implementation. This works for both little-endian and
5416// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005417//===----------------------------------------------------------------------===//
5418
John McCall943fae92010-05-27 06:19:26 +00005419namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005420class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005421 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005422 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5423 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005424 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005425 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005426 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005427 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005428public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005429 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005430 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005431 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005432
5433 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005434 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005435 void computeInfo(CGFunctionInfo &FI) const override;
5436 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5437 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005438};
5439
John McCall943fae92010-05-27 06:19:26 +00005440class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005441 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005442public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005443 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5444 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005445 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005446
Craig Topper4f12f102014-03-12 06:41:41 +00005447 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005448 return 29;
5449 }
5450
Reed Kotler373feca2013-01-16 17:10:28 +00005451 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005452 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005453 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5454 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005455 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005456 if (FD->hasAttr<Mips16Attr>()) {
5457 Fn->addFnAttr("mips16");
5458 }
5459 else if (FD->hasAttr<NoMips16Attr>()) {
5460 Fn->addFnAttr("nomips16");
5461 }
Reed Kotler373feca2013-01-16 17:10:28 +00005462 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005463
John McCall943fae92010-05-27 06:19:26 +00005464 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005465 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005466
Craig Topper4f12f102014-03-12 06:41:41 +00005467 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005468 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005469 }
John McCall943fae92010-05-27 06:19:26 +00005470};
5471}
5472
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005473void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005474 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005475 llvm::IntegerType *IntTy =
5476 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005477
5478 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5479 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5480 ArgList.push_back(IntTy);
5481
5482 // If necessary, add one more integer type to ArgList.
5483 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5484
5485 if (R)
5486 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005487}
5488
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005489// In N32/64, an aligned double precision floating point field is passed in
5490// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005491llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005492 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5493
5494 if (IsO32) {
5495 CoerceToIntArgs(TySize, ArgList);
5496 return llvm::StructType::get(getVMContext(), ArgList);
5497 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005498
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005499 if (Ty->isComplexType())
5500 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005501
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005502 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005503
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005504 // Unions/vectors are passed in integer registers.
5505 if (!RT || !RT->isStructureOrClassType()) {
5506 CoerceToIntArgs(TySize, ArgList);
5507 return llvm::StructType::get(getVMContext(), ArgList);
5508 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005509
5510 const RecordDecl *RD = RT->getDecl();
5511 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005512 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005513
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005514 uint64_t LastOffset = 0;
5515 unsigned idx = 0;
5516 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5517
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005518 // Iterate over fields in the struct/class and check if there are any aligned
5519 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005520 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5521 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005522 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005523 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5524
5525 if (!BT || BT->getKind() != BuiltinType::Double)
5526 continue;
5527
5528 uint64_t Offset = Layout.getFieldOffset(idx);
5529 if (Offset % 64) // Ignore doubles that are not aligned.
5530 continue;
5531
5532 // Add ((Offset - LastOffset) / 64) args of type i64.
5533 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5534 ArgList.push_back(I64);
5535
5536 // Add double type.
5537 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5538 LastOffset = Offset + 64;
5539 }
5540
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005541 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5542 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005543
5544 return llvm::StructType::get(getVMContext(), ArgList);
5545}
5546
Akira Hatanakaddd66342013-10-29 18:41:15 +00005547llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5548 uint64_t Offset) const {
5549 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005550 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005551
Akira Hatanakaddd66342013-10-29 18:41:15 +00005552 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005553}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005554
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005555ABIArgInfo
5556MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005557 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005558 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005559 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005560
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005561 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5562 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005563 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5564 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005565
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005566 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005567 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005568 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005569 return ABIArgInfo::getIgnore();
5570
Mark Lacey3825e832013-10-06 01:33:34 +00005571 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005572 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005573 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005574 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005575
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005576 // If we have reached here, aggregates are passed directly by coercing to
5577 // another structure type. Padding is inserted if the offset of the
5578 // aggregate is unaligned.
5579 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanakaddd66342013-10-29 18:41:15 +00005580 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005581 }
5582
5583 // Treat an enum type as its underlying type.
5584 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5585 Ty = EnumTy->getDecl()->getIntegerType();
5586
Akira Hatanaka1632af62012-01-09 19:31:25 +00005587 if (Ty->isPromotableIntegerType())
5588 return ABIArgInfo::getExtend();
5589
Akira Hatanakaddd66342013-10-29 18:41:15 +00005590 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005591 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005592}
5593
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005594llvm::Type*
5595MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005596 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005597 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005598
Akira Hatanakab6f74432012-02-09 18:49:26 +00005599 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005600 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005601 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5602 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005603
Akira Hatanakab6f74432012-02-09 18:49:26 +00005604 // N32/64 returns struct/classes in floating point registers if the
5605 // following conditions are met:
5606 // 1. The size of the struct/class is no larger than 128-bit.
5607 // 2. The struct/class has one or two fields all of which are floating
5608 // point types.
5609 // 3. The offset of the first field is zero (this follows what gcc does).
5610 //
5611 // Any other composite results are returned in integer registers.
5612 //
5613 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5614 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5615 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005616 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005617
Akira Hatanakab6f74432012-02-09 18:49:26 +00005618 if (!BT || !BT->isFloatingPoint())
5619 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005620
David Blaikie2d7c57e2012-04-30 02:36:29 +00005621 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005622 }
5623
5624 if (b == e)
5625 return llvm::StructType::get(getVMContext(), RTList,
5626 RD->hasAttr<PackedAttr>());
5627
5628 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005629 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005630 }
5631
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005632 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005633 return llvm::StructType::get(getVMContext(), RTList);
5634}
5635
Akira Hatanakab579fe52011-06-02 00:09:17 +00005636ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005637 uint64_t Size = getContext().getTypeSize(RetTy);
5638
Daniel Sandersed39f582014-09-04 13:28:14 +00005639 if (RetTy->isVoidType())
5640 return ABIArgInfo::getIgnore();
5641
5642 // O32 doesn't treat zero-sized structs differently from other structs.
5643 // However, N32/N64 ignores zero sized return values.
5644 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005645 return ABIArgInfo::getIgnore();
5646
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005647 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005648 if (Size <= 128) {
5649 if (RetTy->isAnyComplexType())
5650 return ABIArgInfo::getDirect();
5651
Daniel Sanderse5018b62014-09-04 15:05:39 +00005652 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005653 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005654 if (!IsO32 ||
5655 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5656 ABIArgInfo ArgInfo =
5657 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5658 ArgInfo.setInReg(true);
5659 return ArgInfo;
5660 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005661 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005662
5663 return ABIArgInfo::getIndirect(0);
5664 }
5665
5666 // Treat an enum type as its underlying type.
5667 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5668 RetTy = EnumTy->getDecl()->getIntegerType();
5669
5670 return (RetTy->isPromotableIntegerType() ?
5671 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5672}
5673
5674void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005675 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005676 if (!getCXXABI().classifyReturnType(FI))
5677 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005678
5679 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005680 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005681
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005682 for (auto &I : FI.arguments())
5683 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005684}
5685
5686llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5687 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005688 llvm::Type *BP = CGF.Int8PtrTy;
5689 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5690
5691 CGBuilderTy &Builder = CGF.Builder;
5692 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5693 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5694 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
5695 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5696 llvm::Value *AddrTyped;
5697 unsigned PtrWidth = getTarget().getPointerWidth(0);
5698 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5699
5700 if (TypeAlign > MinABIStackAlignInBytes) {
5701 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5702 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5703 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5704 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5705 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5706 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5707 }
5708 else
5709 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5710
5711 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5712 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
5713 uint64_t Offset =
5714 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
5715 llvm::Value *NextAddr =
5716 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5717 "ap.next");
5718 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5719
5720 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005721}
5722
John McCall943fae92010-05-27 06:19:26 +00005723bool
5724MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5725 llvm::Value *Address) const {
5726 // This information comes from gcc's implementation, which seems to
5727 // as canonical as it gets.
5728
John McCall943fae92010-05-27 06:19:26 +00005729 // Everything on MIPS is 4 bytes. Double-precision FP registers
5730 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005731 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005732
5733 // 0-31 are the general purpose registers, $0 - $31.
5734 // 32-63 are the floating-point registers, $f0 - $f31.
5735 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5736 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005737 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005738
5739 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5740 // They are one bit wide and ignored here.
5741
5742 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5743 // (coprocessor 1 is the FP unit)
5744 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5745 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5746 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005747 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005748 return false;
5749}
5750
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005751//===----------------------------------------------------------------------===//
5752// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5753// Currently subclassed only to implement custom OpenCL C function attribute
5754// handling.
5755//===----------------------------------------------------------------------===//
5756
5757namespace {
5758
5759class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5760public:
5761 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5762 : DefaultTargetCodeGenInfo(CGT) {}
5763
Craig Topper4f12f102014-03-12 06:41:41 +00005764 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5765 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005766};
5767
5768void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5769 llvm::GlobalValue *GV,
5770 CodeGen::CodeGenModule &M) const {
5771 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5772 if (!FD) return;
5773
5774 llvm::Function *F = cast<llvm::Function>(GV);
5775
David Blaikiebbafb8a2012-03-11 07:00:24 +00005776 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005777 if (FD->hasAttr<OpenCLKernelAttr>()) {
5778 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005779 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005780 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5781 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005782 // Convert the reqd_work_group_size() attributes to metadata.
5783 llvm::LLVMContext &Context = F->getContext();
5784 llvm::NamedMDNode *OpenCLMetadata =
5785 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5786
5787 SmallVector<llvm::Value*, 5> Operands;
5788 Operands.push_back(F);
5789
Chris Lattnerece04092012-02-07 00:39:47 +00005790 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005791 llvm::APInt(32, Attr->getXDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005792 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005793 llvm::APInt(32, Attr->getYDim())));
Chris Lattnerece04092012-02-07 00:39:47 +00005794 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005795 llvm::APInt(32, Attr->getZDim())));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005796
5797 // Add a boolean constant operand for "required" (true) or "hint" (false)
5798 // for implementing the work_group_size_hint attr later. Currently
5799 // always true as the hint is not yet implemented.
Chris Lattnerece04092012-02-07 00:39:47 +00005800 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005801 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5802 }
5803 }
5804 }
5805}
5806
5807}
John McCall943fae92010-05-27 06:19:26 +00005808
Tony Linthicum76329bf2011-12-12 21:14:55 +00005809//===----------------------------------------------------------------------===//
5810// Hexagon ABI Implementation
5811//===----------------------------------------------------------------------===//
5812
5813namespace {
5814
5815class HexagonABIInfo : public ABIInfo {
5816
5817
5818public:
5819 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5820
5821private:
5822
5823 ABIArgInfo classifyReturnType(QualType RetTy) const;
5824 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5825
Craig Topper4f12f102014-03-12 06:41:41 +00005826 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005827
Craig Topper4f12f102014-03-12 06:41:41 +00005828 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5829 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005830};
5831
5832class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5833public:
5834 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5835 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5836
Craig Topper4f12f102014-03-12 06:41:41 +00005837 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005838 return 29;
5839 }
5840};
5841
5842}
5843
5844void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005845 if (!getCXXABI().classifyReturnType(FI))
5846 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005847 for (auto &I : FI.arguments())
5848 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005849}
5850
5851ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5852 if (!isAggregateTypeForABI(Ty)) {
5853 // Treat an enum type as its underlying type.
5854 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5855 Ty = EnumTy->getDecl()->getIntegerType();
5856
5857 return (Ty->isPromotableIntegerType() ?
5858 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5859 }
5860
5861 // Ignore empty records.
5862 if (isEmptyRecord(getContext(), Ty, true))
5863 return ABIArgInfo::getIgnore();
5864
Mark Lacey3825e832013-10-06 01:33:34 +00005865 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005866 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005867
5868 uint64_t Size = getContext().getTypeSize(Ty);
5869 if (Size > 64)
5870 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5871 // Pass in the smallest viable integer type.
5872 else if (Size > 32)
5873 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5874 else if (Size > 16)
5875 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5876 else if (Size > 8)
5877 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5878 else
5879 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5880}
5881
5882ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5883 if (RetTy->isVoidType())
5884 return ABIArgInfo::getIgnore();
5885
5886 // Large vector types should be returned via memory.
5887 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5888 return ABIArgInfo::getIndirect(0);
5889
5890 if (!isAggregateTypeForABI(RetTy)) {
5891 // Treat an enum type as its underlying type.
5892 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5893 RetTy = EnumTy->getDecl()->getIntegerType();
5894
5895 return (RetTy->isPromotableIntegerType() ?
5896 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5897 }
5898
Tony Linthicum76329bf2011-12-12 21:14:55 +00005899 if (isEmptyRecord(getContext(), RetTy, true))
5900 return ABIArgInfo::getIgnore();
5901
5902 // Aggregates <= 8 bytes are returned in r0; other aggregates
5903 // are returned indirectly.
5904 uint64_t Size = getContext().getTypeSize(RetTy);
5905 if (Size <= 64) {
5906 // Return in the smallest viable integer type.
5907 if (Size <= 8)
5908 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5909 if (Size <= 16)
5910 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5911 if (Size <= 32)
5912 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5913 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5914 }
5915
5916 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5917}
5918
5919llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00005920 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005921 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00005922 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005923
5924 CGBuilderTy &Builder = CGF.Builder;
5925 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5926 "ap");
5927 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5928 llvm::Type *PTy =
5929 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5930 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5931
5932 uint64_t Offset =
5933 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5934 llvm::Value *NextAddr =
5935 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5936 "ap.next");
5937 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5938
5939 return AddrTyped;
5940}
5941
5942
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00005943//===----------------------------------------------------------------------===//
5944// SPARC v9 ABI Implementation.
5945// Based on the SPARC Compliance Definition version 2.4.1.
5946//
5947// Function arguments a mapped to a nominal "parameter array" and promoted to
5948// registers depending on their type. Each argument occupies 8 or 16 bytes in
5949// the array, structs larger than 16 bytes are passed indirectly.
5950//
5951// One case requires special care:
5952//
5953// struct mixed {
5954// int i;
5955// float f;
5956// };
5957//
5958// When a struct mixed is passed by value, it only occupies 8 bytes in the
5959// parameter array, but the int is passed in an integer register, and the float
5960// is passed in a floating point register. This is represented as two arguments
5961// with the LLVM IR inreg attribute:
5962//
5963// declare void f(i32 inreg %i, float inreg %f)
5964//
5965// The code generator will only allocate 4 bytes from the parameter array for
5966// the inreg arguments. All other arguments are allocated a multiple of 8
5967// bytes.
5968//
5969namespace {
5970class SparcV9ABIInfo : public ABIInfo {
5971public:
5972 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5973
5974private:
5975 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005976 void computeInfo(CGFunctionInfo &FI) const override;
5977 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5978 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00005979
5980 // Coercion type builder for structs passed in registers. The coercion type
5981 // serves two purposes:
5982 //
5983 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5984 // in registers.
5985 // 2. Expose aligned floating point elements as first-level elements, so the
5986 // code generator knows to pass them in floating point registers.
5987 //
5988 // We also compute the InReg flag which indicates that the struct contains
5989 // aligned 32-bit floats.
5990 //
5991 struct CoerceBuilder {
5992 llvm::LLVMContext &Context;
5993 const llvm::DataLayout &DL;
5994 SmallVector<llvm::Type*, 8> Elems;
5995 uint64_t Size;
5996 bool InReg;
5997
5998 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5999 : Context(c), DL(dl), Size(0), InReg(false) {}
6000
6001 // Pad Elems with integers until Size is ToSize.
6002 void pad(uint64_t ToSize) {
6003 assert(ToSize >= Size && "Cannot remove elements");
6004 if (ToSize == Size)
6005 return;
6006
6007 // Finish the current 64-bit word.
6008 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6009 if (Aligned > Size && Aligned <= ToSize) {
6010 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6011 Size = Aligned;
6012 }
6013
6014 // Add whole 64-bit words.
6015 while (Size + 64 <= ToSize) {
6016 Elems.push_back(llvm::Type::getInt64Ty(Context));
6017 Size += 64;
6018 }
6019
6020 // Final in-word padding.
6021 if (Size < ToSize) {
6022 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6023 Size = ToSize;
6024 }
6025 }
6026
6027 // Add a floating point element at Offset.
6028 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6029 // Unaligned floats are treated as integers.
6030 if (Offset % Bits)
6031 return;
6032 // The InReg flag is only required if there are any floats < 64 bits.
6033 if (Bits < 64)
6034 InReg = true;
6035 pad(Offset);
6036 Elems.push_back(Ty);
6037 Size = Offset + Bits;
6038 }
6039
6040 // Add a struct type to the coercion type, starting at Offset (in bits).
6041 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6042 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6043 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6044 llvm::Type *ElemTy = StrTy->getElementType(i);
6045 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6046 switch (ElemTy->getTypeID()) {
6047 case llvm::Type::StructTyID:
6048 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6049 break;
6050 case llvm::Type::FloatTyID:
6051 addFloat(ElemOffset, ElemTy, 32);
6052 break;
6053 case llvm::Type::DoubleTyID:
6054 addFloat(ElemOffset, ElemTy, 64);
6055 break;
6056 case llvm::Type::FP128TyID:
6057 addFloat(ElemOffset, ElemTy, 128);
6058 break;
6059 case llvm::Type::PointerTyID:
6060 if (ElemOffset % 64 == 0) {
6061 pad(ElemOffset);
6062 Elems.push_back(ElemTy);
6063 Size += 64;
6064 }
6065 break;
6066 default:
6067 break;
6068 }
6069 }
6070 }
6071
6072 // Check if Ty is a usable substitute for the coercion type.
6073 bool isUsableType(llvm::StructType *Ty) const {
6074 if (Ty->getNumElements() != Elems.size())
6075 return false;
6076 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6077 if (Elems[i] != Ty->getElementType(i))
6078 return false;
6079 return true;
6080 }
6081
6082 // Get the coercion type as a literal struct type.
6083 llvm::Type *getType() const {
6084 if (Elems.size() == 1)
6085 return Elems.front();
6086 else
6087 return llvm::StructType::get(Context, Elems);
6088 }
6089 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006090};
6091} // end anonymous namespace
6092
6093ABIArgInfo
6094SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6095 if (Ty->isVoidType())
6096 return ABIArgInfo::getIgnore();
6097
6098 uint64_t Size = getContext().getTypeSize(Ty);
6099
6100 // Anything too big to fit in registers is passed with an explicit indirect
6101 // pointer / sret pointer.
6102 if (Size > SizeLimit)
6103 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6104
6105 // Treat an enum type as its underlying type.
6106 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6107 Ty = EnumTy->getDecl()->getIntegerType();
6108
6109 // Integer types smaller than a register are extended.
6110 if (Size < 64 && Ty->isIntegerType())
6111 return ABIArgInfo::getExtend();
6112
6113 // Other non-aggregates go in registers.
6114 if (!isAggregateTypeForABI(Ty))
6115 return ABIArgInfo::getDirect();
6116
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006117 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6118 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6119 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6120 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6121
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006122 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006123 // Build a coercion type from the LLVM struct type.
6124 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6125 if (!StrTy)
6126 return ABIArgInfo::getDirect();
6127
6128 CoerceBuilder CB(getVMContext(), getDataLayout());
6129 CB.addStruct(0, StrTy);
6130 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6131
6132 // Try to use the original type for coercion.
6133 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6134
6135 if (CB.InReg)
6136 return ABIArgInfo::getDirectInReg(CoerceTy);
6137 else
6138 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006139}
6140
6141llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6142 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006143 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6144 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6145 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6146 AI.setCoerceToType(ArgTy);
6147
6148 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6149 CGBuilderTy &Builder = CGF.Builder;
6150 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6151 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6152 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6153 llvm::Value *ArgAddr;
6154 unsigned Stride;
6155
6156 switch (AI.getKind()) {
6157 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006158 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006159 llvm_unreachable("Unsupported ABI kind for va_arg");
6160
6161 case ABIArgInfo::Extend:
6162 Stride = 8;
6163 ArgAddr = Builder
6164 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6165 "extend");
6166 break;
6167
6168 case ABIArgInfo::Direct:
6169 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6170 ArgAddr = Addr;
6171 break;
6172
6173 case ABIArgInfo::Indirect:
6174 Stride = 8;
6175 ArgAddr = Builder.CreateBitCast(Addr,
6176 llvm::PointerType::getUnqual(ArgPtrTy),
6177 "indirect");
6178 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6179 break;
6180
6181 case ABIArgInfo::Ignore:
6182 return llvm::UndefValue::get(ArgPtrTy);
6183 }
6184
6185 // Update VAList.
6186 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6187 Builder.CreateStore(Addr, VAListAddrAsBPP);
6188
6189 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006190}
6191
6192void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6193 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006194 for (auto &I : FI.arguments())
6195 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006196}
6197
6198namespace {
6199class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6200public:
6201 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6202 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006203
Craig Topper4f12f102014-03-12 06:41:41 +00006204 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006205 return 14;
6206 }
6207
6208 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006209 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006210};
6211} // end anonymous namespace
6212
Roman Divackyf02c9942014-02-24 18:46:27 +00006213bool
6214SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6215 llvm::Value *Address) const {
6216 // This is calculated from the LLVM and GCC tables and verified
6217 // against gcc output. AFAIK all ABIs use the same encoding.
6218
6219 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6220
6221 llvm::IntegerType *i8 = CGF.Int8Ty;
6222 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6223 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6224
6225 // 0-31: the 8-byte general-purpose registers
6226 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6227
6228 // 32-63: f0-31, the 4-byte floating-point registers
6229 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6230
6231 // Y = 64
6232 // PSR = 65
6233 // WIM = 66
6234 // TBR = 67
6235 // PC = 68
6236 // NPC = 69
6237 // FSR = 70
6238 // CSR = 71
6239 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6240
6241 // 72-87: d0-15, the 8-byte floating-point registers
6242 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6243
6244 return false;
6245}
6246
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006247
Robert Lytton0e076492013-08-13 09:43:10 +00006248//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006249// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006250//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006251
Robert Lytton0e076492013-08-13 09:43:10 +00006252namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006253
6254/// A SmallStringEnc instance is used to build up the TypeString by passing
6255/// it by reference between functions that append to it.
6256typedef llvm::SmallString<128> SmallStringEnc;
6257
6258/// TypeStringCache caches the meta encodings of Types.
6259///
6260/// The reason for caching TypeStrings is two fold:
6261/// 1. To cache a type's encoding for later uses;
6262/// 2. As a means to break recursive member type inclusion.
6263///
6264/// A cache Entry can have a Status of:
6265/// NonRecursive: The type encoding is not recursive;
6266/// Recursive: The type encoding is recursive;
6267/// Incomplete: An incomplete TypeString;
6268/// IncompleteUsed: An incomplete TypeString that has been used in a
6269/// Recursive type encoding.
6270///
6271/// A NonRecursive entry will have all of its sub-members expanded as fully
6272/// as possible. Whilst it may contain types which are recursive, the type
6273/// itself is not recursive and thus its encoding may be safely used whenever
6274/// the type is encountered.
6275///
6276/// A Recursive entry will have all of its sub-members expanded as fully as
6277/// possible. The type itself is recursive and it may contain other types which
6278/// are recursive. The Recursive encoding must not be used during the expansion
6279/// of a recursive type's recursive branch. For simplicity the code uses
6280/// IncompleteCount to reject all usage of Recursive encodings for member types.
6281///
6282/// An Incomplete entry is always a RecordType and only encodes its
6283/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6284/// are placed into the cache during type expansion as a means to identify and
6285/// handle recursive inclusion of types as sub-members. If there is recursion
6286/// the entry becomes IncompleteUsed.
6287///
6288/// During the expansion of a RecordType's members:
6289///
6290/// If the cache contains a NonRecursive encoding for the member type, the
6291/// cached encoding is used;
6292///
6293/// If the cache contains a Recursive encoding for the member type, the
6294/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6295///
6296/// If the member is a RecordType, an Incomplete encoding is placed into the
6297/// cache to break potential recursive inclusion of itself as a sub-member;
6298///
6299/// Once a member RecordType has been expanded, its temporary incomplete
6300/// entry is removed from the cache. If a Recursive encoding was swapped out
6301/// it is swapped back in;
6302///
6303/// If an incomplete entry is used to expand a sub-member, the incomplete
6304/// entry is marked as IncompleteUsed. The cache keeps count of how many
6305/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6306///
6307/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6308/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6309/// Else the member is part of a recursive type and thus the recursion has
6310/// been exited too soon for the encoding to be correct for the member.
6311///
6312class TypeStringCache {
6313 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6314 struct Entry {
6315 std::string Str; // The encoded TypeString for the type.
6316 enum Status State; // Information about the encoding in 'Str'.
6317 std::string Swapped; // A temporary place holder for a Recursive encoding
6318 // during the expansion of RecordType's members.
6319 };
6320 std::map<const IdentifierInfo *, struct Entry> Map;
6321 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6322 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6323public:
Robert Lyttond263f142014-05-06 09:38:54 +00006324 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006325 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6326 bool removeIncomplete(const IdentifierInfo *ID);
6327 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6328 bool IsRecursive);
6329 StringRef lookupStr(const IdentifierInfo *ID);
6330};
6331
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006332/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006333/// FieldEncoding is a helper for this ordering process.
6334class FieldEncoding {
6335 bool HasName;
6336 std::string Enc;
6337public:
6338 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6339 StringRef str() {return Enc.c_str();};
6340 bool operator<(const FieldEncoding &rhs) const {
6341 if (HasName != rhs.HasName) return HasName;
6342 return Enc < rhs.Enc;
6343 }
6344};
6345
Robert Lytton7d1db152013-08-19 09:46:39 +00006346class XCoreABIInfo : public DefaultABIInfo {
6347public:
6348 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006349 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6350 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006351};
6352
Robert Lyttond21e2d72014-03-03 13:45:29 +00006353class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006354 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006355public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006356 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006357 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006358 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6359 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006360};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006361
Robert Lytton2d196952013-10-11 10:29:34 +00006362} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006363
Robert Lytton7d1db152013-08-19 09:46:39 +00006364llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6365 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006366 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006367
Robert Lytton2d196952013-10-11 10:29:34 +00006368 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006369 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6370 CGF.Int8PtrPtrTy);
6371 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006372
Robert Lytton2d196952013-10-11 10:29:34 +00006373 // Handle the argument.
6374 ABIArgInfo AI = classifyArgumentType(Ty);
6375 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6376 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6377 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006378 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006379 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006380 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006381 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006382 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006383 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006384 llvm_unreachable("Unsupported ABI kind for va_arg");
6385 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006386 Val = llvm::UndefValue::get(ArgPtrTy);
6387 ArgSize = 0;
6388 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006389 case ABIArgInfo::Extend:
6390 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006391 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6392 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6393 if (ArgSize < 4)
6394 ArgSize = 4;
6395 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006396 case ABIArgInfo::Indirect:
6397 llvm::Value *ArgAddr;
6398 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6399 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006400 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6401 ArgSize = 4;
6402 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006403 }
Robert Lytton2d196952013-10-11 10:29:34 +00006404
6405 // Increment the VAList.
6406 if (ArgSize) {
6407 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6408 Builder.CreateStore(APN, VAListAddrAsBPP);
6409 }
6410 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006411}
Robert Lytton0e076492013-08-13 09:43:10 +00006412
Robert Lytton844aeeb2014-05-02 09:33:20 +00006413/// During the expansion of a RecordType, an incomplete TypeString is placed
6414/// into the cache as a means to identify and break recursion.
6415/// If there is a Recursive encoding in the cache, it is swapped out and will
6416/// be reinserted by removeIncomplete().
6417/// All other types of encoding should have been used rather than arriving here.
6418void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6419 std::string StubEnc) {
6420 if (!ID)
6421 return;
6422 Entry &E = Map[ID];
6423 assert( (E.Str.empty() || E.State == Recursive) &&
6424 "Incorrectly use of addIncomplete");
6425 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6426 E.Swapped.swap(E.Str); // swap out the Recursive
6427 E.Str.swap(StubEnc);
6428 E.State = Incomplete;
6429 ++IncompleteCount;
6430}
6431
6432/// Once the RecordType has been expanded, the temporary incomplete TypeString
6433/// must be removed from the cache.
6434/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6435/// Returns true if the RecordType was defined recursively.
6436bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6437 if (!ID)
6438 return false;
6439 auto I = Map.find(ID);
6440 assert(I != Map.end() && "Entry not present");
6441 Entry &E = I->second;
6442 assert( (E.State == Incomplete ||
6443 E.State == IncompleteUsed) &&
6444 "Entry must be an incomplete type");
6445 bool IsRecursive = false;
6446 if (E.State == IncompleteUsed) {
6447 // We made use of our Incomplete encoding, thus we are recursive.
6448 IsRecursive = true;
6449 --IncompleteUsedCount;
6450 }
6451 if (E.Swapped.empty())
6452 Map.erase(I);
6453 else {
6454 // Swap the Recursive back.
6455 E.Swapped.swap(E.Str);
6456 E.Swapped.clear();
6457 E.State = Recursive;
6458 }
6459 --IncompleteCount;
6460 return IsRecursive;
6461}
6462
6463/// Add the encoded TypeString to the cache only if it is NonRecursive or
6464/// Recursive (viz: all sub-members were expanded as fully as possible).
6465void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6466 bool IsRecursive) {
6467 if (!ID || IncompleteUsedCount)
6468 return; // No key or it is is an incomplete sub-type so don't add.
6469 Entry &E = Map[ID];
6470 if (IsRecursive && !E.Str.empty()) {
6471 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6472 "This is not the same Recursive entry");
6473 // The parent container was not recursive after all, so we could have used
6474 // this Recursive sub-member entry after all, but we assumed the worse when
6475 // we started viz: IncompleteCount!=0.
6476 return;
6477 }
6478 assert(E.Str.empty() && "Entry already present");
6479 E.Str = Str.str();
6480 E.State = IsRecursive? Recursive : NonRecursive;
6481}
6482
6483/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6484/// are recursively expanding a type (IncompleteCount != 0) and the cached
6485/// encoding is Recursive, return an empty StringRef.
6486StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6487 if (!ID)
6488 return StringRef(); // We have no key.
6489 auto I = Map.find(ID);
6490 if (I == Map.end())
6491 return StringRef(); // We have no encoding.
6492 Entry &E = I->second;
6493 if (E.State == Recursive && IncompleteCount)
6494 return StringRef(); // We don't use Recursive encodings for member types.
6495
6496 if (E.State == Incomplete) {
6497 // The incomplete type is being used to break out of recursion.
6498 E.State = IncompleteUsed;
6499 ++IncompleteUsedCount;
6500 }
6501 return E.Str.c_str();
6502}
6503
6504/// The XCore ABI includes a type information section that communicates symbol
6505/// type information to the linker. The linker uses this information to verify
6506/// safety/correctness of things such as array bound and pointers et al.
6507/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6508/// This type information (TypeString) is emitted into meta data for all global
6509/// symbols: definitions, declarations, functions & variables.
6510///
6511/// The TypeString carries type, qualifier, name, size & value details.
6512/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6513/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6514/// The output is tested by test/CodeGen/xcore-stringtype.c.
6515///
6516static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6517 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6518
6519/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6520void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6521 CodeGen::CodeGenModule &CGM) const {
6522 SmallStringEnc Enc;
6523 if (getTypeString(Enc, D, CGM, TSC)) {
6524 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
6525 llvm::SmallVector<llvm::Value *, 2> MDVals;
6526 MDVals.push_back(GV);
6527 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6528 llvm::NamedMDNode *MD =
6529 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6530 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6531 }
6532}
6533
6534static bool appendType(SmallStringEnc &Enc, QualType QType,
6535 const CodeGen::CodeGenModule &CGM,
6536 TypeStringCache &TSC);
6537
6538/// Helper function for appendRecordType().
6539/// Builds a SmallVector containing the encoded field types in declaration order.
6540static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6541 const RecordDecl *RD,
6542 const CodeGen::CodeGenModule &CGM,
6543 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006544 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006545 SmallStringEnc Enc;
6546 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006547 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006548 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006549 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006550 Enc += "b(";
6551 llvm::raw_svector_ostream OS(Enc);
6552 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006553 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006554 OS.flush();
6555 Enc += ':';
6556 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006557 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006558 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006559 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006560 Enc += ')';
6561 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006562 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006563 }
6564 return true;
6565}
6566
6567/// Appends structure and union types to Enc and adds encoding to cache.
6568/// Recursively calls appendType (via extractFieldType) for each field.
6569/// Union types have their fields ordered according to the ABI.
6570static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6571 const CodeGen::CodeGenModule &CGM,
6572 TypeStringCache &TSC, const IdentifierInfo *ID) {
6573 // Append the cached TypeString if we have one.
6574 StringRef TypeString = TSC.lookupStr(ID);
6575 if (!TypeString.empty()) {
6576 Enc += TypeString;
6577 return true;
6578 }
6579
6580 // Start to emit an incomplete TypeString.
6581 size_t Start = Enc.size();
6582 Enc += (RT->isUnionType()? 'u' : 's');
6583 Enc += '(';
6584 if (ID)
6585 Enc += ID->getName();
6586 Enc += "){";
6587
6588 // We collect all encoded fields and order as necessary.
6589 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006590 const RecordDecl *RD = RT->getDecl()->getDefinition();
6591 if (RD && !RD->field_empty()) {
6592 // An incomplete TypeString stub is placed in the cache for this RecordType
6593 // so that recursive calls to this RecordType will use it whilst building a
6594 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006595 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006596 std::string StubEnc(Enc.substr(Start).str());
6597 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6598 TSC.addIncomplete(ID, std::move(StubEnc));
6599 if (!extractFieldType(FE, RD, CGM, TSC)) {
6600 (void) TSC.removeIncomplete(ID);
6601 return false;
6602 }
6603 IsRecursive = TSC.removeIncomplete(ID);
6604 // The ABI requires unions to be sorted but not structures.
6605 // See FieldEncoding::operator< for sort algorithm.
6606 if (RT->isUnionType())
6607 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006608 // We can now complete the TypeString.
6609 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006610 for (unsigned I = 0; I != E; ++I) {
6611 if (I)
6612 Enc += ',';
6613 Enc += FE[I].str();
6614 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006615 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006616 Enc += '}';
6617 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6618 return true;
6619}
6620
6621/// Appends enum types to Enc and adds the encoding to the cache.
6622static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6623 TypeStringCache &TSC,
6624 const IdentifierInfo *ID) {
6625 // Append the cached TypeString if we have one.
6626 StringRef TypeString = TSC.lookupStr(ID);
6627 if (!TypeString.empty()) {
6628 Enc += TypeString;
6629 return true;
6630 }
6631
6632 size_t Start = Enc.size();
6633 Enc += "e(";
6634 if (ID)
6635 Enc += ID->getName();
6636 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006637
6638 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006639 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006640 SmallVector<FieldEncoding, 16> FE;
6641 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6642 ++I) {
6643 SmallStringEnc EnumEnc;
6644 EnumEnc += "m(";
6645 EnumEnc += I->getName();
6646 EnumEnc += "){";
6647 I->getInitVal().toString(EnumEnc);
6648 EnumEnc += '}';
6649 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6650 }
6651 std::sort(FE.begin(), FE.end());
6652 unsigned E = FE.size();
6653 for (unsigned I = 0; I != E; ++I) {
6654 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006655 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006656 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006657 }
6658 }
6659 Enc += '}';
6660 TSC.addIfComplete(ID, Enc.substr(Start), false);
6661 return true;
6662}
6663
6664/// Appends type's qualifier to Enc.
6665/// This is done prior to appending the type's encoding.
6666static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6667 // Qualifiers are emitted in alphabetical order.
6668 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6669 int Lookup = 0;
6670 if (QT.isConstQualified())
6671 Lookup += 1<<0;
6672 if (QT.isRestrictQualified())
6673 Lookup += 1<<1;
6674 if (QT.isVolatileQualified())
6675 Lookup += 1<<2;
6676 Enc += Table[Lookup];
6677}
6678
6679/// Appends built-in types to Enc.
6680static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6681 const char *EncType;
6682 switch (BT->getKind()) {
6683 case BuiltinType::Void:
6684 EncType = "0";
6685 break;
6686 case BuiltinType::Bool:
6687 EncType = "b";
6688 break;
6689 case BuiltinType::Char_U:
6690 EncType = "uc";
6691 break;
6692 case BuiltinType::UChar:
6693 EncType = "uc";
6694 break;
6695 case BuiltinType::SChar:
6696 EncType = "sc";
6697 break;
6698 case BuiltinType::UShort:
6699 EncType = "us";
6700 break;
6701 case BuiltinType::Short:
6702 EncType = "ss";
6703 break;
6704 case BuiltinType::UInt:
6705 EncType = "ui";
6706 break;
6707 case BuiltinType::Int:
6708 EncType = "si";
6709 break;
6710 case BuiltinType::ULong:
6711 EncType = "ul";
6712 break;
6713 case BuiltinType::Long:
6714 EncType = "sl";
6715 break;
6716 case BuiltinType::ULongLong:
6717 EncType = "ull";
6718 break;
6719 case BuiltinType::LongLong:
6720 EncType = "sll";
6721 break;
6722 case BuiltinType::Float:
6723 EncType = "ft";
6724 break;
6725 case BuiltinType::Double:
6726 EncType = "d";
6727 break;
6728 case BuiltinType::LongDouble:
6729 EncType = "ld";
6730 break;
6731 default:
6732 return false;
6733 }
6734 Enc += EncType;
6735 return true;
6736}
6737
6738/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6739static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6740 const CodeGen::CodeGenModule &CGM,
6741 TypeStringCache &TSC) {
6742 Enc += "p(";
6743 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6744 return false;
6745 Enc += ')';
6746 return true;
6747}
6748
6749/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006750static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6751 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006752 const CodeGen::CodeGenModule &CGM,
6753 TypeStringCache &TSC, StringRef NoSizeEnc) {
6754 if (AT->getSizeModifier() != ArrayType::Normal)
6755 return false;
6756 Enc += "a(";
6757 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6758 CAT->getSize().toStringUnsigned(Enc);
6759 else
6760 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6761 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006762 // The Qualifiers should be attached to the type rather than the array.
6763 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006764 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6765 return false;
6766 Enc += ')';
6767 return true;
6768}
6769
6770/// Appends a function encoding to Enc, calling appendType for the return type
6771/// and the arguments.
6772static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6773 const CodeGen::CodeGenModule &CGM,
6774 TypeStringCache &TSC) {
6775 Enc += "f{";
6776 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6777 return false;
6778 Enc += "}(";
6779 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6780 // N.B. we are only interested in the adjusted param types.
6781 auto I = FPT->param_type_begin();
6782 auto E = FPT->param_type_end();
6783 if (I != E) {
6784 do {
6785 if (!appendType(Enc, *I, CGM, TSC))
6786 return false;
6787 ++I;
6788 if (I != E)
6789 Enc += ',';
6790 } while (I != E);
6791 if (FPT->isVariadic())
6792 Enc += ",va";
6793 } else {
6794 if (FPT->isVariadic())
6795 Enc += "va";
6796 else
6797 Enc += '0';
6798 }
6799 }
6800 Enc += ')';
6801 return true;
6802}
6803
6804/// Handles the type's qualifier before dispatching a call to handle specific
6805/// type encodings.
6806static bool appendType(SmallStringEnc &Enc, QualType QType,
6807 const CodeGen::CodeGenModule &CGM,
6808 TypeStringCache &TSC) {
6809
6810 QualType QT = QType.getCanonicalType();
6811
Robert Lytton6adb20f2014-06-05 09:06:21 +00006812 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
6813 // The Qualifiers should be attached to the type rather than the array.
6814 // Thus we don't call appendQualifier() here.
6815 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
6816
Robert Lytton844aeeb2014-05-02 09:33:20 +00006817 appendQualifier(Enc, QT);
6818
6819 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
6820 return appendBuiltinType(Enc, BT);
6821
Robert Lytton844aeeb2014-05-02 09:33:20 +00006822 if (const PointerType *PT = QT->getAs<PointerType>())
6823 return appendPointerType(Enc, PT, CGM, TSC);
6824
6825 if (const EnumType *ET = QT->getAs<EnumType>())
6826 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
6827
6828 if (const RecordType *RT = QT->getAsStructureType())
6829 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6830
6831 if (const RecordType *RT = QT->getAsUnionType())
6832 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
6833
6834 if (const FunctionType *FT = QT->getAs<FunctionType>())
6835 return appendFunctionType(Enc, FT, CGM, TSC);
6836
6837 return false;
6838}
6839
6840static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6841 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
6842 if (!D)
6843 return false;
6844
6845 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6846 if (FD->getLanguageLinkage() != CLanguageLinkage)
6847 return false;
6848 return appendType(Enc, FD->getType(), CGM, TSC);
6849 }
6850
6851 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6852 if (VD->getLanguageLinkage() != CLanguageLinkage)
6853 return false;
6854 QualType QT = VD->getType().getCanonicalType();
6855 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
6856 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006857 // The Qualifiers should be attached to the type rather than the array.
6858 // Thus we don't call appendQualifier() here.
6859 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00006860 }
6861 return appendType(Enc, QT, CGM, TSC);
6862 }
6863 return false;
6864}
6865
6866
Robert Lytton0e076492013-08-13 09:43:10 +00006867//===----------------------------------------------------------------------===//
6868// Driver code
6869//===----------------------------------------------------------------------===//
6870
Chris Lattner2b037972010-07-29 02:01:43 +00006871const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006872 if (TheTargetCodeGenInfo)
6873 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006874
John McCallc8e01702013-04-16 22:48:15 +00006875 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00006876 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00006877 default:
Chris Lattner2b037972010-07-29 02:01:43 +00006878 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00006879
Derek Schuff09338a22012-09-06 17:37:28 +00006880 case llvm::Triple::le32:
6881 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00006882 case llvm::Triple::mips:
6883 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006884 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
6885
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00006886 case llvm::Triple::mips64:
6887 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006888 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
6889
Tim Northover25e8a672014-05-24 12:51:25 +00006890 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00006891 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00006892 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006893 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00006894 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00006895
Tim Northover573cbee2014-05-24 12:52:07 +00006896 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00006897 }
6898
Daniel Dunbard59655c2009-09-12 00:59:49 +00006899 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006900 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00006901 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00006902 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006903 {
6904 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00006905 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006906 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00006907 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00006908 (CodeGenOpts.FloatABI != "soft" &&
6909 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006910 Kind = ARMABIInfo::AAPCS_VFP;
6911
Derek Schuffa2020962012-10-16 22:30:41 +00006912 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00006913 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00006914 return *(TheTargetCodeGenInfo =
6915 new NaClARMTargetCodeGenInfo(Types, Kind));
6916 default:
6917 return *(TheTargetCodeGenInfo =
6918 new ARMTargetCodeGenInfo(Types, Kind));
6919 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00006920 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00006921
John McCallea8d8bb2010-03-11 00:10:12 +00006922 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00006923 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00006924 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00006925 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00006926 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006927 if (getTarget().getABI() == "elfv2")
6928 Kind = PPC64_SVR4_ABIInfo::ELFv2;
6929
Ulrich Weigandb7122372014-07-21 00:48:09 +00006930 return *(TheTargetCodeGenInfo =
6931 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6932 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00006933 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00006934 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00006935 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00006936 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00006937 if (getTarget().getABI() == "elfv1")
6938 Kind = PPC64_SVR4_ABIInfo::ELFv1;
6939
Ulrich Weigandb7122372014-07-21 00:48:09 +00006940 return *(TheTargetCodeGenInfo =
6941 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
6942 }
John McCallea8d8bb2010-03-11 00:10:12 +00006943
Peter Collingbournec947aae2012-05-20 23:28:41 +00006944 case llvm::Triple::nvptx:
6945 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00006946 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006947
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006948 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00006949 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00006950
Ulrich Weigand47445072013-05-06 16:26:41 +00006951 case llvm::Triple::systemz:
6952 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
6953
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006954 case llvm::Triple::tce:
6955 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
6956
Eli Friedman33465822011-07-08 23:31:17 +00006957 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00006958 bool IsDarwinVectorABI = Triple.isOSDarwin();
6959 bool IsSmallStructInRegABI =
6960 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasool377066a2014-03-27 22:50:18 +00006961 bool IsWin32FloatStructABI = Triple.isWindowsMSVCEnvironment();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00006962
John McCall1fe2a8c2013-06-18 02:46:29 +00006963 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00006964 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006965 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00006966 IsDarwinVectorABI, IsSmallStructInRegABI,
6967 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00006968 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00006969 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006970 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00006971 new X86_32TargetCodeGenInfo(Types,
6972 IsDarwinVectorABI, IsSmallStructInRegABI,
6973 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00006974 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006975 }
Eli Friedman33465822011-07-08 23:31:17 +00006976 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006977
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006978 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00006979 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006980
Chris Lattner04dc9572010-08-31 16:44:54 +00006981 switch (Triple.getOS()) {
6982 case llvm::Triple::Win32:
Chris Lattner04dc9572010-08-31 16:44:54 +00006983 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Benderskyd7c92032012-12-04 18:38:10 +00006984 case llvm::Triple::NaCl:
John McCallc8e01702013-04-16 22:48:15 +00006985 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
6986 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006987 default:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006988 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
6989 HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00006990 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00006991 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00006992 case llvm::Triple::hexagon:
6993 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006994 case llvm::Triple::sparcv9:
6995 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00006996 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006997 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00006998 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006999}