blob: fff67675c8e71a0f914d8814ea41c2720599bfec [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028
29#include <algorithm> // std::sort
30
Anton Korobeynikov244360d2009-06-05 22:08:42 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall943fae92010-05-27 06:19:26 +000034static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
35 llvm::Value *Array,
36 llvm::Value *Value,
37 unsigned FirstIndex,
38 unsigned LastIndex) {
39 // Alternatively, we could emit this as a loop in the source.
40 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
41 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
42 Builder.CreateStore(Value, Cell);
43 }
44}
45
John McCalla1dee5302010-08-22 10:59:02 +000046static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000047 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000048 T->isMemberFunctionPointerType();
49}
50
Anton Korobeynikov244360d2009-06-05 22:08:42 +000051ABIInfo::~ABIInfo() {}
52
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000053static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000054 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000055 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
56 if (!RD)
57 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000058 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000059}
60
61static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000062 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000063 const RecordType *RT = T->getAs<RecordType>();
64 if (!RT)
65 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000066 return getRecordArgABI(RT, CXXABI);
67}
68
Reid Klecknerb1be6832014-11-15 01:41:41 +000069/// Pass transparent unions as if they were the type of the first element. Sema
70/// should ensure that all elements of the union have the same "machine type".
71static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
72 if (const RecordType *UT = Ty->getAsUnionType()) {
73 const RecordDecl *UD = UT->getDecl();
74 if (UD->hasAttr<TransparentUnionAttr>()) {
75 assert(!UD->field_empty() && "sema created an empty transparent union");
76 return UD->field_begin()->getType();
77 }
78 }
79 return Ty;
80}
81
Mark Lacey3825e832013-10-06 01:33:34 +000082CGCXXABI &ABIInfo::getCXXABI() const {
83 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000084}
85
Chris Lattner2b037972010-07-29 02:01:43 +000086ASTContext &ABIInfo::getContext() const {
87 return CGT.getContext();
88}
89
90llvm::LLVMContext &ABIInfo::getVMContext() const {
91 return CGT.getLLVMContext();
92}
93
Micah Villmowdd31ca12012-10-08 16:25:52 +000094const llvm::DataLayout &ABIInfo::getDataLayout() const {
95 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +000096}
97
John McCallc8e01702013-04-16 22:48:15 +000098const TargetInfo &ABIInfo::getTarget() const {
99 return CGT.getTarget();
100}
Chris Lattner2b037972010-07-29 02:01:43 +0000101
Reid Klecknere9f6a712014-10-31 17:10:41 +0000102bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
103 return false;
104}
105
106bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
107 uint64_t Members) const {
108 return false;
109}
110
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000111void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000112 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000113 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000114 switch (TheKind) {
115 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000116 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000117 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000118 Ty->print(OS);
119 else
120 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000121 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000122 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000123 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000124 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000125 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000126 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000127 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000128 case InAlloca:
129 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
130 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000131 case Indirect:
Daniel Dunbar557893d2010-04-21 19:10:51 +0000132 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000133 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000134 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000135 break;
136 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000137 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000138 break;
139 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000140 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000141}
142
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000143TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
144
John McCall3480ef22011-08-30 01:42:09 +0000145// If someone can figure out a general rule for this, that would be great.
146// It's probably just doomed to be platform-dependent, though.
147unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
148 // Verified for:
149 // x86-64 FreeBSD, Linux, Darwin
150 // x86-32 FreeBSD, Linux, Darwin
151 // PowerPC Linux, Darwin
152 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000153 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000154 return 32;
155}
156
John McCalla729c622012-02-17 03:33:10 +0000157bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
158 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000159 // The following conventions are known to require this to be false:
160 // x86_stdcall
161 // MIPS
162 // For everything else, we just prefer false unless we opt out.
163 return false;
164}
165
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000166void
167TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
168 llvm::SmallString<24> &Opt) const {
169 // This assumes the user is passing a library name like "rt" instead of a
170 // filename like "librt.a/so", and that they don't care whether it's static or
171 // dynamic.
172 Opt = "-l";
173 Opt += Lib;
174}
175
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000176static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000177
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000178/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000179/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000180static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
181 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000182 if (FD->isUnnamedBitfield())
183 return true;
184
185 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186
Eli Friedman0b3f2012011-11-18 03:47:20 +0000187 // Constant arrays of empty records count as empty, strip them off.
188 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000189 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000190 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
191 if (AT->getSize() == 0)
192 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000193 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000194 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000195
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000196 const RecordType *RT = FT->getAs<RecordType>();
197 if (!RT)
198 return false;
199
200 // C++ record fields are never empty, at least in the Itanium ABI.
201 //
202 // FIXME: We should use a predicate for whether this behavior is true in the
203 // current ABI.
204 if (isa<CXXRecordDecl>(RT->getDecl()))
205 return false;
206
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000207 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000208}
209
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000210/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000211/// fields. Note that a structure with a flexible array member is not
212/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000213static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000214 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 if (!RT)
216 return 0;
217 const RecordDecl *RD = RT->getDecl();
218 if (RD->hasFlexibleArrayMember())
219 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000220
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000221 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000222 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000223 for (const auto &I : CXXRD->bases())
224 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000225 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000226
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000227 for (const auto *I : RD->fields())
228 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000229 return false;
230 return true;
231}
232
233/// isSingleElementStruct - Determine if a structure is a "single
234/// element struct", i.e. it has exactly one non-empty field or
235/// exactly one field which is itself a single element
236/// struct. Structures with flexible array members are never
237/// considered single element structs.
238///
239/// \return The field declaration for the single non-empty field, if
240/// it exists.
241static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
242 const RecordType *RT = T->getAsStructureType();
243 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000244 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000245
246 const RecordDecl *RD = RT->getDecl();
247 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000248 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000249
Craig Topper8a13c412014-05-21 05:09:00 +0000250 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000251
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000252 // If this is a C++ record, check the bases first.
253 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000254 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000255 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000256 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000257 continue;
258
259 // If we already found an element then this isn't a single-element struct.
260 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000261 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000262
263 // If this is non-empty and not a single element struct, the composite
264 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000265 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000266 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000267 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000268 }
269 }
270
271 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000272 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000273 QualType FT = FD->getType();
274
275 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000276 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000277 continue;
278
279 // If we already found an element then this isn't a single-element
280 // struct.
281 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000282 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000283
284 // Treat single element arrays as the element.
285 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
286 if (AT->getSize().getZExtValue() != 1)
287 break;
288 FT = AT->getElementType();
289 }
290
John McCalla1dee5302010-08-22 10:59:02 +0000291 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000292 Found = FT.getTypePtr();
293 } else {
294 Found = isSingleElementStruct(FT, Context);
295 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000296 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000297 }
298 }
299
Eli Friedmanee945342011-11-18 01:25:50 +0000300 // We don't consider a struct a single-element struct if it has
301 // padding beyond the element type.
302 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000303 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000304
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000305 return Found;
306}
307
308static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000309 // Treat complex types as the element type.
310 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
311 Ty = CTy->getElementType();
312
313 // Check for a type which we know has a simple scalar argument-passing
314 // convention without any padding. (We're specifically looking for 32
315 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000316 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000317 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000318 return false;
319
320 uint64_t Size = Context.getTypeSize(Ty);
321 return Size == 32 || Size == 64;
322}
323
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000324/// canExpandIndirectArgument - Test whether an argument type which is to be
325/// passed indirectly (on the stack) would have the equivalent layout if it was
326/// expanded into separate arguments. If so, we prefer to do the latter to avoid
327/// inhibiting optimizations.
328///
329// FIXME: This predicate is missing many cases, currently it just follows
330// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
331// should probably make this smarter, or better yet make the LLVM backend
332// capable of handling it.
333static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
334 // We can only expand structure types.
335 const RecordType *RT = Ty->getAs<RecordType>();
336 if (!RT)
337 return false;
338
339 // We can only expand (C) structures.
340 //
341 // FIXME: This needs to be generalized to handle classes as well.
342 const RecordDecl *RD = RT->getDecl();
343 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
344 return false;
345
Eli Friedmane5c85622011-11-18 01:32:26 +0000346 uint64_t Size = 0;
347
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000348 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000349 if (!is32Or64BitBasicType(FD->getType(), Context))
350 return false;
351
352 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
353 // how to expand them yet, and the predicate for telling if a bitfield still
354 // counts as "basic" is more complicated than what we were doing previously.
355 if (FD->isBitField())
356 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000357
358 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359 }
360
Eli Friedmane5c85622011-11-18 01:32:26 +0000361 // Make sure there are not any holes in the struct.
362 if (Size != Context.getTypeSize(Ty))
363 return false;
364
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000365 return true;
366}
367
368namespace {
369/// DefaultABIInfo - The default implementation for ABI specific
370/// details. This implementation provides information which results in
371/// self-consistent and sensible LLVM IR generation, but does not
372/// conform to any particular ABI.
373class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000374public:
375 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000376
Chris Lattner458b2aa2010-07-29 02:16:43 +0000377 ABIArgInfo classifyReturnType(QualType RetTy) const;
378 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000379
Craig Topper4f12f102014-03-12 06:41:41 +0000380 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000381 if (!getCXXABI().classifyReturnType(FI))
382 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000383 for (auto &I : FI.arguments())
384 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000385 }
386
Craig Topper4f12f102014-03-12 06:41:41 +0000387 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
388 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000389};
390
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000391class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
392public:
Chris Lattner2b037972010-07-29 02:01:43 +0000393 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
394 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000395};
396
397llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
398 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000399 return nullptr;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000400}
401
Chris Lattner458b2aa2010-07-29 02:16:43 +0000402ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000403 if (isAggregateTypeForABI(Ty))
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000404 return ABIArgInfo::getIndirect(0);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000405
Chris Lattner9723d6c2010-03-11 18:19:55 +0000406 // Treat an enum type as its underlying type.
407 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
408 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000409
Chris Lattner9723d6c2010-03-11 18:19:55 +0000410 return (Ty->isPromotableIntegerType() ?
411 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000412}
413
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000414ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
415 if (RetTy->isVoidType())
416 return ABIArgInfo::getIgnore();
417
418 if (isAggregateTypeForABI(RetTy))
419 return ABIArgInfo::getIndirect(0);
420
421 // Treat an enum type as its underlying type.
422 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
423 RetTy = EnumTy->getDecl()->getIntegerType();
424
425 return (RetTy->isPromotableIntegerType() ?
426 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
427}
428
Derek Schuff09338a22012-09-06 17:37:28 +0000429//===----------------------------------------------------------------------===//
430// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000431//
432// This is a simplified version of the x86_32 ABI. Arguments and return values
433// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000434//===----------------------------------------------------------------------===//
435
436class PNaClABIInfo : public ABIInfo {
437 public:
438 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
439
440 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000441 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000442
Craig Topper4f12f102014-03-12 06:41:41 +0000443 void computeInfo(CGFunctionInfo &FI) const override;
444 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
445 CodeGenFunction &CGF) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000446};
447
448class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
449 public:
450 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
451 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
452};
453
454void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000455 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000456 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
457
Reid Kleckner40ca9132014-05-13 22:05:45 +0000458 for (auto &I : FI.arguments())
459 I.info = classifyArgumentType(I.type);
460}
Derek Schuff09338a22012-09-06 17:37:28 +0000461
462llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
463 CodeGenFunction &CGF) const {
Craig Topper8a13c412014-05-21 05:09:00 +0000464 return nullptr;
Derek Schuff09338a22012-09-06 17:37:28 +0000465}
466
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000467/// \brief Classify argument of given type \p Ty.
468ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000469 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000470 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000471 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff09338a22012-09-06 17:37:28 +0000472 return ABIArgInfo::getIndirect(0);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000473 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
474 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000475 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000476 } else if (Ty->isFloatingType()) {
477 // Floating-point types don't go inreg.
478 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000479 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000480
481 return (Ty->isPromotableIntegerType() ?
482 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000483}
484
485ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
486 if (RetTy->isVoidType())
487 return ABIArgInfo::getIgnore();
488
Eli Benderskye20dad62013-04-04 22:49:35 +0000489 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000490 if (isAggregateTypeForABI(RetTy))
491 return ABIArgInfo::getIndirect(0);
492
493 // Treat an enum type as its underlying type.
494 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
495 RetTy = EnumTy->getDecl()->getIntegerType();
496
497 return (RetTy->isPromotableIntegerType() ?
498 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
499}
500
Chad Rosier651c1832013-03-25 21:00:27 +0000501/// IsX86_MMXType - Return true if this is an MMX type.
502bool IsX86_MMXType(llvm::Type *IRType) {
503 // 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 +0000504 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
505 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
506 IRType->getScalarSizeInBits() != 64;
507}
508
Jay Foad7c57be32011-07-11 09:56:20 +0000509static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000510 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000511 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000512 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
513 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
514 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000515 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000516 }
517
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000518 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000519 }
520
521 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000522 return Ty;
523}
524
Reid Kleckner80944df2014-10-31 22:00:51 +0000525/// Returns true if this type can be passed in SSE registers with the
526/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
527static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
528 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
529 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
530 return true;
531 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
532 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
533 // registers specially.
534 unsigned VecSize = Context.getTypeSize(VT);
535 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
536 return true;
537 }
538 return false;
539}
540
541/// Returns true if this aggregate is small enough to be passed in SSE registers
542/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
543static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
544 return NumMembers <= 4;
545}
546
Chris Lattner0cf24192010-06-28 20:05:43 +0000547//===----------------------------------------------------------------------===//
548// X86-32 ABI Implementation
549//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000550
Reid Kleckner661f35b2014-01-18 01:12:41 +0000551/// \brief Similar to llvm::CCState, but for Clang.
552struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000553 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000554
555 unsigned CC;
556 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000557 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000558};
559
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000560/// X86_32ABIInfo - The X86-32 ABI information.
561class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000562 enum Class {
563 Integer,
564 Float
565 };
566
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000567 static const unsigned MinABIStackAlignInBytes = 4;
568
David Chisnallde3a0692009-08-17 23:08:21 +0000569 bool IsDarwinVectorABI;
570 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000571 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000572 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000573
574 static bool isRegisterSize(unsigned Size) {
575 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
576 }
577
Reid Kleckner80944df2014-10-31 22:00:51 +0000578 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
579 // FIXME: Assumes vectorcall is in use.
580 return isX86VectorTypeForVectorCall(getContext(), Ty);
581 }
582
583 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
584 uint64_t NumMembers) const override {
585 // FIXME: Assumes vectorcall is in use.
586 return isX86VectorCallAggregateSmallEnough(NumMembers);
587 }
588
Reid Kleckner40ca9132014-05-13 22:05:45 +0000589 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000590
Daniel Dunbar557893d2010-04-21 19:10:51 +0000591 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
592 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000593 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
594
595 ABIArgInfo getIndirectReturnResult(CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000596
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000597 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000598 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000599
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000600 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000601 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000602 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
603 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000604
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000605 /// \brief Rewrite the function info so that all memory arguments use
606 /// inalloca.
607 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
608
609 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
610 unsigned &StackOffset, ABIArgInfo &Info,
611 QualType Type) const;
612
Rafael Espindola75419dc2012-07-23 23:30:29 +0000613public:
614
Craig Topper4f12f102014-03-12 06:41:41 +0000615 void computeInfo(CGFunctionInfo &FI) const override;
616 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
617 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000618
Chad Rosier651c1832013-03-25 21:00:27 +0000619 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000620 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000621 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000622 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000623};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000624
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000625class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
626public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000627 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000628 bool d, bool p, bool w, unsigned r)
629 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000630
John McCall1fe2a8c2013-06-18 02:46:29 +0000631 static bool isStructReturnInRegABI(
632 const llvm::Triple &Triple, const CodeGenOptions &Opts);
633
Charles Davis4ea31ab2010-02-13 15:54:06 +0000634 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000635 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000636
Craig Topper4f12f102014-03-12 06:41:41 +0000637 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000638 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000639 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000640 return 4;
641 }
642
643 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000644 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000645
Jay Foad7c57be32011-07-11 09:56:20 +0000646 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000647 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000648 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000649 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
650 }
651
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000652 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
653 std::string &Constraints,
654 std::vector<llvm::Type *> &ResultRegTypes,
655 std::vector<llvm::Type *> &ResultTruncRegTypes,
656 std::vector<LValue> &ResultRegDests,
657 std::string &AsmString,
658 unsigned NumOutputs) const override;
659
Craig Topper4f12f102014-03-12 06:41:41 +0000660 llvm::Constant *
661 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000662 unsigned Sig = (0xeb << 0) | // jmp rel8
663 (0x06 << 8) | // .+0x08
664 ('F' << 16) |
665 ('T' << 24);
666 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
667 }
668
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000669};
670
671}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000672
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000673/// Rewrite input constraint references after adding some output constraints.
674/// In the case where there is one output and one input and we add one output,
675/// we need to replace all operand references greater than or equal to 1:
676/// mov $0, $1
677/// mov eax, $1
678/// The result will be:
679/// mov $0, $2
680/// mov eax, $2
681static void rewriteInputConstraintReferences(unsigned FirstIn,
682 unsigned NumNewOuts,
683 std::string &AsmString) {
684 std::string Buf;
685 llvm::raw_string_ostream OS(Buf);
686 size_t Pos = 0;
687 while (Pos < AsmString.size()) {
688 size_t DollarStart = AsmString.find('$', Pos);
689 if (DollarStart == std::string::npos)
690 DollarStart = AsmString.size();
691 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
692 if (DollarEnd == std::string::npos)
693 DollarEnd = AsmString.size();
694 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
695 Pos = DollarEnd;
696 size_t NumDollars = DollarEnd - DollarStart;
697 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
698 // We have an operand reference.
699 size_t DigitStart = Pos;
700 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
701 if (DigitEnd == std::string::npos)
702 DigitEnd = AsmString.size();
703 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
704 unsigned OperandIndex;
705 if (!OperandStr.getAsInteger(10, OperandIndex)) {
706 if (OperandIndex >= FirstIn)
707 OperandIndex += NumNewOuts;
708 OS << OperandIndex;
709 } else {
710 OS << OperandStr;
711 }
712 Pos = DigitEnd;
713 }
714 }
715 AsmString = std::move(OS.str());
716}
717
718/// Add output constraints for EAX:EDX because they are return registers.
719void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
720 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
721 std::vector<llvm::Type *> &ResultRegTypes,
722 std::vector<llvm::Type *> &ResultTruncRegTypes,
723 std::vector<LValue> &ResultRegDests, std::string &AsmString,
724 unsigned NumOutputs) const {
725 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
726
727 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
728 // larger.
729 if (!Constraints.empty())
730 Constraints += ',';
731 if (RetWidth <= 32) {
732 Constraints += "={eax}";
733 ResultRegTypes.push_back(CGF.Int32Ty);
734 } else {
735 // Use the 'A' constraint for EAX:EDX.
736 Constraints += "=A";
737 ResultRegTypes.push_back(CGF.Int64Ty);
738 }
739
740 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
741 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
742 ResultTruncRegTypes.push_back(CoerceTy);
743
744 // Coerce the integer by bitcasting the return slot pointer.
745 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
746 CoerceTy->getPointerTo()));
747 ResultRegDests.push_back(ReturnSlot);
748
749 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
750}
751
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000752/// shouldReturnTypeInRegister - Determine if the given type should be
753/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000754bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
755 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000756 uint64_t Size = Context.getTypeSize(Ty);
757
758 // Type must be register sized.
759 if (!isRegisterSize(Size))
760 return false;
761
762 if (Ty->isVectorType()) {
763 // 64- and 128- bit vectors inside structures are not returned in
764 // registers.
765 if (Size == 64 || Size == 128)
766 return false;
767
768 return true;
769 }
770
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000771 // If this is a builtin, pointer, enum, complex type, member pointer, or
772 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000773 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +0000774 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000775 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000776 return true;
777
778 // Arrays are treated like records.
779 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +0000780 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000781
782 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000783 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000784 if (!RT) return false;
785
Anders Carlsson40446e82010-01-27 03:25:19 +0000786 // FIXME: Traverse bases here too.
787
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000788 // Structure types are passed in register if all fields would be
789 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000790 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000791 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000792 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000793 continue;
794
795 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000796 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000797 return false;
798 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000799 return true;
800}
801
Reid Kleckner661f35b2014-01-18 01:12:41 +0000802ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(CCState &State) const {
803 // If the return value is indirect, then the hidden argument is consuming one
804 // integer register.
805 if (State.FreeRegs) {
806 --State.FreeRegs;
807 return ABIArgInfo::getIndirectInReg(/*Align=*/0, /*ByVal=*/false);
808 }
809 return ABIArgInfo::getIndirect(/*Align=*/0, /*ByVal=*/false);
810}
811
Reid Kleckner40ca9132014-05-13 22:05:45 +0000812ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000813 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000814 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000815
Reid Kleckner80944df2014-10-31 22:00:51 +0000816 const Type *Base = nullptr;
817 uint64_t NumElts = 0;
818 if (State.CC == llvm::CallingConv::X86_VectorCall &&
819 isHomogeneousAggregate(RetTy, Base, NumElts)) {
820 // The LLVM struct type for such an aggregate should lower properly.
821 return ABIArgInfo::getDirect();
822 }
823
Chris Lattner458b2aa2010-07-29 02:16:43 +0000824 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000825 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +0000826 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000827 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000828
829 // 128-bit vectors are a special case; they are returned in
830 // registers and we need to make sure to pick a type the LLVM
831 // backend will like.
832 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000833 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +0000834 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000835
836 // Always return in register if it fits in a general purpose
837 // register, or if it is 64 bits and has a single element.
838 if ((Size == 8 || Size == 16 || Size == 32) ||
839 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000840 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +0000841 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000842
Reid Kleckner661f35b2014-01-18 01:12:41 +0000843 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000844 }
845
846 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +0000847 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000848
John McCalla1dee5302010-08-22 10:59:02 +0000849 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +0000850 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +0000851 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000852 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000853 return getIndirectReturnResult(State);
Anders Carlsson5789c492009-10-20 22:07:59 +0000854 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000855
David Chisnallde3a0692009-08-17 23:08:21 +0000856 // If specified, structs and unions are always indirect.
857 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Reid Kleckner661f35b2014-01-18 01:12:41 +0000858 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000859
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000860 // Small structures which are register sized are generally returned
861 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +0000862 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +0000863 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +0000864
865 // As a special-case, if the struct is a "single-element" struct, and
866 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +0000867 // floating-point register. (MSVC does not apply this special case.)
868 // We apply a similar transformation for pointer types to improve the
869 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +0000870 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000871 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +0000872 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +0000873 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
874
875 // FIXME: We should be able to narrow this integer in cases with dead
876 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000877 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000878 }
879
Reid Kleckner661f35b2014-01-18 01:12:41 +0000880 return getIndirectReturnResult(State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000881 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000882
Chris Lattner458b2aa2010-07-29 02:16:43 +0000883 // Treat an enum type as its underlying type.
884 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
885 RetTy = EnumTy->getDecl()->getIntegerType();
886
887 return (RetTy->isPromotableIntegerType() ?
888 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000889}
890
Eli Friedman7919bea2012-06-05 19:40:46 +0000891static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
892 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
893}
894
Daniel Dunbared23de32010-09-16 20:42:00 +0000895static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
896 const RecordType *RT = Ty->getAs<RecordType>();
897 if (!RT)
898 return 0;
899 const RecordDecl *RD = RT->getDecl();
900
901 // If this is a C++ record, check the bases first.
902 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000903 for (const auto &I : CXXRD->bases())
904 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +0000905 return false;
906
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000907 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +0000908 QualType FT = i->getType();
909
Eli Friedman7919bea2012-06-05 19:40:46 +0000910 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +0000911 return true;
912
913 if (isRecordWithSSEVectorType(Context, FT))
914 return true;
915 }
916
917 return false;
918}
919
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000920unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
921 unsigned Align) const {
922 // Otherwise, if the alignment is less than or equal to the minimum ABI
923 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000924 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000925 return 0; // Use default alignment.
926
927 // On non-Darwin, the stack type alignment is always 4.
928 if (!IsDarwinVectorABI) {
929 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000930 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000931 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000932
Daniel Dunbared23de32010-09-16 20:42:00 +0000933 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +0000934 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
935 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +0000936 return 16;
937
938 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000939}
940
Rafael Espindola703c47f2012-10-19 05:04:37 +0000941ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +0000942 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +0000943 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +0000944 if (State.FreeRegs) {
945 --State.FreeRegs; // Non-byval indirects just use one pointer.
Rafael Espindola703c47f2012-10-19 05:04:37 +0000946 return ABIArgInfo::getIndirectInReg(0, false);
947 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000948 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +0000949 }
Daniel Dunbar53fac692010-04-21 19:49:55 +0000950
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000951 // Compute the byval alignment.
952 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
953 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
954 if (StackAlign == 0)
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000955 return ABIArgInfo::getIndirect(4, /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000956
957 // If the stack alignment is less than the type alignment, realign the
958 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000959 bool Realign = TypeAlign > StackAlign;
960 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +0000961}
962
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000963X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
964 const Type *T = isSingleElementStruct(Ty, getContext());
965 if (!T)
966 T = Ty.getTypePtr();
967
968 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
969 BuiltinType::Kind K = BT->getKind();
970 if (K == BuiltinType::Float || K == BuiltinType::Double)
971 return Float;
972 }
973 return Integer;
974}
975
Reid Kleckner661f35b2014-01-18 01:12:41 +0000976bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
977 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +0000978 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000979 Class C = classify(Ty);
980 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +0000981 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000982
Rafael Espindola077dd592012-10-24 01:58:58 +0000983 unsigned Size = getContext().getTypeSize(Ty);
984 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +0000985
986 if (SizeInRegs == 0)
987 return false;
988
Reid Kleckner661f35b2014-01-18 01:12:41 +0000989 if (SizeInRegs > State.FreeRegs) {
990 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +0000991 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000992 }
Rafael Espindola703c47f2012-10-19 05:04:37 +0000993
Reid Kleckner661f35b2014-01-18 01:12:41 +0000994 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +0000995
Reid Kleckner80944df2014-10-31 22:00:51 +0000996 if (State.CC == llvm::CallingConv::X86_FastCall ||
997 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +0000998 if (Size > 32)
999 return false;
1000
1001 if (Ty->isIntegralOrEnumerationType())
1002 return true;
1003
1004 if (Ty->isPointerType())
1005 return true;
1006
1007 if (Ty->isReferenceType())
1008 return true;
1009
Reid Kleckner661f35b2014-01-18 01:12:41 +00001010 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001011 NeedsPadding = true;
1012
Rafael Espindola077dd592012-10-24 01:58:58 +00001013 return false;
1014 }
1015
Rafael Espindola703c47f2012-10-19 05:04:37 +00001016 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001017}
1018
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001019ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1020 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001021 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001022
Reid Klecknerb1be6832014-11-15 01:41:41 +00001023 Ty = useFirstFieldIfTransparentUnion(Ty);
1024
Reid Kleckner80944df2014-10-31 22:00:51 +00001025 // Check with the C++ ABI first.
1026 const RecordType *RT = Ty->getAs<RecordType>();
1027 if (RT) {
1028 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1029 if (RAA == CGCXXABI::RAA_Indirect) {
1030 return getIndirectResult(Ty, false, State);
1031 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1032 // The field index doesn't matter, we'll fix it up later.
1033 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1034 }
1035 }
1036
1037 // vectorcall adds the concept of a homogenous vector aggregate, similar
1038 // to other targets.
1039 const Type *Base = nullptr;
1040 uint64_t NumElts = 0;
1041 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1042 isHomogeneousAggregate(Ty, Base, NumElts)) {
1043 if (State.FreeSSERegs >= NumElts) {
1044 State.FreeSSERegs -= NumElts;
1045 if (Ty->isBuiltinType() || Ty->isVectorType())
1046 return ABIArgInfo::getDirect();
1047 return ABIArgInfo::getExpand();
1048 }
1049 return getIndirectResult(Ty, /*ByVal=*/false, State);
1050 }
1051
1052 if (isAggregateTypeForABI(Ty)) {
1053 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001054 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001055 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001056 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001057
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001058 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001059 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001060 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001061 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001062
Eli Friedman9f061a32011-11-18 00:28:11 +00001063 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001064 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001065 return ABIArgInfo::getIgnore();
1066
Rafael Espindolafad28de2012-10-24 01:59:00 +00001067 llvm::LLVMContext &LLVMContext = getVMContext();
1068 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1069 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001070 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001071 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001072 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001073 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1074 return ABIArgInfo::getDirectInReg(Result);
1075 }
Craig Topper8a13c412014-05-21 05:09:00 +00001076 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001077
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001078 // Expand small (<= 128-bit) record types when we know that the stack layout
1079 // of those arguments will match the struct. This is important because the
1080 // LLVM backend isn't smart enough to remove byval, which inhibits many
1081 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001082 if (getContext().getTypeSize(Ty) <= 4*32 &&
1083 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001084 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001085 State.CC == llvm::CallingConv::X86_FastCall ||
1086 State.CC == llvm::CallingConv::X86_VectorCall,
1087 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001088
Reid Kleckner661f35b2014-01-18 01:12:41 +00001089 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001090 }
1091
Chris Lattnerd774ae92010-08-26 20:05:13 +00001092 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001093 // On Darwin, some vectors are passed in memory, we handle this by passing
1094 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001095 if (IsDarwinVectorABI) {
1096 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001097 if ((Size == 8 || Size == 16 || Size == 32) ||
1098 (Size == 64 && VT->getNumElements() == 1))
1099 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1100 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001101 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001102
Chad Rosier651c1832013-03-25 21:00:27 +00001103 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1104 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001105
Chris Lattnerd774ae92010-08-26 20:05:13 +00001106 return ABIArgInfo::getDirect();
1107 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001108
1109
Chris Lattner458b2aa2010-07-29 02:16:43 +00001110 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1111 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001112
Rafael Espindolafad28de2012-10-24 01:59:00 +00001113 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001114 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001115
1116 if (Ty->isPromotableIntegerType()) {
1117 if (InReg)
1118 return ABIArgInfo::getExtendInReg();
1119 return ABIArgInfo::getExtend();
1120 }
1121 if (InReg)
1122 return ABIArgInfo::getDirectInReg();
1123 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001124}
1125
Rafael Espindolaa6472962012-07-24 00:01:07 +00001126void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001127 CCState State(FI.getCallingConvention());
1128 if (State.CC == llvm::CallingConv::X86_FastCall)
1129 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001130 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1131 State.FreeRegs = 2;
1132 State.FreeSSERegs = 6;
1133 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001134 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001135 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001136 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001137
Reid Kleckner677539d2014-07-10 01:58:55 +00001138 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001139 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001140 } else if (FI.getReturnInfo().isIndirect()) {
1141 // The C++ ABI is not aware of register usage, so we have to check if the
1142 // return value was sret and put it in a register ourselves if appropriate.
1143 if (State.FreeRegs) {
1144 --State.FreeRegs; // The sret parameter consumes a register.
1145 FI.getReturnInfo().setInReg(true);
1146 }
1147 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001148
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001149 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001150 for (auto &I : FI.arguments()) {
1151 I.info = classifyArgumentType(I.type, State);
1152 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001153 }
1154
1155 // If we needed to use inalloca for any argument, do a second pass and rewrite
1156 // all the memory arguments to use inalloca.
1157 if (UsedInAlloca)
1158 rewriteWithInAlloca(FI);
1159}
1160
1161void
1162X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1163 unsigned &StackOffset,
1164 ABIArgInfo &Info, QualType Type) const {
Reid Klecknerd378a712014-04-10 19:09:43 +00001165 assert(StackOffset % 4U == 0 && "unaligned inalloca struct");
1166 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1167 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1168 StackOffset += getContext().getTypeSizeInChars(Type).getQuantity();
1169
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001170 // Insert padding bytes to respect alignment. For x86_32, each argument is 4
1171 // byte aligned.
Reid Klecknerd378a712014-04-10 19:09:43 +00001172 if (StackOffset % 4U) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001173 unsigned OldOffset = StackOffset;
Reid Klecknerd378a712014-04-10 19:09:43 +00001174 StackOffset = llvm::RoundUpToAlignment(StackOffset, 4U);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001175 unsigned NumBytes = StackOffset - OldOffset;
1176 assert(NumBytes);
1177 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1178 Ty = llvm::ArrayType::get(Ty, NumBytes);
1179 FrameFields.push_back(Ty);
1180 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001181}
1182
Reid Kleckner852361d2014-07-26 00:12:26 +00001183static bool isArgInAlloca(const ABIArgInfo &Info) {
1184 // Leave ignored and inreg arguments alone.
1185 switch (Info.getKind()) {
1186 case ABIArgInfo::InAlloca:
1187 return true;
1188 case ABIArgInfo::Indirect:
1189 assert(Info.getIndirectByVal());
1190 return true;
1191 case ABIArgInfo::Ignore:
1192 return false;
1193 case ABIArgInfo::Direct:
1194 case ABIArgInfo::Extend:
1195 case ABIArgInfo::Expand:
1196 if (Info.getInReg())
1197 return false;
1198 return true;
1199 }
1200 llvm_unreachable("invalid enum");
1201}
1202
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001203void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1204 assert(IsWin32StructABI && "inalloca only supported on win32");
1205
1206 // Build a packed struct type for all of the arguments in memory.
1207 SmallVector<llvm::Type *, 6> FrameFields;
1208
1209 unsigned StackOffset = 0;
Reid Kleckner852361d2014-07-26 00:12:26 +00001210 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1211
1212 // Put 'this' into the struct before 'sret', if necessary.
1213 bool IsThisCall =
1214 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1215 ABIArgInfo &Ret = FI.getReturnInfo();
1216 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1217 isArgInAlloca(I->info)) {
1218 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1219 ++I;
1220 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001221
1222 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001223 if (Ret.isIndirect() && !Ret.getInReg()) {
1224 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1225 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001226 // On Windows, the hidden sret parameter is always returned in eax.
1227 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001228 }
1229
1230 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001231 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001232 ++I;
1233
1234 // Put arguments passed in memory into the struct.
1235 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001236 if (isArgInAlloca(I->info))
1237 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001238 }
1239
1240 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1241 /*isPacked=*/true));
Rafael Espindolaa6472962012-07-24 00:01:07 +00001242}
1243
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001244llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1245 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00001246 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247
1248 CGBuilderTy &Builder = CGF.Builder;
1249 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1250 "ap");
1251 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001252
1253 // Compute if the address needs to be aligned
1254 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1255 Align = getTypeStackAlignInBytes(Ty, Align);
1256 Align = std::max(Align, 4U);
1257 if (Align > 4) {
1258 // addr = (addr + align - 1) & -align;
1259 llvm::Value *Offset =
1260 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1261 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1262 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1263 CGF.Int32Ty);
1264 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1265 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1266 Addr->getType(),
1267 "ap.cur.aligned");
1268 }
1269
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001270 llvm::Type *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001271 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001272 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1273
1274 uint64_t Offset =
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001275 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001276 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00001277 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278 "ap.next");
1279 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1280
1281 return AddrTyped;
1282}
1283
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001284bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1285 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1286 assert(Triple.getArch() == llvm::Triple::x86);
1287
1288 switch (Opts.getStructReturnConvention()) {
1289 case CodeGenOptions::SRCK_Default:
1290 break;
1291 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1292 return false;
1293 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1294 return true;
1295 }
1296
1297 if (Triple.isOSDarwin())
1298 return true;
1299
1300 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001301 case llvm::Triple::DragonFly:
1302 case llvm::Triple::FreeBSD:
1303 case llvm::Triple::OpenBSD:
1304 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001305 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001306 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001307 default:
1308 return false;
1309 }
1310}
1311
Charles Davis4ea31ab2010-02-13 15:54:06 +00001312void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1313 llvm::GlobalValue *GV,
1314 CodeGen::CodeGenModule &CGM) const {
1315 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1316 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1317 // Get the LLVM function.
1318 llvm::Function *Fn = cast<llvm::Function>(GV);
1319
1320 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001321 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001322 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001323 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1324 llvm::AttributeSet::get(CGM.getLLVMContext(),
1325 llvm::AttributeSet::FunctionIndex,
1326 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001327 }
1328 }
1329}
1330
John McCallbeec5a02010-03-06 00:35:14 +00001331bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1332 CodeGen::CodeGenFunction &CGF,
1333 llvm::Value *Address) const {
1334 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001335
Chris Lattnerece04092012-02-07 00:39:47 +00001336 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001337
John McCallbeec5a02010-03-06 00:35:14 +00001338 // 0-7 are the eight integer registers; the order is different
1339 // on Darwin (for EH), but the range is the same.
1340 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001341 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001342
John McCallc8e01702013-04-16 22:48:15 +00001343 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001344 // 12-16 are st(0..4). Not sure why we stop at 4.
1345 // These have size 16, which is sizeof(long double) on
1346 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001347 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001348 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001349
John McCallbeec5a02010-03-06 00:35:14 +00001350 } else {
1351 // 9 is %eflags, which doesn't get a size on Darwin for some
1352 // reason.
1353 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1354
1355 // 11-16 are st(0..5). Not sure why we stop at 5.
1356 // These have size 12, which is sizeof(long double) on
1357 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001358 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001359 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1360 }
John McCallbeec5a02010-03-06 00:35:14 +00001361
1362 return false;
1363}
1364
Chris Lattner0cf24192010-06-28 20:05:43 +00001365//===----------------------------------------------------------------------===//
1366// X86-64 ABI Implementation
1367//===----------------------------------------------------------------------===//
1368
1369
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001370namespace {
1371/// X86_64ABIInfo - The X86_64 ABI information.
1372class X86_64ABIInfo : public ABIInfo {
1373 enum Class {
1374 Integer = 0,
1375 SSE,
1376 SSEUp,
1377 X87,
1378 X87Up,
1379 ComplexX87,
1380 NoClass,
1381 Memory
1382 };
1383
1384 /// merge - Implement the X86_64 ABI merging algorithm.
1385 ///
1386 /// Merge an accumulating classification \arg Accum with a field
1387 /// classification \arg Field.
1388 ///
1389 /// \param Accum - The accumulating classification. This should
1390 /// always be either NoClass or the result of a previous merge
1391 /// call. In addition, this should never be Memory (the caller
1392 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001393 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001394
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001395 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1396 ///
1397 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1398 /// final MEMORY or SSE classes when necessary.
1399 ///
1400 /// \param AggregateSize - The size of the current aggregate in
1401 /// the classification process.
1402 ///
1403 /// \param Lo - The classification for the parts of the type
1404 /// residing in the low word of the containing object.
1405 ///
1406 /// \param Hi - The classification for the parts of the type
1407 /// residing in the higher words of the containing object.
1408 ///
1409 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1410
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001411 /// classify - Determine the x86_64 register classes in which the
1412 /// given type T should be passed.
1413 ///
1414 /// \param Lo - The classification for the parts of the type
1415 /// residing in the low word of the containing object.
1416 ///
1417 /// \param Hi - The classification for the parts of the type
1418 /// residing in the high word of the containing object.
1419 ///
1420 /// \param OffsetBase - The bit offset of this type in the
1421 /// containing object. Some parameters are classified different
1422 /// depending on whether they straddle an eightbyte boundary.
1423 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001424 /// \param isNamedArg - Whether the argument in question is a "named"
1425 /// argument, as used in AMD64-ABI 3.5.7.
1426 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001427 /// If a word is unused its result will be NoClass; if a type should
1428 /// be passed in Memory then at least the classification of \arg Lo
1429 /// will be Memory.
1430 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001431 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001432 ///
1433 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1434 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001435 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1436 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001437
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001438 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001439 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1440 unsigned IROffset, QualType SourceTy,
1441 unsigned SourceOffset) const;
1442 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1443 unsigned IROffset, QualType SourceTy,
1444 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001445
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001446 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001447 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001448 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001449
1450 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001451 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001452 ///
1453 /// \param freeIntRegs - The number of free integer registers remaining
1454 /// available.
1455 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001456
Chris Lattner458b2aa2010-07-29 02:16:43 +00001457 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001458
Bill Wendling5cd41c42010-10-18 03:41:31 +00001459 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001460 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001461 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001462 unsigned &neededSSE,
1463 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001464
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001465 bool IsIllegalVectorType(QualType Ty) const;
1466
John McCalle0fda732011-04-21 01:20:55 +00001467 /// The 0.98 ABI revision clarified a lot of ambiguities,
1468 /// unfortunately in ways that were not always consistent with
1469 /// certain previous compilers. In particular, platforms which
1470 /// required strict binary compatibility with older versions of GCC
1471 /// may need to exempt themselves.
1472 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001473 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001474 }
1475
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001476 bool HasAVX;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001477 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1478 // 64-bit hardware.
1479 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001480
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001481public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001482 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffc7dd7222012-10-11 15:52:22 +00001483 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff8a872f32012-10-11 18:21:13 +00001484 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001485 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001486
John McCalla729c622012-02-17 03:33:10 +00001487 bool isPassedUsingAVXType(QualType type) const {
1488 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001489 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001490 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1491 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001492 if (info.isDirect()) {
1493 llvm::Type *ty = info.getCoerceToType();
1494 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1495 return (vectorTy->getBitWidth() > 128);
1496 }
1497 return false;
1498 }
1499
Craig Topper4f12f102014-03-12 06:41:41 +00001500 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001501
Craig Topper4f12f102014-03-12 06:41:41 +00001502 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1503 CodeGenFunction &CGF) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001504};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001505
Chris Lattner04dc9572010-08-31 16:44:54 +00001506/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001507class WinX86_64ABIInfo : public ABIInfo {
1508
Reid Kleckner80944df2014-10-31 22:00:51 +00001509 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1510 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001511
Chris Lattner04dc9572010-08-31 16:44:54 +00001512public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001513 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1514
Craig Topper4f12f102014-03-12 06:41:41 +00001515 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001516
Craig Topper4f12f102014-03-12 06:41:41 +00001517 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1518 CodeGenFunction &CGF) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001519
1520 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1521 // FIXME: Assumes vectorcall is in use.
1522 return isX86VectorTypeForVectorCall(getContext(), Ty);
1523 }
1524
1525 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1526 uint64_t NumMembers) const override {
1527 // FIXME: Assumes vectorcall is in use.
1528 return isX86VectorCallAggregateSmallEnough(NumMembers);
1529 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001530};
1531
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001532class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001533 bool HasAVX;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001534public:
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001535 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Alexander Musman09184fe2014-09-30 05:29:28 +00001536 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {}
John McCallbeec5a02010-03-06 00:35:14 +00001537
John McCalla729c622012-02-17 03:33:10 +00001538 const X86_64ABIInfo &getABIInfo() const {
1539 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1540 }
1541
Craig Topper4f12f102014-03-12 06:41:41 +00001542 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001543 return 7;
1544 }
1545
1546 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001547 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001548 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001549
John McCall943fae92010-05-27 06:19:26 +00001550 // 0-15 are the 16 integer registers.
1551 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001552 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001553 return false;
1554 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001555
Jay Foad7c57be32011-07-11 09:56:20 +00001556 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001557 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001558 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001559 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1560 }
1561
John McCalla729c622012-02-17 03:33:10 +00001562 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001563 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001564 // The default CC on x86-64 sets %al to the number of SSA
1565 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001566 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001567 // that when AVX types are involved: the ABI explicitly states it is
1568 // undefined, and it doesn't work in practice because of how the ABI
1569 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001570 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001571 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001572 for (CallArgList::const_iterator
1573 it = args.begin(), ie = args.end(); it != ie; ++it) {
1574 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1575 HasAVXType = true;
1576 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001577 }
1578 }
John McCalla729c622012-02-17 03:33:10 +00001579
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001580 if (!HasAVXType)
1581 return true;
1582 }
John McCallcbc038a2011-09-21 08:08:30 +00001583
John McCalla729c622012-02-17 03:33:10 +00001584 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001585 }
1586
Craig Topper4f12f102014-03-12 06:41:41 +00001587 llvm::Constant *
1588 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001589 unsigned Sig = (0xeb << 0) | // jmp rel8
1590 (0x0a << 8) | // .+0x0c
1591 ('F' << 16) |
1592 ('T' << 24);
1593 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1594 }
1595
Alexander Musman09184fe2014-09-30 05:29:28 +00001596 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1597 return HasAVX ? 32 : 16;
1598 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001599};
1600
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001601static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1602 // If the argument does not end in .lib, automatically add the suffix. This
1603 // matches the behavior of MSVC.
1604 std::string ArgStr = Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001605 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001606 ArgStr += ".lib";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001607 return ArgStr;
1608}
1609
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001610class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1611public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001612 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1613 bool d, bool p, bool w, unsigned RegParms)
1614 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001615
1616 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001617 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001618 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001619 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001620 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001621
1622 void getDetectMismatchOption(llvm::StringRef Name,
1623 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001624 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001625 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001626 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001627};
1628
Chris Lattner04dc9572010-08-31 16:44:54 +00001629class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00001630 bool HasAVX;
Chris Lattner04dc9572010-08-31 16:44:54 +00001631public:
Alexander Musman09184fe2014-09-30 05:29:28 +00001632 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
1633 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)), HasAVX(HasAVX) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001634
Craig Topper4f12f102014-03-12 06:41:41 +00001635 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001636 return 7;
1637 }
1638
1639 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001640 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001641 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001642
Chris Lattner04dc9572010-08-31 16:44:54 +00001643 // 0-15 are the 16 integer registers.
1644 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001645 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001646 return false;
1647 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001648
1649 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001650 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001651 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001652 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001653 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001654
1655 void getDetectMismatchOption(llvm::StringRef Name,
1656 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001657 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001658 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001659 }
Alexander Musman09184fe2014-09-30 05:29:28 +00001660
1661 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
1662 return HasAVX ? 32 : 16;
1663 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001664};
1665
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001666}
1667
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001668void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1669 Class &Hi) const {
1670 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1671 //
1672 // (a) If one of the classes is Memory, the whole argument is passed in
1673 // memory.
1674 //
1675 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1676 // memory.
1677 //
1678 // (c) If the size of the aggregate exceeds two eightbytes and the first
1679 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1680 // argument is passed in memory. NOTE: This is necessary to keep the
1681 // ABI working for processors that don't support the __m256 type.
1682 //
1683 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1684 //
1685 // Some of these are enforced by the merging logic. Others can arise
1686 // only with unions; for example:
1687 // union { _Complex double; unsigned; }
1688 //
1689 // Note that clauses (b) and (c) were added in 0.98.
1690 //
1691 if (Hi == Memory)
1692 Lo = Memory;
1693 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1694 Lo = Memory;
1695 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1696 Lo = Memory;
1697 if (Hi == SSEUp && Lo != SSE)
1698 Hi = SSE;
1699}
1700
Chris Lattnerd776fb12010-06-28 21:43:59 +00001701X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001702 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1703 // classified recursively so that always two fields are
1704 // considered. The resulting class is calculated according to
1705 // the classes of the fields in the eightbyte:
1706 //
1707 // (a) If both classes are equal, this is the resulting class.
1708 //
1709 // (b) If one of the classes is NO_CLASS, the resulting class is
1710 // the other class.
1711 //
1712 // (c) If one of the classes is MEMORY, the result is the MEMORY
1713 // class.
1714 //
1715 // (d) If one of the classes is INTEGER, the result is the
1716 // INTEGER.
1717 //
1718 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1719 // MEMORY is used as class.
1720 //
1721 // (f) Otherwise class SSE is used.
1722
1723 // Accum should never be memory (we should have returned) or
1724 // ComplexX87 (because this cannot be passed in a structure).
1725 assert((Accum != Memory && Accum != ComplexX87) &&
1726 "Invalid accumulated classification during merge.");
1727 if (Accum == Field || Field == NoClass)
1728 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001729 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001730 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001731 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001732 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001733 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001734 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001735 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1736 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001737 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001738 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001739}
1740
Chris Lattner5c740f12010-06-30 19:14:05 +00001741void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00001742 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001743 // FIXME: This code can be simplified by introducing a simple value class for
1744 // Class pairs with appropriate constructor methods for the various
1745 // situations.
1746
1747 // FIXME: Some of the split computations are wrong; unaligned vectors
1748 // shouldn't be passed in registers for example, so there is no chance they
1749 // can straddle an eightbyte. Verify & simplify.
1750
1751 Lo = Hi = NoClass;
1752
1753 Class &Current = OffsetBase < 64 ? Lo : Hi;
1754 Current = Memory;
1755
John McCall9dd450b2009-09-21 23:43:11 +00001756 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001757 BuiltinType::Kind k = BT->getKind();
1758
1759 if (k == BuiltinType::Void) {
1760 Current = NoClass;
1761 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1762 Lo = Integer;
1763 Hi = Integer;
1764 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1765 Current = Integer;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001766 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1767 (k == BuiltinType::LongDouble &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001768 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001769 Current = SSE;
1770 } else if (k == BuiltinType::LongDouble) {
1771 Lo = X87;
1772 Hi = X87Up;
1773 }
1774 // FIXME: _Decimal32 and _Decimal64 are SSE.
1775 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001776 return;
1777 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001778
Chris Lattnerd776fb12010-06-28 21:43:59 +00001779 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001780 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00001781 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00001782 return;
1783 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001784
Chris Lattnerd776fb12010-06-28 21:43:59 +00001785 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001786 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00001787 return;
1788 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001789
Chris Lattnerd776fb12010-06-28 21:43:59 +00001790 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001791 if (Ty->isMemberFunctionPointerType()) {
1792 if (Has64BitPointers) {
1793 // If Has64BitPointers, this is an {i64, i64}, so classify both
1794 // Lo and Hi now.
1795 Lo = Hi = Integer;
1796 } else {
1797 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
1798 // straddles an eightbyte boundary, Hi should be classified as well.
1799 uint64_t EB_FuncPtr = (OffsetBase) / 64;
1800 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
1801 if (EB_FuncPtr != EB_ThisAdj) {
1802 Lo = Hi = Integer;
1803 } else {
1804 Current = Integer;
1805 }
1806 }
1807 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00001808 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00001809 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001810 return;
1811 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001812
Chris Lattnerd776fb12010-06-28 21:43:59 +00001813 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001814 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001815 if (Size == 32) {
1816 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1817 // float> as integer.
1818 Current = Integer;
1819
1820 // If this type crosses an eightbyte boundary, it should be
1821 // split.
1822 uint64_t EB_Real = (OffsetBase) / 64;
1823 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1824 if (EB_Real != EB_Imag)
1825 Hi = Lo;
1826 } else if (Size == 64) {
1827 // gcc passes <1 x double> in memory. :(
1828 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1829 return;
1830
1831 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00001832 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00001833 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1834 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1835 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001836 Current = Integer;
1837 else
1838 Current = SSE;
1839
1840 // If this type crosses an eightbyte boundary, it should be
1841 // split.
1842 if (OffsetBase && OffsetBase != 64)
1843 Hi = Lo;
Eli Friedman96fd2642013-06-12 00:13:45 +00001844 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001845 // Arguments of 256-bits are split into four eightbyte chunks. The
1846 // least significant one belongs to class SSE and all the others to class
1847 // SSEUP. The original Lo and Hi design considers that types can't be
1848 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1849 // This design isn't correct for 256-bits, but since there're no cases
1850 // where the upper parts would need to be inspected, avoid adding
1851 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00001852 //
1853 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1854 // registers if they are "named", i.e. not part of the "..." of a
1855 // variadic function.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001856 Lo = SSE;
1857 Hi = SSEUp;
1858 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00001859 return;
1860 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001861
Chris Lattnerd776fb12010-06-28 21:43:59 +00001862 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001863 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001864
Chris Lattner2b037972010-07-29 02:01:43 +00001865 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00001866 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001867 if (Size <= 64)
1868 Current = Integer;
1869 else if (Size <= 128)
1870 Lo = Hi = Integer;
Chris Lattner2b037972010-07-29 02:01:43 +00001871 } else if (ET == getContext().FloatTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001872 Current = SSE;
Derek Schuff57b7e8f2012-10-11 16:55:58 +00001873 else if (ET == getContext().DoubleTy ||
1874 (ET == getContext().LongDoubleTy &&
Cameron Esfahani556d91e2013-09-14 01:09:11 +00001875 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001876 Lo = Hi = SSE;
Chris Lattner2b037972010-07-29 02:01:43 +00001877 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001878 Current = ComplexX87;
1879
1880 // If this complex type crosses an eightbyte boundary then it
1881 // should be split.
1882 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00001883 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884 if (Hi == NoClass && EB_Real != EB_Imag)
1885 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001886
Chris Lattnerd776fb12010-06-28 21:43:59 +00001887 return;
1888 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001889
Chris Lattner2b037972010-07-29 02:01:43 +00001890 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001891 // Arrays are treated like structures.
1892
Chris Lattner2b037972010-07-29 02:01:43 +00001893 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001894
1895 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001896 // than four eightbytes, ..., it has class MEMORY.
1897 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001898 return;
1899
1900 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1901 // fields, it has class MEMORY.
1902 //
1903 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00001904 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001905 return;
1906
1907 // Otherwise implement simplified merge. We could be smarter about
1908 // this, but it isn't worth it and would be harder to verify.
1909 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00001910 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001911 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00001912
1913 // The only case a 256-bit wide vector could be used is when the array
1914 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1915 // to work for sizes wider than 128, early check and fallback to memory.
1916 if (Size > 128 && EltSize != 256)
1917 return;
1918
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001919 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1920 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00001921 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001922 Lo = merge(Lo, FieldLo);
1923 Hi = merge(Hi, FieldHi);
1924 if (Lo == Memory || Hi == Memory)
1925 break;
1926 }
1927
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001928 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001929 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00001930 return;
1931 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001932
Chris Lattnerd776fb12010-06-28 21:43:59 +00001933 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00001934 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001935
1936 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001937 // than four eightbytes, ..., it has class MEMORY.
1938 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001939 return;
1940
Anders Carlsson20759ad2009-09-16 15:53:40 +00001941 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1942 // copy constructor or a non-trivial destructor, it is passed by invisible
1943 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00001944 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00001945 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001946
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001947 const RecordDecl *RD = RT->getDecl();
1948
1949 // Assume variable sized types are passed in memory.
1950 if (RD->hasFlexibleArrayMember())
1951 return;
1952
Chris Lattner2b037972010-07-29 02:01:43 +00001953 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001954
1955 // Reset Lo class, this will be recomputed.
1956 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001957
1958 // If this is a C++ record, classify the bases first.
1959 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001960 for (const auto &I : CXXRD->bases()) {
1961 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001962 "Unexpected base class!");
1963 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00001964 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001965
1966 // Classify this field.
1967 //
1968 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1969 // single eightbyte, each is classified separately. Each eightbyte gets
1970 // initialized to class NO_CLASS.
1971 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00001972 uint64_t Offset =
1973 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00001974 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00001975 Lo = merge(Lo, FieldLo);
1976 Hi = merge(Hi, FieldHi);
1977 if (Lo == Memory || Hi == Memory)
1978 break;
1979 }
1980 }
1981
1982 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001983 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00001984 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001985 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001986 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1987 bool BitField = i->isBitField();
1988
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001989 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1990 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001991 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00001992 // The only case a 256-bit wide vector could be used is when the struct
1993 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1994 // to work for sizes wider than 128, early check and fallback to memory.
1995 //
1996 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1997 Lo = Memory;
1998 return;
1999 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002000 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002001 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002002 Lo = Memory;
2003 return;
2004 }
2005
2006 // Classify this field.
2007 //
2008 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2009 // exceeds a single eightbyte, each is classified
2010 // separately. Each eightbyte gets initialized to class
2011 // NO_CLASS.
2012 Class FieldLo, FieldHi;
2013
2014 // Bit-fields require special handling, they do not force the
2015 // structure to be passed in memory even if unaligned, and
2016 // therefore they can straddle an eightbyte.
2017 if (BitField) {
2018 // Ignore padding bit-fields.
2019 if (i->isUnnamedBitfield())
2020 continue;
2021
2022 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002023 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002024
2025 uint64_t EB_Lo = Offset / 64;
2026 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002027
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002028 if (EB_Lo) {
2029 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2030 FieldLo = NoClass;
2031 FieldHi = Integer;
2032 } else {
2033 FieldLo = Integer;
2034 FieldHi = EB_Hi ? Integer : NoClass;
2035 }
2036 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002037 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002038 Lo = merge(Lo, FieldLo);
2039 Hi = merge(Hi, FieldHi);
2040 if (Lo == Memory || Hi == Memory)
2041 break;
2042 }
2043
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002044 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002045 }
2046}
2047
Chris Lattner22a931e2010-06-29 06:01:59 +00002048ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002049 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2050 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002051 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002052 // Treat an enum type as its underlying type.
2053 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2054 Ty = EnumTy->getDecl()->getIntegerType();
2055
2056 return (Ty->isPromotableIntegerType() ?
2057 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2058 }
2059
2060 return ABIArgInfo::getIndirect(0);
2061}
2062
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002063bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2064 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2065 uint64_t Size = getContext().getTypeSize(VecTy);
2066 unsigned LargestVector = HasAVX ? 256 : 128;
2067 if (Size <= 64 || Size > LargestVector)
2068 return true;
2069 }
2070
2071 return false;
2072}
2073
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002074ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2075 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2077 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002078 //
2079 // This assumption is optimistic, as there could be free registers available
2080 // when we need to pass this argument in memory, and LLVM could try to pass
2081 // the argument in the free register. This does not seem to happen currently,
2082 // but this code would be much safer if we could mark the argument with
2083 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002084 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002085 // Treat an enum type as its underlying type.
2086 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2087 Ty = EnumTy->getDecl()->getIntegerType();
2088
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002089 return (Ty->isPromotableIntegerType() ?
2090 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002091 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002092
Mark Lacey3825e832013-10-06 01:33:34 +00002093 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002094 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002095
Chris Lattner44c2b902011-05-22 23:21:23 +00002096 // Compute the byval alignment. We specify the alignment of the byval in all
2097 // cases so that the mid-level optimizer knows the alignment of the byval.
2098 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002099
2100 // Attempt to avoid passing indirect results using byval when possible. This
2101 // is important for good codegen.
2102 //
2103 // We do this by coercing the value into a scalar type which the backend can
2104 // handle naturally (i.e., without using byval).
2105 //
2106 // For simplicity, we currently only do this when we have exhausted all of the
2107 // free integer registers. Doing this when there are free integer registers
2108 // would require more care, as we would have to ensure that the coerced value
2109 // did not claim the unused register. That would require either reording the
2110 // arguments to the function (so that any subsequent inreg values came first),
2111 // or only doing this optimization when there were no following arguments that
2112 // might be inreg.
2113 //
2114 // We currently expect it to be rare (particularly in well written code) for
2115 // arguments to be passed on the stack when there are still free integer
2116 // registers available (this would typically imply large structs being passed
2117 // by value), so this seems like a fair tradeoff for now.
2118 //
2119 // We can revisit this if the backend grows support for 'onstack' parameter
2120 // attributes. See PR12193.
2121 if (freeIntRegs == 0) {
2122 uint64_t Size = getContext().getTypeSize(Ty);
2123
2124 // If this type fits in an eightbyte, coerce it into the matching integral
2125 // type, which will end up on the stack (with alignment 8).
2126 if (Align == 8 && Size <= 64)
2127 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2128 Size));
2129 }
2130
Chris Lattner44c2b902011-05-22 23:21:23 +00002131 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002132}
2133
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002134/// GetByteVectorType - The ABI specifies that a value should be passed in an
2135/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner4200fe42010-07-29 04:56:46 +00002136/// vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002137llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002138 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002139
Chris Lattner9fa15c32010-07-29 05:02:29 +00002140 // Wrapper structs that just contain vectors are passed just like vectors,
2141 // strip them off if present.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002142 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner9fa15c32010-07-29 05:02:29 +00002143 while (STy && STy->getNumElements() == 1) {
2144 IRType = STy->getElementType(0);
2145 STy = dyn_cast<llvm::StructType>(IRType);
2146 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002147
Bruno Cardoso Lopes129b4cc2011-07-08 22:57:35 +00002148 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002149 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
2150 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002151 unsigned BitWidth = VT->getBitWidth();
Tanya Lattner71f1b2d2011-11-28 23:18:11 +00002152 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner4200fe42010-07-29 04:56:46 +00002153 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
2154 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
2155 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
2156 EltTy->isIntegerTy(128)))
2157 return VT;
2158 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002159
Chris Lattner4200fe42010-07-29 04:56:46 +00002160 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
2161}
2162
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002163/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2164/// is known to either be off the end of the specified type or being in
2165/// alignment padding. The user type specified is known to be at most 128 bits
2166/// in size, and have passed through X86_64ABIInfo::classify with a successful
2167/// classification that put one of the two halves in the INTEGER class.
2168///
2169/// It is conservatively correct to return false.
2170static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2171 unsigned EndBit, ASTContext &Context) {
2172 // If the bytes being queried are off the end of the type, there is no user
2173 // data hiding here. This handles analysis of builtins, vectors and other
2174 // types that don't contain interesting padding.
2175 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2176 if (TySize <= StartBit)
2177 return true;
2178
Chris Lattner98076a22010-07-29 07:43:55 +00002179 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2180 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2181 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2182
2183 // Check each element to see if the element overlaps with the queried range.
2184 for (unsigned i = 0; i != NumElts; ++i) {
2185 // If the element is after the span we care about, then we're done..
2186 unsigned EltOffset = i*EltSize;
2187 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002188
Chris Lattner98076a22010-07-29 07:43:55 +00002189 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2190 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2191 EndBit-EltOffset, Context))
2192 return false;
2193 }
2194 // If it overlaps no elements, then it is safe to process as padding.
2195 return true;
2196 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002197
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002198 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2199 const RecordDecl *RD = RT->getDecl();
2200 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002201
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002202 // If this is a C++ record, check the bases first.
2203 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002204 for (const auto &I : CXXRD->bases()) {
2205 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002206 "Unexpected base class!");
2207 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002208 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002209
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002210 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002211 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002212 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002213
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002214 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002215 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002216 EndBit-BaseOffset, Context))
2217 return false;
2218 }
2219 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002220
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002221 // Verify that no field has data that overlaps the region of interest. Yes
2222 // this could be sped up a lot by being smarter about queried fields,
2223 // however we're only looking at structs up to 16 bytes, so we don't care
2224 // much.
2225 unsigned idx = 0;
2226 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2227 i != e; ++i, ++idx) {
2228 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002229
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002230 // If we found a field after the region we care about, then we're done.
2231 if (FieldOffset >= EndBit) break;
2232
2233 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2234 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2235 Context))
2236 return false;
2237 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002238
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002239 // If nothing in this record overlapped the area of interest, then we're
2240 // clean.
2241 return true;
2242 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002243
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002244 return false;
2245}
2246
Chris Lattnere556a712010-07-29 18:39:32 +00002247/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2248/// float member at the specified offset. For example, {int,{float}} has a
2249/// float at offset 4. It is conservatively correct for this routine to return
2250/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002251static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002252 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002253 // Base case if we find a float.
2254 if (IROffset == 0 && IRType->isFloatTy())
2255 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002256
Chris Lattnere556a712010-07-29 18:39:32 +00002257 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002258 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002259 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2260 unsigned Elt = SL->getElementContainingOffset(IROffset);
2261 IROffset -= SL->getElementOffset(Elt);
2262 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2263 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002264
Chris Lattnere556a712010-07-29 18:39:32 +00002265 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002266 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2267 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002268 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2269 IROffset -= IROffset/EltSize*EltSize;
2270 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2271 }
2272
2273 return false;
2274}
2275
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002276
2277/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2278/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002279llvm::Type *X86_64ABIInfo::
2280GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002281 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002282 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002283 // pass as float if the last 4 bytes is just padding. This happens for
2284 // structs that contain 3 floats.
2285 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2286 SourceOffset*8+64, getContext()))
2287 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002288
Chris Lattnere556a712010-07-29 18:39:32 +00002289 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2290 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2291 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002292 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2293 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002294 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002295
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002296 return llvm::Type::getDoubleTy(getVMContext());
2297}
2298
2299
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002300/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2301/// an 8-byte GPR. This means that we either have a scalar or we are talking
2302/// about the high or low part of an up-to-16-byte struct. This routine picks
2303/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002304/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2305/// etc).
2306///
2307/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2308/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2309/// the 8-byte value references. PrefType may be null.
2310///
Alp Toker9907f082014-07-09 14:06:35 +00002311/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002312/// an offset into this that we're processing (which is always either 0 or 8).
2313///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002314llvm::Type *X86_64ABIInfo::
2315GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002316 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002317 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2318 // returning an 8-byte unit starting with it. See if we can safely use it.
2319 if (IROffset == 0) {
2320 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002321 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2322 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002323 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002324
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002325 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2326 // goodness in the source type is just tail padding. This is allowed to
2327 // kick in for struct {double,int} on the int, but not on
2328 // struct{double,int,int} because we wouldn't return the second int. We
2329 // have to do this analysis on the source type because we can't depend on
2330 // unions being lowered a specific way etc.
2331 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002332 IRType->isIntegerTy(32) ||
2333 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2334 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2335 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002336
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002337 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2338 SourceOffset*8+64, getContext()))
2339 return IRType;
2340 }
2341 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002342
Chris Lattner2192fe52011-07-18 04:24:23 +00002343 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002344 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002345 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002346 if (IROffset < SL->getSizeInBytes()) {
2347 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2348 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002349
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002350 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2351 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002352 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002353 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002354
Chris Lattner2192fe52011-07-18 04:24:23 +00002355 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002356 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002357 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002358 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002359 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2360 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002361 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002362
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002363 // Okay, we don't have any better idea of what to pass, so we pass this in an
2364 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002365 unsigned TySizeInBytes =
2366 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002367
Chris Lattner3f763422010-07-29 17:34:39 +00002368 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002369
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002370 // It is always safe to classify this as an integer type up to i64 that
2371 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002372 return llvm::IntegerType::get(getVMContext(),
2373 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002374}
2375
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002376
2377/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2378/// be used as elements of a two register pair to pass or return, return a
2379/// first class aggregate to represent them. For example, if the low part of
2380/// a by-value argument should be passed as i32* and the high part as float,
2381/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002382static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002383GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002384 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002385 // In order to correctly satisfy the ABI, we need to the high part to start
2386 // at offset 8. If the high and low parts we inferred are both 4-byte types
2387 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2388 // the second element at offset 8. Check for this:
2389 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2390 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002391 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002392 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002393
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002394 // To handle this, we have to increase the size of the low part so that the
2395 // second element will start at an 8 byte offset. We can't increase the size
2396 // of the second element because it might make us access off the end of the
2397 // struct.
2398 if (HiStart != 8) {
2399 // There are only two sorts of types the ABI generation code can produce for
2400 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2401 // Promote these to a larger type.
2402 if (Lo->isFloatTy())
2403 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2404 else {
2405 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2406 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2407 }
2408 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002409
Reid Kleckneree7cf842014-12-01 22:02:27 +00002410 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002411
2412
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002413 // Verify that the second element is at an 8-byte offset.
2414 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2415 "Invalid x86-64 argument pair!");
2416 return Result;
2417}
2418
Chris Lattner31faff52010-07-28 23:06:14 +00002419ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002420classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002421 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2422 // classification algorithm.
2423 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002424 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002425
2426 // Check some invariants.
2427 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002428 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2429
Craig Topper8a13c412014-05-21 05:09:00 +00002430 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002431 switch (Lo) {
2432 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002433 if (Hi == NoClass)
2434 return ABIArgInfo::getIgnore();
2435 // If the low part is just padding, it takes no register, leave ResType
2436 // null.
2437 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2438 "Unknown missing lo part");
2439 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002440
2441 case SSEUp:
2442 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002443 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002444
2445 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2446 // hidden argument.
2447 case Memory:
2448 return getIndirectReturnResult(RetTy);
2449
2450 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2451 // available register of the sequence %rax, %rdx is used.
2452 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002453 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002454
Chris Lattner1f3a0632010-07-29 21:42:50 +00002455 // If we have a sign or zero extended integer, make sure to return Extend
2456 // so that the parameter gets the right LLVM IR attributes.
2457 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2458 // Treat an enum type as its underlying type.
2459 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2460 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002461
Chris Lattner1f3a0632010-07-29 21:42:50 +00002462 if (RetTy->isIntegralOrEnumerationType() &&
2463 RetTy->isPromotableIntegerType())
2464 return ABIArgInfo::getExtend();
2465 }
Chris Lattner31faff52010-07-28 23:06:14 +00002466 break;
2467
2468 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2469 // available SSE register of the sequence %xmm0, %xmm1 is used.
2470 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002471 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002472 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002473
2474 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2475 // returned on the X87 stack in %st0 as 80-bit x87 number.
2476 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002477 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002478 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002479
2480 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2481 // part of the value is returned in %st0 and the imaginary part in
2482 // %st1.
2483 case ComplexX87:
2484 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002485 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002486 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002487 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002488 break;
2489 }
2490
Craig Topper8a13c412014-05-21 05:09:00 +00002491 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002492 switch (Hi) {
2493 // Memory was handled previously and X87 should
2494 // never occur as a hi class.
2495 case Memory:
2496 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002497 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002498
2499 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002500 case NoClass:
2501 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002502
Chris Lattner52b3c132010-09-01 00:20:33 +00002503 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002504 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002505 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2506 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002507 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002508 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002509 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002510 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2511 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002512 break;
2513
2514 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002515 // is passed in the next available eightbyte chunk if the last used
2516 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002517 //
Chris Lattner57540c52011-04-15 05:22:18 +00002518 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002519 case SSEUp:
2520 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002521 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002522 break;
2523
2524 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2525 // returned together with the previous X87 value in %st0.
2526 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002527 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002528 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002529 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002530 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002531 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002532 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002533 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2534 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002535 }
Chris Lattner31faff52010-07-28 23:06:14 +00002536 break;
2537 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002538
Chris Lattner52b3c132010-09-01 00:20:33 +00002539 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002540 // known to pass in the high eightbyte of the result. We do this by forming a
2541 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002542 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002543 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002544
Chris Lattner1f3a0632010-07-29 21:42:50 +00002545 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002546}
2547
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002548ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002549 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2550 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002551 const
2552{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002553 Ty = useFirstFieldIfTransparentUnion(Ty);
2554
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002556 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002557
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558 // Check some invariants.
2559 // FIXME: Enforce these by construction.
2560 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002561 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2562
2563 neededInt = 0;
2564 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002565 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566 switch (Lo) {
2567 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002568 if (Hi == NoClass)
2569 return ABIArgInfo::getIgnore();
2570 // If the low part is just padding, it takes no register, leave ResType
2571 // null.
2572 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2573 "Unknown missing lo part");
2574 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002575
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002576 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2577 // on the stack.
2578 case Memory:
2579
2580 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2581 // COMPLEX_X87, it is passed in memory.
2582 case X87:
2583 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002584 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002585 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002586 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002587
2588 case SSEUp:
2589 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002590 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002591
2592 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2593 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2594 // and %r9 is used.
2595 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002596 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002597
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002598 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002599 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002600
2601 // If we have a sign or zero extended integer, make sure to return Extend
2602 // so that the parameter gets the right LLVM IR attributes.
2603 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2604 // Treat an enum type as its underlying type.
2605 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2606 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002607
Chris Lattner1f3a0632010-07-29 21:42:50 +00002608 if (Ty->isIntegralOrEnumerationType() &&
2609 Ty->isPromotableIntegerType())
2610 return ABIArgInfo::getExtend();
2611 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002612
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002613 break;
2614
2615 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2616 // available SSE register is used, the registers are taken in the
2617 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002618 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002619 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002620 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002621 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 break;
2623 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002624 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625
Craig Topper8a13c412014-05-21 05:09:00 +00002626 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627 switch (Hi) {
2628 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002629 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002630 // which is passed in memory.
2631 case Memory:
2632 case X87:
2633 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002634 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002635
2636 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002637
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002638 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002640 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002641 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002642
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002643 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2644 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002645 break;
2646
2647 // X87Up generally doesn't occur here (long double is passed in
2648 // memory), except in situations involving unions.
2649 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002650 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002651 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002652
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002653 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2654 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002655
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002656 ++neededSSE;
2657 break;
2658
2659 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2660 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002661 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002662 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002663 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002664 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002665 break;
2666 }
2667
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002668 // If a high part was specified, merge it together with the low part. It is
2669 // known to pass in the high eightbyte of the result. We do this by forming a
2670 // first class struct aggregate with the high and low part: {low, high}
2671 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002672 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002673
Chris Lattner1f3a0632010-07-29 21:42:50 +00002674 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002675}
2676
Chris Lattner22326a12010-07-29 02:31:05 +00002677void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002678
Reid Kleckner40ca9132014-05-13 22:05:45 +00002679 if (!getCXXABI().classifyReturnType(FI))
2680 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002681
2682 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002683 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002684
2685 // If the return value is indirect, then the hidden argument is consuming one
2686 // integer register.
2687 if (FI.getReturnInfo().isIndirect())
2688 --freeIntRegs;
2689
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002690 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002691 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2692 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002693 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002694 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002695 it != ie; ++it, ++ArgNo) {
2696 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00002697
Bill Wendling9987c0e2010-10-18 23:51:38 +00002698 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002699 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00002700 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002701
2702 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2703 // eightbyte of an argument, the whole argument is passed on the
2704 // stack. If registers have already been assigned for some
2705 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002706 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 freeIntRegs -= neededInt;
2708 freeSSERegs -= neededSSE;
2709 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002710 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002711 }
2712 }
2713}
2714
2715static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2716 QualType Ty,
2717 CodeGenFunction &CGF) {
2718 llvm::Value *overflow_arg_area_p =
2719 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2720 llvm::Value *overflow_arg_area =
2721 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2722
2723 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2724 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00002725 // It isn't stated explicitly in the standard, but in practice we use
2726 // alignment greater than 16 where necessary.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2728 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00002729 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00002730 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00002731 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002732 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2733 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00002734 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00002735 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002736 overflow_arg_area =
2737 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2738 overflow_arg_area->getType(),
2739 "overflow_arg_area.align");
2740 }
2741
2742 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00002743 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744 llvm::Value *Res =
2745 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002746 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747
2748 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2749 // l->overflow_arg_area + sizeof(type).
2750 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2751 // an 8 byte boundary.
2752
2753 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00002754 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00002755 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002756 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2757 "overflow_arg_area.next");
2758 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2759
2760 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2761 return Res;
2762}
2763
2764llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2765 CodeGenFunction &CGF) const {
2766 // Assume that va_list type is correct; should be pointer to LLVM type:
2767 // struct {
2768 // i32 gp_offset;
2769 // i32 fp_offset;
2770 // i8* overflow_arg_area;
2771 // i8* reg_save_area;
2772 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00002773 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002774
Chris Lattner9723d6c2010-03-11 18:19:55 +00002775 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman96fd2642013-06-12 00:13:45 +00002776 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2777 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002778
2779 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2780 // in the registers. If not go to step 7.
2781 if (!neededInt && !neededSSE)
2782 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2783
2784 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2785 // general purpose registers needed to pass type and num_fp to hold
2786 // the number of floating point registers needed.
2787
2788 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2789 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2790 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2791 //
2792 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2793 // register save space).
2794
Craig Topper8a13c412014-05-21 05:09:00 +00002795 llvm::Value *InRegs = nullptr;
2796 llvm::Value *gp_offset_p = nullptr, *gp_offset = nullptr;
2797 llvm::Value *fp_offset_p = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002798 if (neededInt) {
2799 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2800 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002801 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2802 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803 }
2804
2805 if (neededSSE) {
2806 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2807 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2808 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00002809 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2810 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002811 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2812 }
2813
2814 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2815 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2816 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2817 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2818
2819 // Emit code to load the value if it was passed in registers.
2820
2821 CGF.EmitBlock(InRegBlock);
2822
2823 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2824 // an offset of l->gp_offset and/or l->fp_offset. This may require
2825 // copying to a temporary location in case the parameter is passed
2826 // in different register classes or requires an alignment greater
2827 // than 8 for general purpose registers and 16 for XMM registers.
2828 //
2829 // FIXME: This really results in shameful code when we end up needing to
2830 // collect arguments from different places; often what should result in a
2831 // simple assembling of a structure from scattered addresses has many more
2832 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00002833 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002834 llvm::Value *RegAddr =
2835 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2836 "reg_save_area");
2837 if (neededInt && neededSSE) {
2838 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00002839 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002840 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmanc11c1692013-06-07 23:20:55 +00002841 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2842 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002843 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002844 llvm::Type *TyLo = ST->getElementType(0);
2845 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00002846 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002847 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00002848 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2849 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002850 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2851 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00002852 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
2853 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002854 llvm::Value *V =
2855 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2856 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2857 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2858 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2859
Owen Anderson170229f2009-07-14 23:10:40 +00002860 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002861 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002862 } else if (neededInt) {
2863 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2864 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson9793f0e2009-07-29 22:16:19 +00002865 llvm::PointerType::getUnqual(LTy));
Eli Friedmanc11c1692013-06-07 23:20:55 +00002866
2867 // Copy to a temporary if necessary to ensure the appropriate alignment.
2868 std::pair<CharUnits, CharUnits> SizeAlign =
2869 CGF.getContext().getTypeInfoInChars(Ty);
2870 uint64_t TySize = SizeAlign.first.getQuantity();
2871 unsigned TyAlign = SizeAlign.second.getQuantity();
2872 if (TyAlign > 8) {
Eli Friedmanc11c1692013-06-07 23:20:55 +00002873 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2874 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2875 RegAddr = Tmp;
2876 }
Chris Lattner0cf24192010-06-28 20:05:43 +00002877 } else if (neededSSE == 1) {
2878 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2879 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2880 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002881 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00002882 assert(neededSSE == 2 && "Invalid number of needed registers!");
2883 // SSE registers are spaced 16 bytes apart in the register save
2884 // area, we need to collect the two eightbytes together.
2885 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002886 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattnerece04092012-02-07 00:39:47 +00002887 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2192fe52011-07-18 04:24:23 +00002888 llvm::Type *DblPtrTy =
Chris Lattner0cf24192010-06-28 20:05:43 +00002889 llvm::PointerType::getUnqual(DoubleTy);
Reid Kleckneree7cf842014-12-01 22:02:27 +00002890 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
Eli Friedmanc11c1692013-06-07 23:20:55 +00002891 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2892 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattner0cf24192010-06-28 20:05:43 +00002893 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2894 DblPtrTy));
2895 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2896 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2897 DblPtrTy));
2898 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2899 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2900 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002901 }
2902
2903 // AMD64-ABI 3.5.7p5: Step 5. Set:
2904 // l->gp_offset = l->gp_offset + num_gp * 8
2905 // l->fp_offset = l->fp_offset + num_fp * 16.
2906 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002907 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002908 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2909 gp_offset_p);
2910 }
2911 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00002912 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002913 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2914 fp_offset_p);
2915 }
2916 CGF.EmitBranch(ContBlock);
2917
2918 // Emit code to load the value if it was passed in memory.
2919
2920 CGF.EmitBlock(InMemBlock);
2921 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2922
2923 // Return the appropriate result.
2924
2925 CGF.EmitBlock(ContBlock);
Jay Foad20c0f022011-03-30 11:28:58 +00002926 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002927 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002928 ResAddr->addIncoming(RegAddr, InRegBlock);
2929 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002930 return ResAddr;
2931}
2932
Reid Kleckner80944df2014-10-31 22:00:51 +00002933ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
2934 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002935
2936 if (Ty->isVoidType())
2937 return ABIArgInfo::getIgnore();
2938
2939 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2940 Ty = EnumTy->getDecl()->getIntegerType();
2941
Reid Kleckner80944df2014-10-31 22:00:51 +00002942 TypeInfo Info = getContext().getTypeInfo(Ty);
2943 uint64_t Width = Info.Width;
2944 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002945
Reid Kleckner9005f412014-05-02 00:51:20 +00002946 const RecordType *RT = Ty->getAs<RecordType>();
2947 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00002948 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00002949 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00002950 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2951 }
2952
2953 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002954 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2955
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002956 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00002957 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002958 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00002959 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00002960 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002961
Reid Kleckner80944df2014-10-31 22:00:51 +00002962 // vectorcall adds the concept of a homogenous vector aggregate, similar to
2963 // other targets.
2964 const Type *Base = nullptr;
2965 uint64_t NumElts = 0;
2966 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
2967 if (FreeSSERegs >= NumElts) {
2968 FreeSSERegs -= NumElts;
2969 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
2970 return ABIArgInfo::getDirect();
2971 return ABIArgInfo::getExpand();
2972 }
2973 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
2974 }
2975
2976
Reid Klecknerec87fec2014-05-02 01:17:12 +00002977 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00002978 // If the member pointer is represented by an LLVM int or ptr, pass it
2979 // directly.
2980 llvm::Type *LLTy = CGT.ConvertType(Ty);
2981 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
2982 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00002983 }
2984
2985 if (RT || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00002986 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2987 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00002988 if (Width > 64 || !llvm::isPowerOf2_64(Width))
Reid Kleckner9005f412014-05-02 00:51:20 +00002989 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002990
Reid Kleckner9005f412014-05-02 00:51:20 +00002991 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00002992 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002993 }
2994
Julien Lerouge10dcff82014-08-27 00:36:55 +00002995 // Bool type is always extended to the ABI, other builtin types are not
2996 // extended.
2997 const BuiltinType *BT = Ty->getAs<BuiltinType>();
2998 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00002999 return ABIArgInfo::getExtend();
3000
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003001 return ABIArgInfo::getDirect();
3002}
3003
3004void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003005 bool IsVectorCall =
3006 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003007
Reid Kleckner80944df2014-10-31 22:00:51 +00003008 // We can use up to 4 SSE return registers with vectorcall.
3009 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3010 if (!getCXXABI().classifyReturnType(FI))
3011 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3012
3013 // We can use up to 6 SSE register parameters with vectorcall.
3014 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003015 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003016 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003017}
3018
Chris Lattner04dc9572010-08-31 16:44:54 +00003019llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3020 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00003021 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattner0cf24192010-06-28 20:05:43 +00003022
Chris Lattner04dc9572010-08-31 16:44:54 +00003023 CGBuilderTy &Builder = CGF.Builder;
3024 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
3025 "ap");
3026 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3027 llvm::Type *PTy =
3028 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3029 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3030
3031 uint64_t Offset =
3032 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
3033 llvm::Value *NextAddr =
3034 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
3035 "ap.next");
3036 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3037
3038 return AddrTyped;
3039}
Chris Lattner0cf24192010-06-28 20:05:43 +00003040
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003041namespace {
3042
Derek Schuffa2020962012-10-16 22:30:41 +00003043class NaClX86_64ABIInfo : public ABIInfo {
3044 public:
3045 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3046 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
Craig Topper4f12f102014-03-12 06:41:41 +00003047 void computeInfo(CGFunctionInfo &FI) const override;
3048 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3049 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00003050 private:
3051 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3052 X86_64ABIInfo NInfo; // Used for everything else.
3053};
3054
3055class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
Alexander Musman09184fe2014-09-30 05:29:28 +00003056 bool HasAVX;
Derek Schuffa2020962012-10-16 22:30:41 +00003057 public:
Alexander Musman09184fe2014-09-30 05:29:28 +00003058 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
3059 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)), HasAVX(HasAVX) {
3060 }
3061 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3062 return HasAVX ? 32 : 16;
3063 }
Derek Schuffa2020962012-10-16 22:30:41 +00003064};
3065
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00003066}
3067
Derek Schuffa2020962012-10-16 22:30:41 +00003068void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3069 if (FI.getASTCallingConvention() == CC_PnaclCall)
3070 PInfo.computeInfo(FI);
3071 else
3072 NInfo.computeInfo(FI);
3073}
3074
3075llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3076 CodeGenFunction &CGF) const {
3077 // Always use the native convention; calling pnacl-style varargs functions
3078 // is unuspported.
3079 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
3080}
3081
3082
John McCallea8d8bb2010-03-11 00:10:12 +00003083// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003084namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003085/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3086class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003087public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003088 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3089
3090 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3091 CodeGenFunction &CGF) const override;
3092};
3093
3094class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3095public:
3096 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003097
Craig Topper4f12f102014-03-12 06:41:41 +00003098 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003099 // This is recovered from gcc output.
3100 return 1; // r1 is the dedicated stack pointer
3101 }
3102
3103 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003104 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003105
3106 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3107 return 16; // Natural alignment for Altivec vectors.
3108 }
John McCallea8d8bb2010-03-11 00:10:12 +00003109};
3110
3111}
3112
Roman Divacky8a12d842014-11-03 18:32:54 +00003113llvm::Value *PPC32_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3114 QualType Ty,
3115 CodeGenFunction &CGF) const {
3116 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3117 // TODO: Implement this. For now ignore.
3118 (void)CTy;
3119 return nullptr;
3120 }
3121
3122 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
3123 bool isInt = Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
3124 llvm::Type *CharPtr = CGF.Int8PtrTy;
3125 llvm::Type *CharPtrPtr = CGF.Int8PtrPtrTy;
3126
3127 CGBuilderTy &Builder = CGF.Builder;
3128 llvm::Value *GPRPtr = Builder.CreateBitCast(VAListAddr, CharPtr, "gprptr");
3129 llvm::Value *GPRPtrAsInt = Builder.CreatePtrToInt(GPRPtr, CGF.Int32Ty);
3130 llvm::Value *FPRPtrAsInt = Builder.CreateAdd(GPRPtrAsInt, Builder.getInt32(1));
3131 llvm::Value *FPRPtr = Builder.CreateIntToPtr(FPRPtrAsInt, CharPtr);
3132 llvm::Value *OverflowAreaPtrAsInt = Builder.CreateAdd(FPRPtrAsInt, Builder.getInt32(3));
3133 llvm::Value *OverflowAreaPtr = Builder.CreateIntToPtr(OverflowAreaPtrAsInt, CharPtrPtr);
3134 llvm::Value *RegsaveAreaPtrAsInt = Builder.CreateAdd(OverflowAreaPtrAsInt, Builder.getInt32(4));
3135 llvm::Value *RegsaveAreaPtr = Builder.CreateIntToPtr(RegsaveAreaPtrAsInt, CharPtrPtr);
3136 llvm::Value *GPR = Builder.CreateLoad(GPRPtr, false, "gpr");
3137 // Align GPR when TY is i64.
3138 if (isI64) {
3139 llvm::Value *GPRAnd = Builder.CreateAnd(GPR, Builder.getInt8(1));
3140 llvm::Value *CC64 = Builder.CreateICmpEQ(GPRAnd, Builder.getInt8(1));
3141 llvm::Value *GPRPlusOne = Builder.CreateAdd(GPR, Builder.getInt8(1));
3142 GPR = Builder.CreateSelect(CC64, GPRPlusOne, GPR);
3143 }
3144 llvm::Value *FPR = Builder.CreateLoad(FPRPtr, false, "fpr");
3145 llvm::Value *OverflowArea = Builder.CreateLoad(OverflowAreaPtr, false, "overflow_area");
3146 llvm::Value *OverflowAreaAsInt = Builder.CreatePtrToInt(OverflowArea, CGF.Int32Ty);
3147 llvm::Value *RegsaveArea = Builder.CreateLoad(RegsaveAreaPtr, false, "regsave_area");
3148 llvm::Value *RegsaveAreaAsInt = Builder.CreatePtrToInt(RegsaveArea, CGF.Int32Ty);
3149
3150 llvm::Value *CC = Builder.CreateICmpULT(isInt ? GPR : FPR,
3151 Builder.getInt8(8), "cond");
3152
3153 llvm::Value *RegConstant = Builder.CreateMul(isInt ? GPR : FPR,
3154 Builder.getInt8(isInt ? 4 : 8));
3155
3156 llvm::Value *OurReg = Builder.CreateAdd(RegsaveAreaAsInt, Builder.CreateSExt(RegConstant, CGF.Int32Ty));
3157
3158 if (Ty->isFloatingType())
3159 OurReg = Builder.CreateAdd(OurReg, Builder.getInt32(32));
3160
3161 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3162 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3163 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3164
3165 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3166
3167 CGF.EmitBlock(UsingRegs);
3168
3169 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3170 llvm::Value *Result1 = Builder.CreateIntToPtr(OurReg, PTy);
3171 // Increase the GPR/FPR indexes.
3172 if (isInt) {
3173 GPR = Builder.CreateAdd(GPR, Builder.getInt8(isI64 ? 2 : 1));
3174 Builder.CreateStore(GPR, GPRPtr);
3175 } else {
3176 FPR = Builder.CreateAdd(FPR, Builder.getInt8(1));
3177 Builder.CreateStore(FPR, FPRPtr);
3178 }
3179 CGF.EmitBranch(Cont);
3180
3181 CGF.EmitBlock(UsingOverflow);
3182
3183 // Increase the overflow area.
3184 llvm::Value *Result2 = Builder.CreateIntToPtr(OverflowAreaAsInt, PTy);
3185 OverflowAreaAsInt = Builder.CreateAdd(OverflowAreaAsInt, Builder.getInt32(isInt ? 4 : 8));
3186 Builder.CreateStore(Builder.CreateIntToPtr(OverflowAreaAsInt, CharPtr), OverflowAreaPtr);
3187 CGF.EmitBranch(Cont);
3188
3189 CGF.EmitBlock(Cont);
3190
3191 llvm::PHINode *Result = CGF.Builder.CreatePHI(PTy, 2, "vaarg.addr");
3192 Result->addIncoming(Result1, UsingRegs);
3193 Result->addIncoming(Result2, UsingOverflow);
3194
3195 if (Ty->isAggregateType()) {
3196 llvm::Value *AGGPtr = Builder.CreateBitCast(Result, CharPtrPtr, "aggrptr") ;
3197 return Builder.CreateLoad(AGGPtr, false, "aggr");
3198 }
3199
3200 return Result;
3201}
3202
John McCallea8d8bb2010-03-11 00:10:12 +00003203bool
3204PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3205 llvm::Value *Address) const {
3206 // This is calculated from the LLVM and GCC tables and verified
3207 // against gcc output. AFAIK all ABIs use the same encoding.
3208
3209 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003210
Chris Lattnerece04092012-02-07 00:39:47 +00003211 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003212 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3213 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3214 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3215
3216 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003217 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003218
3219 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003220 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003221
3222 // 64-76 are various 4-byte special-purpose registers:
3223 // 64: mq
3224 // 65: lr
3225 // 66: ctr
3226 // 67: ap
3227 // 68-75 cr0-7
3228 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003229 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003230
3231 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003232 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003233
3234 // 109: vrsave
3235 // 110: vscr
3236 // 111: spe_acc
3237 // 112: spefscr
3238 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003239 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003240
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003241 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003242}
3243
Roman Divackyd966e722012-05-09 18:22:46 +00003244// PowerPC-64
3245
3246namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003247/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3248class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003249public:
3250 enum ABIKind {
3251 ELFv1 = 0,
3252 ELFv2
3253 };
3254
3255private:
3256 static const unsigned GPRBits = 64;
3257 ABIKind Kind;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003258
3259public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003260 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
3261 : DefaultABIInfo(CGT), Kind(Kind) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003262
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003263 bool isPromotableTypeForABI(QualType Ty) const;
Ulrich Weigand581badc2014-07-10 17:20:07 +00003264 bool isAlignedParamType(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003265
3266 ABIArgInfo classifyReturnType(QualType RetTy) const;
3267 ABIArgInfo classifyArgumentType(QualType Ty) const;
3268
Reid Klecknere9f6a712014-10-31 17:10:41 +00003269 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3270 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3271 uint64_t Members) const override;
3272
Bill Schmidt84d37792012-10-12 19:26:17 +00003273 // TODO: We can add more logic to computeInfo to improve performance.
3274 // Example: For aggregate arguments that fit in a register, we could
3275 // use getDirectInReg (as is done below for structs containing a single
3276 // floating-point value) to avoid pushing them to memory on function
3277 // entry. This would require changing the logic in PPCISelLowering
3278 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003279 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003280 if (!getCXXABI().classifyReturnType(FI))
3281 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003282 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003283 // We rely on the default argument classification for the most part.
3284 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003285 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003286 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003287 if (T) {
3288 const BuiltinType *BT = T->getAs<BuiltinType>();
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003289 if ((T->isVectorType() && getContext().getTypeSize(T) == 128) ||
3290 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003291 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003292 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003293 continue;
3294 }
3295 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003296 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003297 }
3298 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003299
Craig Topper4f12f102014-03-12 06:41:41 +00003300 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3301 CodeGenFunction &CGF) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003302};
3303
3304class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
3305public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003306 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
3307 PPC64_SVR4_ABIInfo::ABIKind Kind)
3308 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003309
Craig Topper4f12f102014-03-12 06:41:41 +00003310 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003311 // This is recovered from gcc output.
3312 return 1; // r1 is the dedicated stack pointer
3313 }
3314
3315 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003316 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003317
3318 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3319 return 16; // Natural alignment for Altivec and VSX vectors.
3320 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003321};
3322
Roman Divackyd966e722012-05-09 18:22:46 +00003323class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3324public:
3325 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3326
Craig Topper4f12f102014-03-12 06:41:41 +00003327 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003328 // This is recovered from gcc output.
3329 return 1; // r1 is the dedicated stack pointer
3330 }
3331
3332 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003333 llvm::Value *Address) const override;
Hal Finkel92e31a52014-10-03 17:45:20 +00003334
3335 unsigned getOpenMPSimdDefaultAlignment(QualType) const override {
3336 return 16; // Natural alignment for Altivec vectors.
3337 }
Roman Divackyd966e722012-05-09 18:22:46 +00003338};
3339
3340}
3341
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003342// Return true if the ABI requires Ty to be passed sign- or zero-
3343// extended to 64 bits.
3344bool
3345PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3346 // Treat an enum type as its underlying type.
3347 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3348 Ty = EnumTy->getDecl()->getIntegerType();
3349
3350 // Promotable integer types are required to be promoted by the ABI.
3351 if (Ty->isPromotableIntegerType())
3352 return true;
3353
3354 // In addition to the usual promotable integer types, we also need to
3355 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3356 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3357 switch (BT->getKind()) {
3358 case BuiltinType::Int:
3359 case BuiltinType::UInt:
3360 return true;
3361 default:
3362 break;
3363 }
3364
3365 return false;
3366}
3367
Ulrich Weigand581badc2014-07-10 17:20:07 +00003368/// isAlignedParamType - Determine whether a type requires 16-byte
3369/// alignment in the parameter area.
3370bool
3371PPC64_SVR4_ABIInfo::isAlignedParamType(QualType Ty) const {
3372 // Complex types are passed just like their elements.
3373 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3374 Ty = CTy->getElementType();
3375
3376 // Only vector types of size 16 bytes need alignment (larger types are
3377 // passed via reference, smaller types are not aligned).
3378 if (Ty->isVectorType())
3379 return getContext().getTypeSize(Ty) == 128;
3380
3381 // For single-element float/vector structs, we consider the whole type
3382 // to have the same alignment requirements as its single element.
3383 const Type *AlignAsType = nullptr;
3384 const Type *EltType = isSingleElementStruct(Ty, getContext());
3385 if (EltType) {
3386 const BuiltinType *BT = EltType->getAs<BuiltinType>();
3387 if ((EltType->isVectorType() &&
3388 getContext().getTypeSize(EltType) == 128) ||
3389 (BT && BT->isFloatingPoint()))
3390 AlignAsType = EltType;
3391 }
3392
Ulrich Weigandb7122372014-07-21 00:48:09 +00003393 // Likewise for ELFv2 homogeneous aggregates.
3394 const Type *Base = nullptr;
3395 uint64_t Members = 0;
3396 if (!AlignAsType && Kind == ELFv2 &&
3397 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3398 AlignAsType = Base;
3399
Ulrich Weigand581badc2014-07-10 17:20:07 +00003400 // With special case aggregates, only vector base types need alignment.
3401 if (AlignAsType)
3402 return AlignAsType->isVectorType();
3403
3404 // Otherwise, we only need alignment for any aggregate type that
3405 // has an alignment requirement of >= 16 bytes.
3406 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128)
3407 return true;
3408
3409 return false;
3410}
3411
Ulrich Weigandb7122372014-07-21 00:48:09 +00003412/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3413/// aggregate. Base is set to the base element type, and Members is set
3414/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003415bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3416 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003417 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3418 uint64_t NElements = AT->getSize().getZExtValue();
3419 if (NElements == 0)
3420 return false;
3421 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3422 return false;
3423 Members *= NElements;
3424 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3425 const RecordDecl *RD = RT->getDecl();
3426 if (RD->hasFlexibleArrayMember())
3427 return false;
3428
3429 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003430
3431 // If this is a C++ record, check the bases first.
3432 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3433 for (const auto &I : CXXRD->bases()) {
3434 // Ignore empty records.
3435 if (isEmptyRecord(getContext(), I.getType(), true))
3436 continue;
3437
3438 uint64_t FldMembers;
3439 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3440 return false;
3441
3442 Members += FldMembers;
3443 }
3444 }
3445
Ulrich Weigandb7122372014-07-21 00:48:09 +00003446 for (const auto *FD : RD->fields()) {
3447 // Ignore (non-zero arrays of) empty records.
3448 QualType FT = FD->getType();
3449 while (const ConstantArrayType *AT =
3450 getContext().getAsConstantArrayType(FT)) {
3451 if (AT->getSize().getZExtValue() == 0)
3452 return false;
3453 FT = AT->getElementType();
3454 }
3455 if (isEmptyRecord(getContext(), FT, true))
3456 continue;
3457
3458 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3459 if (getContext().getLangOpts().CPlusPlus &&
3460 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3461 continue;
3462
3463 uint64_t FldMembers;
3464 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3465 return false;
3466
3467 Members = (RD->isUnion() ?
3468 std::max(Members, FldMembers) : Members + FldMembers);
3469 }
3470
3471 if (!Base)
3472 return false;
3473
3474 // Ensure there is no padding.
3475 if (getContext().getTypeSize(Base) * Members !=
3476 getContext().getTypeSize(Ty))
3477 return false;
3478 } else {
3479 Members = 1;
3480 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3481 Members = 2;
3482 Ty = CT->getElementType();
3483 }
3484
Reid Klecknere9f6a712014-10-31 17:10:41 +00003485 // Most ABIs only support float, double, and some vector type widths.
3486 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003487 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003488
3489 // The base type must be the same for all members. Types that
3490 // agree in both total size and mode (float vs. vector) are
3491 // treated as being equivalent here.
3492 const Type *TyPtr = Ty.getTypePtr();
3493 if (!Base)
3494 Base = TyPtr;
3495
3496 if (Base->isVectorType() != TyPtr->isVectorType() ||
3497 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3498 return false;
3499 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003500 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3501}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003502
Reid Klecknere9f6a712014-10-31 17:10:41 +00003503bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3504 // Homogeneous aggregates for ELFv2 must have base types of float,
3505 // double, long double, or 128-bit vectors.
3506 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3507 if (BT->getKind() == BuiltinType::Float ||
3508 BT->getKind() == BuiltinType::Double ||
3509 BT->getKind() == BuiltinType::LongDouble)
3510 return true;
3511 }
3512 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3513 if (getContext().getTypeSize(VT) == 128)
3514 return true;
3515 }
3516 return false;
3517}
3518
3519bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3520 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003521 // Vector types require one register, floating point types require one
3522 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003523 uint32_t NumRegs =
3524 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003525
3526 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003527 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003528}
3529
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003530ABIArgInfo
3531PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003532 Ty = useFirstFieldIfTransparentUnion(Ty);
3533
Bill Schmidt90b22c92012-11-27 02:46:43 +00003534 if (Ty->isAnyComplexType())
3535 return ABIArgInfo::getDirect();
3536
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003537 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3538 // or via reference (larger than 16 bytes).
3539 if (Ty->isVectorType()) {
3540 uint64_t Size = getContext().getTypeSize(Ty);
3541 if (Size > 128)
3542 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3543 else if (Size < 128) {
3544 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3545 return ABIArgInfo::getDirect(CoerceTy);
3546 }
3547 }
3548
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003549 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003550 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003551 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003552
Ulrich Weigand581badc2014-07-10 17:20:07 +00003553 uint64_t ABIAlign = isAlignedParamType(Ty)? 16 : 8;
3554 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003555
3556 // ELFv2 homogeneous aggregates are passed as array types.
3557 const Type *Base = nullptr;
3558 uint64_t Members = 0;
3559 if (Kind == ELFv2 &&
3560 isHomogeneousAggregate(Ty, Base, Members)) {
3561 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3562 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3563 return ABIArgInfo::getDirect(CoerceTy);
3564 }
3565
Ulrich Weigand601957f2014-07-21 00:56:36 +00003566 // If an aggregate may end up fully in registers, we do not
3567 // use the ByVal method, but pass the aggregate as array.
3568 // This is usually beneficial since we avoid forcing the
3569 // back-end to store the argument to memory.
3570 uint64_t Bits = getContext().getTypeSize(Ty);
3571 if (Bits > 0 && Bits <= 8 * GPRBits) {
3572 llvm::Type *CoerceTy;
3573
3574 // Types up to 8 bytes are passed as integer type (which will be
3575 // properly aligned in the argument save area doubleword).
3576 if (Bits <= GPRBits)
3577 CoerceTy = llvm::IntegerType::get(getVMContext(),
3578 llvm::RoundUpToAlignment(Bits, 8));
3579 // Larger types are passed as arrays, with the base type selected
3580 // according to the required alignment in the save area.
3581 else {
3582 uint64_t RegBits = ABIAlign * 8;
3583 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3584 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3585 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3586 }
3587
3588 return ABIArgInfo::getDirect(CoerceTy);
3589 }
3590
Ulrich Weigandb7122372014-07-21 00:48:09 +00003591 // All other aggregates are passed ByVal.
Ulrich Weigand581badc2014-07-10 17:20:07 +00003592 return ABIArgInfo::getIndirect(ABIAlign, /*ByVal=*/true,
3593 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003594 }
3595
3596 return (isPromotableTypeForABI(Ty) ?
3597 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3598}
3599
3600ABIArgInfo
3601PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3602 if (RetTy->isVoidType())
3603 return ABIArgInfo::getIgnore();
3604
Bill Schmidta3d121c2012-12-17 04:20:17 +00003605 if (RetTy->isAnyComplexType())
3606 return ABIArgInfo::getDirect();
3607
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003608 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3609 // or via reference (larger than 16 bytes).
3610 if (RetTy->isVectorType()) {
3611 uint64_t Size = getContext().getTypeSize(RetTy);
3612 if (Size > 128)
3613 return ABIArgInfo::getIndirect(0);
3614 else if (Size < 128) {
3615 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3616 return ABIArgInfo::getDirect(CoerceTy);
3617 }
3618 }
3619
Ulrich Weigandb7122372014-07-21 00:48:09 +00003620 if (isAggregateTypeForABI(RetTy)) {
3621 // ELFv2 homogeneous aggregates are returned as array types.
3622 const Type *Base = nullptr;
3623 uint64_t Members = 0;
3624 if (Kind == ELFv2 &&
3625 isHomogeneousAggregate(RetTy, Base, Members)) {
3626 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3627 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3628 return ABIArgInfo::getDirect(CoerceTy);
3629 }
3630
3631 // ELFv2 small aggregates are returned in up to two registers.
3632 uint64_t Bits = getContext().getTypeSize(RetTy);
3633 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
3634 if (Bits == 0)
3635 return ABIArgInfo::getIgnore();
3636
3637 llvm::Type *CoerceTy;
3638 if (Bits > GPRBits) {
3639 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00003640 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003641 } else
3642 CoerceTy = llvm::IntegerType::get(getVMContext(),
3643 llvm::RoundUpToAlignment(Bits, 8));
3644 return ABIArgInfo::getDirect(CoerceTy);
3645 }
3646
3647 // All other aggregates are returned indirectly.
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003648 return ABIArgInfo::getIndirect(0);
Ulrich Weigandb7122372014-07-21 00:48:09 +00003649 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003650
3651 return (isPromotableTypeForABI(RetTy) ?
3652 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3653}
3654
Bill Schmidt25cb3492012-10-03 19:18:57 +00003655// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
3656llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
3657 QualType Ty,
3658 CodeGenFunction &CGF) const {
3659 llvm::Type *BP = CGF.Int8PtrTy;
3660 llvm::Type *BPP = CGF.Int8PtrPtrTy;
3661
3662 CGBuilderTy &Builder = CGF.Builder;
3663 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
3664 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
3665
Ulrich Weigand581badc2014-07-10 17:20:07 +00003666 // Handle types that require 16-byte alignment in the parameter save area.
3667 if (isAlignedParamType(Ty)) {
3668 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3669 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(15));
3670 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt64(-16));
3671 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
3672 }
3673
Bill Schmidt924c4782013-01-14 17:45:36 +00003674 // Update the va_list pointer. The pointer should be bumped by the
3675 // size of the object. We can trust getTypeSize() except for a complex
3676 // type whose base type is smaller than a doubleword. For these, the
3677 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt25cb3492012-10-03 19:18:57 +00003678 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt924c4782013-01-14 17:45:36 +00003679 QualType BaseTy;
3680 unsigned CplxBaseSize = 0;
3681
3682 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3683 BaseTy = CTy->getElementType();
3684 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
3685 if (CplxBaseSize < 8)
3686 SizeInBytes = 16;
3687 }
3688
Bill Schmidt25cb3492012-10-03 19:18:57 +00003689 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
3690 llvm::Value *NextAddr =
3691 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
3692 "ap.next");
3693 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3694
Bill Schmidt924c4782013-01-14 17:45:36 +00003695 // If we have a complex type and the base type is smaller than 8 bytes,
3696 // the ABI calls for the real and imaginary parts to be right-adjusted
3697 // in separate doublewords. However, Clang expects us to produce a
3698 // pointer to a structure with the two parts packed tightly. So generate
3699 // loads of the real and imaginary parts relative to the va_list pointer,
3700 // and store them to a temporary structure.
3701 if (CplxBaseSize && CplxBaseSize < 8) {
3702 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3703 llvm::Value *ImagAddr = RealAddr;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003704 if (CGF.CGM.getDataLayout().isBigEndian()) {
3705 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
3706 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
3707 } else {
3708 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(8));
3709 }
Bill Schmidt924c4782013-01-14 17:45:36 +00003710 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
3711 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
3712 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
3713 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
3714 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
3715 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
3716 "vacplx");
3717 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
3718 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
3719 Builder.CreateStore(Real, RealPtr, false);
3720 Builder.CreateStore(Imag, ImagPtr, false);
3721 return Ptr;
3722 }
3723
Bill Schmidt25cb3492012-10-03 19:18:57 +00003724 // If the argument is smaller than 8 bytes, it is right-adjusted in
3725 // its doubleword slot. Adjust the pointer to pick it up from the
3726 // correct offset.
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00003727 if (SizeInBytes < 8 && CGF.CGM.getDataLayout().isBigEndian()) {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003728 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
3729 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
3730 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
3731 }
3732
3733 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3734 return Builder.CreateBitCast(Addr, PTy);
3735}
3736
3737static bool
3738PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3739 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00003740 // This is calculated from the LLVM and GCC tables and verified
3741 // against gcc output. AFAIK all ABIs use the same encoding.
3742
3743 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3744
3745 llvm::IntegerType *i8 = CGF.Int8Ty;
3746 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3747 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3748 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3749
3750 // 0-31: r0-31, the 8-byte general-purpose registers
3751 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3752
3753 // 32-63: fp0-31, the 8-byte floating-point registers
3754 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3755
3756 // 64-76 are various 4-byte special-purpose registers:
3757 // 64: mq
3758 // 65: lr
3759 // 66: ctr
3760 // 67: ap
3761 // 68-75 cr0-7
3762 // 76: xer
3763 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3764
3765 // 77-108: v0-31, the 16-byte vector registers
3766 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3767
3768 // 109: vrsave
3769 // 110: vscr
3770 // 111: spe_acc
3771 // 112: spefscr
3772 // 113: sfp
3773 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3774
3775 return false;
3776}
John McCallea8d8bb2010-03-11 00:10:12 +00003777
Bill Schmidt25cb3492012-10-03 19:18:57 +00003778bool
3779PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3780 CodeGen::CodeGenFunction &CGF,
3781 llvm::Value *Address) const {
3782
3783 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3784}
3785
3786bool
3787PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3788 llvm::Value *Address) const {
3789
3790 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3791}
3792
Chris Lattner0cf24192010-06-28 20:05:43 +00003793//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00003794// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00003795//===----------------------------------------------------------------------===//
3796
3797namespace {
3798
Tim Northover573cbee2014-05-24 12:52:07 +00003799class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003800public:
3801 enum ABIKind {
3802 AAPCS = 0,
3803 DarwinPCS
3804 };
3805
3806private:
3807 ABIKind Kind;
3808
3809public:
Tim Northover573cbee2014-05-24 12:52:07 +00003810 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003811
3812private:
3813 ABIKind getABIKind() const { return Kind; }
3814 bool isDarwinPCS() const { return Kind == DarwinPCS; }
3815
3816 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00003817 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003818 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3819 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3820 uint64_t Members) const override;
3821
Tim Northovera2ee4332014-03-29 15:09:45 +00003822 bool isIllegalVectorType(QualType Ty) const;
3823
David Blaikie1cbb9712014-11-14 19:09:44 +00003824 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003825 if (!getCXXABI().classifyReturnType(FI))
3826 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00003827
Tim Northoverb047bfa2014-11-27 21:02:49 +00003828 for (auto &it : FI.arguments())
3829 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00003830 }
3831
3832 llvm::Value *EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
3833 CodeGenFunction &CGF) const;
3834
3835 llvm::Value *EmitAAPCSVAArg(llvm::Value *VAListAddr, QualType Ty,
3836 CodeGenFunction &CGF) const;
3837
3838 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
NAKAMURA Takumi8c894962014-11-01 01:32:27 +00003839 CodeGenFunction &CGF) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00003840 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
3841 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
3842 }
3843};
3844
Tim Northover573cbee2014-05-24 12:52:07 +00003845class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00003846public:
Tim Northover573cbee2014-05-24 12:52:07 +00003847 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
3848 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00003849
3850 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
3851 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
3852 }
3853
3854 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const { return 31; }
3855
3856 virtual bool doesReturnSlotInterfereWithArgs() const { return false; }
3857};
3858}
3859
Tim Northoverb047bfa2014-11-27 21:02:49 +00003860ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003861 Ty = useFirstFieldIfTransparentUnion(Ty);
3862
Tim Northovera2ee4332014-03-29 15:09:45 +00003863 // Handle illegal vector types here.
3864 if (isIllegalVectorType(Ty)) {
3865 uint64_t Size = getContext().getTypeSize(Ty);
3866 if (Size <= 32) {
3867 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00003868 return ABIArgInfo::getDirect(ResType);
3869 }
3870 if (Size == 64) {
3871 llvm::Type *ResType =
3872 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00003873 return ABIArgInfo::getDirect(ResType);
3874 }
3875 if (Size == 128) {
3876 llvm::Type *ResType =
3877 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00003878 return ABIArgInfo::getDirect(ResType);
3879 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003880 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3881 }
Tim Northovera2ee4332014-03-29 15:09:45 +00003882
3883 if (!isAggregateTypeForABI(Ty)) {
3884 // Treat an enum type as its underlying type.
3885 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3886 Ty = EnumTy->getDecl()->getIntegerType();
3887
Tim Northovera2ee4332014-03-29 15:09:45 +00003888 return (Ty->isPromotableIntegerType() && isDarwinPCS()
3889 ? ABIArgInfo::getExtend()
3890 : ABIArgInfo::getDirect());
3891 }
3892
3893 // Structures with either a non-trivial destructor or a non-trivial
3894 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00003895 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003896 return ABIArgInfo::getIndirect(0, /*ByVal=*/RAA ==
Tim Northoverb047bfa2014-11-27 21:02:49 +00003897 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00003898 }
3899
3900 // Empty records are always ignored on Darwin, but actually passed in C++ mode
3901 // elsewhere for GNU compatibility.
3902 if (isEmptyRecord(getContext(), Ty, true)) {
3903 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
3904 return ABIArgInfo::getIgnore();
3905
Tim Northovera2ee4332014-03-29 15:09:45 +00003906 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
3907 }
3908
3909 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00003910 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00003911 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003912 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00003913 return ABIArgInfo::getDirect(
3914 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00003915 }
3916
3917 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
3918 uint64_t Size = getContext().getTypeSize(Ty);
3919 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00003920 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00003921 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00003922
Tim Northovera2ee4332014-03-29 15:09:45 +00003923 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
3924 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00003925 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003926 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
3927 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
3928 }
3929 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3930 }
3931
Tim Northovera2ee4332014-03-29 15:09:45 +00003932 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3933}
3934
Tim Northover573cbee2014-05-24 12:52:07 +00003935ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003936 if (RetTy->isVoidType())
3937 return ABIArgInfo::getIgnore();
3938
3939 // Large vector types should be returned via memory.
3940 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3941 return ABIArgInfo::getIndirect(0);
3942
3943 if (!isAggregateTypeForABI(RetTy)) {
3944 // Treat an enum type as its underlying type.
3945 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3946 RetTy = EnumTy->getDecl()->getIntegerType();
3947
Tim Northover4dab6982014-04-18 13:46:08 +00003948 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
3949 ? ABIArgInfo::getExtend()
3950 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00003951 }
3952
Tim Northovera2ee4332014-03-29 15:09:45 +00003953 if (isEmptyRecord(getContext(), RetTy, true))
3954 return ABIArgInfo::getIgnore();
3955
Craig Topper8a13c412014-05-21 05:09:00 +00003956 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00003957 uint64_t Members = 0;
3958 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00003959 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
3960 return ABIArgInfo::getDirect();
3961
3962 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
3963 uint64_t Size = getContext().getTypeSize(RetTy);
3964 if (Size <= 128) {
3965 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
3966 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
3967 }
3968
3969 return ABIArgInfo::getIndirect(0);
3970}
3971
Tim Northover573cbee2014-05-24 12:52:07 +00003972/// isIllegalVectorType - check whether the vector type is legal for AArch64.
3973bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00003974 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3975 // Check whether VT is legal.
3976 unsigned NumElements = VT->getNumElements();
3977 uint64_t Size = getContext().getTypeSize(VT);
3978 // NumElements should be power of 2 between 1 and 16.
3979 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
3980 return true;
3981 return Size != 64 && (Size != 128 || NumElements == 1);
3982 }
3983 return false;
3984}
3985
Reid Klecknere9f6a712014-10-31 17:10:41 +00003986bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3987 // Homogeneous aggregates for AAPCS64 must have base types of a floating
3988 // point type or a short-vector type. This is the same as the 32-bit ABI,
3989 // but with the difference that any floating-point type is allowed,
3990 // including __fp16.
3991 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3992 if (BT->isFloatingPoint())
3993 return true;
3994 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3995 unsigned VecSize = getContext().getTypeSize(VT);
3996 if (VecSize == 64 || VecSize == 128)
3997 return true;
3998 }
3999 return false;
4000}
4001
4002bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4003 uint64_t Members) const {
4004 return Members <= 4;
4005}
4006
Tim Northoverb047bfa2014-11-27 21:02:49 +00004007llvm::Value *AArch64ABIInfo::EmitAAPCSVAArg(llvm::Value *VAListAddr,
4008 QualType Ty,
4009 CodeGenFunction &CGF) const {
4010 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004011 bool IsIndirect = AI.isIndirect();
4012
Tim Northoverb047bfa2014-11-27 21:02:49 +00004013 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4014 if (IsIndirect)
4015 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4016 else if (AI.getCoerceToType())
4017 BaseTy = AI.getCoerceToType();
4018
4019 unsigned NumRegs = 1;
4020 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4021 BaseTy = ArrTy->getElementType();
4022 NumRegs = ArrTy->getNumElements();
4023 }
4024 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4025
Tim Northovera2ee4332014-03-29 15:09:45 +00004026 // The AArch64 va_list type and handling is specified in the Procedure Call
4027 // Standard, section B.4:
4028 //
4029 // struct {
4030 // void *__stack;
4031 // void *__gr_top;
4032 // void *__vr_top;
4033 // int __gr_offs;
4034 // int __vr_offs;
4035 // };
4036
4037 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4038 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4039 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4040 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4041 auto &Ctx = CGF.getContext();
4042
Craig Topper8a13c412014-05-21 05:09:00 +00004043 llvm::Value *reg_offs_p = nullptr, *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004044 int reg_top_index;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004045 int RegSize = IsIndirect ? 8 : getContext().getTypeSize(Ty) / 8;
4046 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004047 // 3 is the field number of __gr_offs
4048 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
4049 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4050 reg_top_index = 1; // field number for __gr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004051 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004052 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004053 // 4 is the field number of __vr_offs.
4054 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4055 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4056 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00004057 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004058 }
4059
4060 //=======================================
4061 // Find out where argument was passed
4062 //=======================================
4063
4064 // If reg_offs >= 0 we're already using the stack for this type of
4065 // argument. We don't want to keep updating reg_offs (in case it overflows,
4066 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4067 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004068 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004069 UsingStack = CGF.Builder.CreateICmpSGE(
4070 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4071
4072 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4073
4074 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004075 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004076 CGF.EmitBlock(MaybeRegBlock);
4077
4078 // Integer arguments may need to correct register alignment (for example a
4079 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4080 // align __gr_offs to calculate the potential address.
Tim Northoverb047bfa2014-11-27 21:02:49 +00004081 if (!IsFPR && !IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004082 int Align = Ctx.getTypeAlign(Ty) / 8;
4083
4084 reg_offs = CGF.Builder.CreateAdd(
4085 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4086 "align_regoffs");
4087 reg_offs = CGF.Builder.CreateAnd(
4088 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4089 "aligned_regoffs");
4090 }
4091
4092 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
Craig Topper8a13c412014-05-21 05:09:00 +00004093 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004094 NewOffset = CGF.Builder.CreateAdd(
4095 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4096 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4097
4098 // Now we're in a position to decide whether this argument really was in
4099 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004100 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004101 InRegs = CGF.Builder.CreateICmpSLE(
4102 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4103
4104 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4105
4106 //=======================================
4107 // Argument was in registers
4108 //=======================================
4109
4110 // Now we emit the code for if the argument was originally passed in
4111 // registers. First start the appropriate block:
4112 CGF.EmitBlock(InRegBlock);
4113
Craig Topper8a13c412014-05-21 05:09:00 +00004114 llvm::Value *reg_top_p = nullptr, *reg_top = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004115 reg_top_p =
4116 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4117 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4118 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
Craig Topper8a13c412014-05-21 05:09:00 +00004119 llvm::Value *RegAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004120 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4121
4122 if (IsIndirect) {
4123 // If it's been passed indirectly (actually a struct), whatever we find from
4124 // stored registers or on the stack will actually be a struct **.
4125 MemTy = llvm::PointerType::getUnqual(MemTy);
4126 }
4127
Craig Topper8a13c412014-05-21 05:09:00 +00004128 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004129 uint64_t NumMembers = 0;
4130 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004131 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004132 // Homogeneous aggregates passed in registers will have their elements split
4133 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4134 // qN+1, ...). We reload and store into a temporary local variable
4135 // contiguously.
4136 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
4137 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4138 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4139 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4140 int Offset = 0;
4141
4142 if (CGF.CGM.getDataLayout().isBigEndian() && Ctx.getTypeSize(Base) < 128)
4143 Offset = 16 - Ctx.getTypeSize(Base) / 8;
4144 for (unsigned i = 0; i < NumMembers; ++i) {
4145 llvm::Value *BaseOffset =
4146 llvm::ConstantInt::get(CGF.Int32Ty, 16 * i + Offset);
4147 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4148 LoadAddr = CGF.Builder.CreateBitCast(
4149 LoadAddr, llvm::PointerType::getUnqual(BaseTy));
4150 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4151
4152 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4153 CGF.Builder.CreateStore(Elem, StoreAddr);
4154 }
4155
4156 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4157 } else {
4158 // Otherwise the object is contiguous in memory
4159 unsigned BeAlign = reg_top_index == 2 ? 16 : 8;
James Molloy467be602014-05-07 14:45:55 +00004160 if (CGF.CGM.getDataLayout().isBigEndian() &&
4161 (IsHFA || !isAggregateTypeForABI(Ty)) &&
Tim Northovera2ee4332014-03-29 15:09:45 +00004162 Ctx.getTypeSize(Ty) < (BeAlign * 8)) {
4163 int Offset = BeAlign - Ctx.getTypeSize(Ty) / 8;
4164 BaseAddr = CGF.Builder.CreatePtrToInt(BaseAddr, CGF.Int64Ty);
4165
4166 BaseAddr = CGF.Builder.CreateAdd(
4167 BaseAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4168
4169 BaseAddr = CGF.Builder.CreateIntToPtr(BaseAddr, CGF.Int8PtrTy);
4170 }
4171
4172 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4173 }
4174
4175 CGF.EmitBranch(ContBlock);
4176
4177 //=======================================
4178 // Argument was on the stack
4179 //=======================================
4180 CGF.EmitBlock(OnStackBlock);
4181
Craig Topper8a13c412014-05-21 05:09:00 +00004182 llvm::Value *stack_p = nullptr, *OnStackAddr = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004183 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4184 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4185
4186 // Again, stack arguments may need realigmnent. In this case both integer and
4187 // floating-point ones might be affected.
4188 if (!IsIndirect && Ctx.getTypeAlign(Ty) > 64) {
4189 int Align = Ctx.getTypeAlign(Ty) / 8;
4190
4191 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4192
4193 OnStackAddr = CGF.Builder.CreateAdd(
4194 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4195 "align_stack");
4196 OnStackAddr = CGF.Builder.CreateAnd(
4197 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4198 "align_stack");
4199
4200 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4201 }
4202
4203 uint64_t StackSize;
4204 if (IsIndirect)
4205 StackSize = 8;
4206 else
4207 StackSize = Ctx.getTypeSize(Ty) / 8;
4208
4209 // All stack slots are 8 bytes
4210 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4211
4212 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4213 llvm::Value *NewStack =
4214 CGF.Builder.CreateGEP(OnStackAddr, StackSizeC, "new_stack");
4215
4216 // Write the new value of __stack for the next call to va_arg
4217 CGF.Builder.CreateStore(NewStack, stack_p);
4218
4219 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
4220 Ctx.getTypeSize(Ty) < 64) {
4221 int Offset = 8 - Ctx.getTypeSize(Ty) / 8;
4222 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4223
4224 OnStackAddr = CGF.Builder.CreateAdd(
4225 OnStackAddr, llvm::ConstantInt::get(CGF.Int64Ty, Offset), "align_be");
4226
4227 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4228 }
4229
4230 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4231
4232 CGF.EmitBranch(ContBlock);
4233
4234 //=======================================
4235 // Tidy up
4236 //=======================================
4237 CGF.EmitBlock(ContBlock);
4238
4239 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4240 ResAddr->addIncoming(RegAddr, InRegBlock);
4241 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4242
4243 if (IsIndirect)
4244 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4245
4246 return ResAddr;
4247}
4248
Tim Northover573cbee2014-05-24 12:52:07 +00004249llvm::Value *AArch64ABIInfo::EmitDarwinVAArg(llvm::Value *VAListAddr, QualType Ty,
Tim Northovera2ee4332014-03-29 15:09:45 +00004250 CodeGenFunction &CGF) const {
4251 // We do not support va_arg for aggregates or illegal vector types.
4252 // Lower VAArg here for these cases and use the LLVM va_arg instruction for
4253 // other cases.
4254 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
Craig Topper8a13c412014-05-21 05:09:00 +00004255 return nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004256
4257 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
4258 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
4259
Craig Topper8a13c412014-05-21 05:09:00 +00004260 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004261 uint64_t Members = 0;
4262 bool isHA = isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004263
4264 bool isIndirect = false;
4265 // Arguments bigger than 16 bytes which aren't homogeneous aggregates should
4266 // be passed indirectly.
4267 if (Size > 16 && !isHA) {
4268 isIndirect = true;
4269 Size = 8;
4270 Align = 8;
4271 }
4272
4273 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
4274 llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
4275
4276 CGBuilderTy &Builder = CGF.Builder;
4277 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4278 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
4279
4280 if (isEmptyRecord(getContext(), Ty, true)) {
4281 // These are ignored for parameter passing purposes.
4282 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4283 return Builder.CreateBitCast(Addr, PTy);
4284 }
4285
4286 const uint64_t MinABIAlign = 8;
4287 if (Align > MinABIAlign) {
4288 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
4289 Addr = Builder.CreateGEP(Addr, Offset);
4290 llvm::Value *AsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
4291 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, ~(Align - 1));
4292 llvm::Value *Aligned = Builder.CreateAnd(AsInt, Mask);
4293 Addr = Builder.CreateIntToPtr(Aligned, BP, "ap.align");
4294 }
4295
4296 uint64_t Offset = llvm::RoundUpToAlignment(Size, MinABIAlign);
4297 llvm::Value *NextAddr = Builder.CreateGEP(
4298 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next");
4299 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4300
4301 if (isIndirect)
4302 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
4303 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4304 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
4305
4306 return AddrTyped;
4307}
4308
4309//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004310// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004311//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004312
4313namespace {
4314
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004315class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004316public:
4317 enum ABIKind {
4318 APCS = 0,
4319 AAPCS = 1,
4320 AAPCS_VFP
4321 };
4322
4323private:
4324 ABIKind Kind;
Oliver Stannard405bded2014-02-11 09:25:50 +00004325 mutable int VFPRegs[16];
4326 const unsigned NumVFPs;
4327 const unsigned NumGPRs;
4328 mutable unsigned AllocatedGPRs;
4329 mutable unsigned AllocatedVFPs;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004330
4331public:
Oliver Stannard405bded2014-02-11 09:25:50 +00004332 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind),
4333 NumVFPs(16), NumGPRs(4) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004334 setCCs();
Oliver Stannard405bded2014-02-11 09:25:50 +00004335 resetAllocatedRegs();
John McCall882987f2013-02-28 19:01:20 +00004336 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004337
John McCall3480ef22011-08-30 01:42:09 +00004338 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004339 switch (getTarget().getTriple().getEnvironment()) {
4340 case llvm::Triple::Android:
4341 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004342 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004343 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004344 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004345 return true;
4346 default:
4347 return false;
4348 }
John McCall3480ef22011-08-30 01:42:09 +00004349 }
4350
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004351 bool isEABIHF() const {
4352 switch (getTarget().getTriple().getEnvironment()) {
4353 case llvm::Triple::EABIHF:
4354 case llvm::Triple::GNUEABIHF:
4355 return true;
4356 default:
4357 return false;
4358 }
4359 }
4360
Daniel Dunbar020daa92009-09-12 01:00:39 +00004361 ABIKind getABIKind() const { return Kind; }
4362
Tim Northovera484bc02013-10-01 14:34:25 +00004363private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004364 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
James Molloy6f244b62014-05-09 16:21:39 +00004365 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004366 bool &IsCPRC) const;
Manman Renfef9e312012-10-16 19:18:39 +00004367 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004368
Reid Klecknere9f6a712014-10-31 17:10:41 +00004369 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4370 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4371 uint64_t Members) const override;
4372
Craig Topper4f12f102014-03-12 06:41:41 +00004373 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004374
Craig Topper4f12f102014-03-12 06:41:41 +00004375 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4376 CodeGenFunction &CGF) const override;
John McCall882987f2013-02-28 19:01:20 +00004377
4378 llvm::CallingConv::ID getLLVMDefaultCC() const;
4379 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004380 void setCCs();
Oliver Stannard405bded2014-02-11 09:25:50 +00004381
4382 void markAllocatedGPRs(unsigned Alignment, unsigned NumRequired) const;
4383 void markAllocatedVFPs(unsigned Alignment, unsigned NumRequired) const;
4384 void resetAllocatedRegs(void) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004385};
4386
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004387class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4388public:
Chris Lattner2b037972010-07-29 02:01:43 +00004389 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4390 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004391
John McCall3480ef22011-08-30 01:42:09 +00004392 const ARMABIInfo &getABIInfo() const {
4393 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4394 }
4395
Craig Topper4f12f102014-03-12 06:41:41 +00004396 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004397 return 13;
4398 }
Roman Divackyc1617352011-05-18 19:36:54 +00004399
Craig Topper4f12f102014-03-12 06:41:41 +00004400 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004401 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4402 }
4403
Roman Divackyc1617352011-05-18 19:36:54 +00004404 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004405 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004406 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004407
4408 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004409 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004410 return false;
4411 }
John McCall3480ef22011-08-30 01:42:09 +00004412
Craig Topper4f12f102014-03-12 06:41:41 +00004413 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004414 if (getABIInfo().isEABI()) return 88;
4415 return TargetCodeGenInfo::getSizeOfUnwindException();
4416 }
Tim Northovera484bc02013-10-01 14:34:25 +00004417
4418 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004419 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004420 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4421 if (!FD)
4422 return;
4423
4424 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4425 if (!Attr)
4426 return;
4427
4428 const char *Kind;
4429 switch (Attr->getInterrupt()) {
4430 case ARMInterruptAttr::Generic: Kind = ""; break;
4431 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4432 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4433 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4434 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4435 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4436 }
4437
4438 llvm::Function *Fn = cast<llvm::Function>(GV);
4439
4440 Fn->addFnAttr("interrupt", Kind);
4441
4442 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4443 return;
4444
4445 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4446 // however this is not necessarily true on taking any interrupt. Instruct
4447 // the backend to perform a realignment as part of the function prologue.
4448 llvm::AttrBuilder B;
4449 B.addStackAlignmentAttr(8);
4450 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4451 llvm::AttributeSet::get(CGM.getLLVMContext(),
4452 llvm::AttributeSet::FunctionIndex,
4453 B));
4454 }
4455
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004456};
4457
Daniel Dunbard59655c2009-09-12 00:59:49 +00004458}
4459
Chris Lattner22326a12010-07-29 02:31:05 +00004460void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004461 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Renb505d332012-10-31 19:02:26 +00004462 // VFP registers allocated so far.
Manman Ren2a523d82012-10-30 23:21:41 +00004463 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4464 // VFP registers of the appropriate type unallocated then the argument is
4465 // allocated to the lowest-numbered sequence of such registers.
4466 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4467 // unallocated are marked as unavailable.
Oliver Stannard405bded2014-02-11 09:25:50 +00004468 resetAllocatedRegs();
4469
Reid Kleckner40ca9132014-05-13 22:05:45 +00004470 if (getCXXABI().classifyReturnType(FI)) {
4471 if (FI.getReturnInfo().isIndirect())
4472 markAllocatedGPRs(1, 1);
4473 } else {
4474 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic());
4475 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004476 for (auto &I : FI.arguments()) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004477 unsigned PreAllocationVFPs = AllocatedVFPs;
4478 unsigned PreAllocationGPRs = AllocatedGPRs;
Oliver Stannard405bded2014-02-11 09:25:50 +00004479 bool IsCPRC = false;
Manman Ren2a523d82012-10-30 23:21:41 +00004480 // 6.1.2.3 There is one VFP co-processor register class using registers
4481 // s0-s15 (d0-d7) for passing arguments.
James Molloy6f244b62014-05-09 16:21:39 +00004482 I.info = classifyArgumentType(I.type, FI.isVariadic(), IsCPRC);
Oliver Stannard405bded2014-02-11 09:25:50 +00004483
4484 // If we have allocated some arguments onto the stack (due to running
4485 // out of VFP registers), we cannot split an argument between GPRs and
4486 // the stack. If this situation occurs, we add padding to prevent the
Oliver Stannarda3afc692014-05-19 13:10:05 +00004487 // GPRs from being used. In this situation, the current argument could
Oliver Stannard405bded2014-02-11 09:25:50 +00004488 // only be allocated by rule C.8, so rule C.6 would mark these GPRs as
4489 // unusable anyway.
Oliver Stannarde0228512014-07-18 09:09:31 +00004490 // We do not have to do this if the argument is being passed ByVal, as the
4491 // backend can handle that situation correctly.
Oliver Stannard405bded2014-02-11 09:25:50 +00004492 const bool StackUsed = PreAllocationGPRs > NumGPRs || PreAllocationVFPs > NumVFPs;
Oliver Stannarde0228512014-07-18 09:09:31 +00004493 const bool IsByVal = I.info.isIndirect() && I.info.getIndirectByVal();
4494 if (!IsCPRC && PreAllocationGPRs < NumGPRs && AllocatedGPRs > NumGPRs &&
4495 StackUsed && !IsByVal) {
Oliver Stannard405bded2014-02-11 09:25:50 +00004496 llvm::Type *PaddingTy = llvm::ArrayType::get(
4497 llvm::Type::getInt32Ty(getVMContext()), NumGPRs - PreAllocationGPRs);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004498 if (I.info.canHaveCoerceToType()) {
Tim Northover5a1558e2014-11-07 22:30:50 +00004499 I.info = ABIArgInfo::getDirect(I.info.getCoerceToType() /* type */,
4500 0 /* offset */, PaddingTy, true);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004501 } else {
4502 I.info = ABIArgInfo::getDirect(nullptr /* type */, 0 /* offset */,
Tim Northover5a1558e2014-11-07 22:30:50 +00004503 PaddingTy, true);
Oliver Stannarda3afc692014-05-19 13:10:05 +00004504 }
Manman Ren2a523d82012-10-30 23:21:41 +00004505 }
4506 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004507
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004508 // Always honor user-specified calling convention.
4509 if (FI.getCallingConvention() != llvm::CallingConv::C)
4510 return;
4511
John McCall882987f2013-02-28 19:01:20 +00004512 llvm::CallingConv::ID cc = getRuntimeCC();
4513 if (cc != llvm::CallingConv::C)
4514 FI.setEffectiveCallingConvention(cc);
4515}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004516
John McCall882987f2013-02-28 19:01:20 +00004517/// Return the default calling convention that LLVM will use.
4518llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4519 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004520 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004521 return llvm::CallingConv::ARM_AAPCS_VFP;
4522 else if (isEABI())
4523 return llvm::CallingConv::ARM_AAPCS;
4524 else
4525 return llvm::CallingConv::ARM_APCS;
4526}
4527
4528/// Return the calling convention that our ABI would like us to use
4529/// as the C calling convention.
4530llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004531 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004532 case APCS: return llvm::CallingConv::ARM_APCS;
4533 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4534 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004535 }
John McCall882987f2013-02-28 19:01:20 +00004536 llvm_unreachable("bad ABI kind");
4537}
4538
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004539void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004540 assert(getRuntimeCC() == llvm::CallingConv::C);
4541
4542 // Don't muddy up the IR with a ton of explicit annotations if
4543 // they'd just match what LLVM will infer from the triple.
4544 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4545 if (abiCC != getLLVMDefaultCC())
4546 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004547
4548 BuiltinCC = (getABIKind() == APCS ?
4549 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004550}
4551
Manman Renb505d332012-10-31 19:02:26 +00004552/// markAllocatedVFPs - update VFPRegs according to the alignment and
4553/// number of VFP registers (unit is S register) requested.
Oliver Stannard405bded2014-02-11 09:25:50 +00004554void ARMABIInfo::markAllocatedVFPs(unsigned Alignment,
4555 unsigned NumRequired) const {
Manman Renb505d332012-10-31 19:02:26 +00004556 // Early Exit.
Oliver Stannard405bded2014-02-11 09:25:50 +00004557 if (AllocatedVFPs >= 16) {
4558 // We use AllocatedVFP > 16 to signal that some CPRCs were allocated on
4559 // the stack.
4560 AllocatedVFPs = 17;
Manman Renb505d332012-10-31 19:02:26 +00004561 return;
Oliver Stannard405bded2014-02-11 09:25:50 +00004562 }
Manman Renb505d332012-10-31 19:02:26 +00004563 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
4564 // VFP registers of the appropriate type unallocated then the argument is
4565 // allocated to the lowest-numbered sequence of such registers.
4566 for (unsigned I = 0; I < 16; I += Alignment) {
4567 bool FoundSlot = true;
4568 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4569 if (J >= 16 || VFPRegs[J]) {
4570 FoundSlot = false;
4571 break;
4572 }
4573 if (FoundSlot) {
4574 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
4575 VFPRegs[J] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004576 AllocatedVFPs += NumRequired;
Manman Renb505d332012-10-31 19:02:26 +00004577 return;
4578 }
4579 }
4580 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
4581 // unallocated are marked as unavailable.
4582 for (unsigned I = 0; I < 16; I++)
4583 VFPRegs[I] = 1;
Oliver Stannard405bded2014-02-11 09:25:50 +00004584 AllocatedVFPs = 17; // We do not have enough VFP registers.
Manman Renb505d332012-10-31 19:02:26 +00004585}
4586
Oliver Stannard405bded2014-02-11 09:25:50 +00004587/// Update AllocatedGPRs to record the number of general purpose registers
4588/// which have been allocated. It is valid for AllocatedGPRs to go above 4,
4589/// this represents arguments being stored on the stack.
4590void ARMABIInfo::markAllocatedGPRs(unsigned Alignment,
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004591 unsigned NumRequired) const {
Oliver Stannard405bded2014-02-11 09:25:50 +00004592 assert((Alignment == 1 || Alignment == 2) && "Alignment must be 4 or 8 bytes");
4593
4594 if (Alignment == 2 && AllocatedGPRs & 0x1)
4595 AllocatedGPRs += 1;
4596
4597 AllocatedGPRs += NumRequired;
4598}
4599
4600void ARMABIInfo::resetAllocatedRegs(void) const {
4601 AllocatedGPRs = 0;
4602 AllocatedVFPs = 0;
4603 for (unsigned i = 0; i < NumVFPs; ++i)
4604 VFPRegs[i] = 0;
4605}
4606
James Molloy6f244b62014-05-09 16:21:39 +00004607ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
Oliver Stannard405bded2014-02-11 09:25:50 +00004608 bool &IsCPRC) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004609 // We update number of allocated VFPs according to
4610 // 6.1.2.1 The following argument types are VFP CPRCs:
4611 // A single-precision floating-point type (including promoted
4612 // half-precision types); A double-precision floating-point type;
4613 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4614 // with a Base Type of a single- or double-precision floating-point type,
4615 // 64-bit containerized vectors or 128-bit containerized vectors with one
4616 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004617 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004618
Reid Klecknerb1be6832014-11-15 01:41:41 +00004619 Ty = useFirstFieldIfTransparentUnion(Ty);
4620
Manman Renfef9e312012-10-16 19:18:39 +00004621 // Handle illegal vector types here.
4622 if (isIllegalVectorType(Ty)) {
4623 uint64_t Size = getContext().getTypeSize(Ty);
4624 if (Size <= 32) {
4625 llvm::Type *ResType =
4626 llvm::Type::getInt32Ty(getVMContext());
Oliver Stannard405bded2014-02-11 09:25:50 +00004627 markAllocatedGPRs(1, 1);
Tim Northover5a1558e2014-11-07 22:30:50 +00004628 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004629 }
4630 if (Size == 64) {
4631 llvm::Type *ResType = llvm::VectorType::get(
4632 llvm::Type::getInt32Ty(getVMContext()), 2);
Oliver Stannard405bded2014-02-11 09:25:50 +00004633 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic){
4634 markAllocatedGPRs(2, 2);
4635 } else {
4636 markAllocatedVFPs(2, 2);
4637 IsCPRC = true;
4638 }
Tim Northover5a1558e2014-11-07 22:30:50 +00004639 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004640 }
4641 if (Size == 128) {
4642 llvm::Type *ResType = llvm::VectorType::get(
4643 llvm::Type::getInt32Ty(getVMContext()), 4);
Oliver Stannard405bded2014-02-11 09:25:50 +00004644 if (getABIKind() == ARMABIInfo::AAPCS || isVariadic) {
4645 markAllocatedGPRs(2, 4);
4646 } else {
4647 markAllocatedVFPs(4, 4);
4648 IsCPRC = true;
4649 }
Tim Northover5a1558e2014-11-07 22:30:50 +00004650 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004651 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004652 markAllocatedGPRs(1, 1);
Manman Renfef9e312012-10-16 19:18:39 +00004653 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
4654 }
Manman Renb505d332012-10-31 19:02:26 +00004655 // Update VFPRegs for legal vector types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004656 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4657 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4658 uint64_t Size = getContext().getTypeSize(VT);
4659 // Size of a legal vector should be power of 2 and above 64.
4660 markAllocatedVFPs(Size >= 128 ? 4 : 2, Size / 32);
4661 IsCPRC = true;
4662 }
Manman Ren2a523d82012-10-30 23:21:41 +00004663 }
Manman Renb505d332012-10-31 19:02:26 +00004664 // Update VFPRegs for floating point types.
Oliver Stannard405bded2014-02-11 09:25:50 +00004665 if (getABIKind() == ARMABIInfo::AAPCS_VFP && !isVariadic) {
4666 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4667 if (BT->getKind() == BuiltinType::Half ||
4668 BT->getKind() == BuiltinType::Float) {
4669 markAllocatedVFPs(1, 1);
4670 IsCPRC = true;
4671 }
4672 if (BT->getKind() == BuiltinType::Double ||
4673 BT->getKind() == BuiltinType::LongDouble) {
4674 markAllocatedVFPs(2, 2);
4675 IsCPRC = true;
4676 }
4677 }
Manman Ren2a523d82012-10-30 23:21:41 +00004678 }
Manman Renfef9e312012-10-16 19:18:39 +00004679
John McCalla1dee5302010-08-22 10:59:02 +00004680 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004681 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004682 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004683 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004684 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004685
Oliver Stannard405bded2014-02-11 09:25:50 +00004686 unsigned Size = getContext().getTypeSize(Ty);
4687 if (!IsCPRC)
4688 markAllocatedGPRs(Size > 32 ? 2 : 1, (Size + 31) / 32);
Tim Northover5a1558e2014-11-07 22:30:50 +00004689 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4690 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004691 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004692
Oliver Stannard405bded2014-02-11 09:25:50 +00004693 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
4694 markAllocatedGPRs(1, 1);
Tim Northover1060eae2013-06-21 22:49:34 +00004695 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004696 }
Tim Northover1060eae2013-06-21 22:49:34 +00004697
Daniel Dunbar09d33622009-09-14 21:54:03 +00004698 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004699 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004700 return ABIArgInfo::getIgnore();
4701
Tim Northover5a1558e2014-11-07 22:30:50 +00004702 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004703 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4704 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004705 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004706 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004707 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004708 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004709 // Base can be a floating-point or a vector.
4710 if (Base->isVectorType()) {
4711 // ElementSize is in number of floats.
4712 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Oliver Stannard405bded2014-02-11 09:25:50 +00004713 markAllocatedVFPs(ElementSize,
Manman Ren77b02382012-11-06 19:05:29 +00004714 Members * ElementSize);
Manman Ren2a523d82012-10-30 23:21:41 +00004715 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Oliver Stannard405bded2014-02-11 09:25:50 +00004716 markAllocatedVFPs(1, Members);
Manman Ren2a523d82012-10-30 23:21:41 +00004717 else {
4718 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
4719 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Oliver Stannard405bded2014-02-11 09:25:50 +00004720 markAllocatedVFPs(2, Members * 2);
Manman Ren2a523d82012-10-30 23:21:41 +00004721 }
Oliver Stannard405bded2014-02-11 09:25:50 +00004722 IsCPRC = true;
Tim Northover5a1558e2014-11-07 22:30:50 +00004723 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004724 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004725 }
4726
Manman Ren6c30e132012-08-13 21:23:55 +00004727 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004728 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4729 // most 8-byte. We realign the indirect argument if type alignment is bigger
4730 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004731 uint64_t ABIAlign = 4;
4732 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4733 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4734 getABIKind() == ARMABIInfo::AAPCS)
4735 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren8cd99812012-11-06 04:58:01 +00004736 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Oliver Stannard3f32b9b2014-06-27 13:59:27 +00004737 // Update Allocated GPRs. Since this is only used when the size of the
4738 // argument is greater than 64 bytes, this will always use up any available
4739 // registers (of which there are 4). We also don't care about getting the
4740 // alignment right, because general-purpose registers cannot be back-filled.
4741 markAllocatedGPRs(1, 4);
Oliver Stannard7c3c09e2014-03-12 14:02:50 +00004742 return ABIArgInfo::getIndirect(TyAlign, /*ByVal=*/true,
Manman Ren77b02382012-11-06 19:05:29 +00004743 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004744 }
4745
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004746 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004747 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004748 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004749 // FIXME: Try to match the types of the arguments more accurately where
4750 // we can.
4751 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004752 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4753 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Oliver Stannard405bded2014-02-11 09:25:50 +00004754 markAllocatedGPRs(1, SizeRegs);
Manman Ren6fdb1582012-06-25 22:04:00 +00004755 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004756 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4757 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Oliver Stannard405bded2014-02-11 09:25:50 +00004758 markAllocatedGPRs(2, SizeRegs * 2);
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004759 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004760
Tim Northover5a1558e2014-11-07 22:30:50 +00004761 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004762}
4763
Chris Lattner458b2aa2010-07-29 02:16:43 +00004764static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004765 llvm::LLVMContext &VMContext) {
4766 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4767 // is called integer-like if its size is less than or equal to one word, and
4768 // the offset of each of its addressable sub-fields is zero.
4769
4770 uint64_t Size = Context.getTypeSize(Ty);
4771
4772 // Check that the type fits in a word.
4773 if (Size > 32)
4774 return false;
4775
4776 // FIXME: Handle vector types!
4777 if (Ty->isVectorType())
4778 return false;
4779
Daniel Dunbard53bac72009-09-14 02:20:34 +00004780 // Float types are never treated as "integer like".
4781 if (Ty->isRealFloatingType())
4782 return false;
4783
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004784 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004785 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004786 return true;
4787
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004788 // Small complex integer types are "integer like".
4789 if (const ComplexType *CT = Ty->getAs<ComplexType>())
4790 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004791
4792 // Single element and zero sized arrays should be allowed, by the definition
4793 // above, but they are not.
4794
4795 // Otherwise, it must be a record type.
4796 const RecordType *RT = Ty->getAs<RecordType>();
4797 if (!RT) return false;
4798
4799 // Ignore records with flexible arrays.
4800 const RecordDecl *RD = RT->getDecl();
4801 if (RD->hasFlexibleArrayMember())
4802 return false;
4803
4804 // Check that all sub-fields are at offset 0, and are themselves "integer
4805 // like".
4806 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
4807
4808 bool HadField = false;
4809 unsigned idx = 0;
4810 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4811 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00004812 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004813
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004814 // Bit-fields are not addressable, we only need to verify they are "integer
4815 // like". We still have to disallow a subsequent non-bitfield, for example:
4816 // struct { int : 0; int x }
4817 // is non-integer like according to gcc.
4818 if (FD->isBitField()) {
4819 if (!RD->isUnion())
4820 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004821
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004822 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4823 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004824
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004825 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004826 }
4827
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004828 // Check if this field is at offset 0.
4829 if (Layout.getFieldOffset(idx) != 0)
4830 return false;
4831
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004832 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
4833 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004834
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00004835 // Only allow at most one field in a structure. This doesn't match the
4836 // wording above, but follows gcc in situations with a field following an
4837 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004838 if (!RD->isUnion()) {
4839 if (HadField)
4840 return false;
4841
4842 HadField = true;
4843 }
4844 }
4845
4846 return true;
4847}
4848
Oliver Stannard405bded2014-02-11 09:25:50 +00004849ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
4850 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00004851 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004852
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004853 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004854 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004855
Daniel Dunbar19964db2010-09-23 01:54:32 +00004856 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004857 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
4858 markAllocatedGPRs(1, 1);
Daniel Dunbar19964db2010-09-23 01:54:32 +00004859 return ABIArgInfo::getIndirect(0);
Oliver Stannard405bded2014-02-11 09:25:50 +00004860 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00004861
John McCalla1dee5302010-08-22 10:59:02 +00004862 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004863 // Treat an enum type as its underlying type.
4864 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4865 RetTy = EnumTy->getDecl()->getIntegerType();
4866
Tim Northover5a1558e2014-11-07 22:30:50 +00004867 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4868 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00004869 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004870
4871 // Are we following APCS?
4872 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00004873 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004874 return ABIArgInfo::getIgnore();
4875
Daniel Dunbareedf1512010-02-01 23:31:19 +00004876 // Complex types are all returned as packed integers.
4877 //
4878 // FIXME: Consider using 2 x vector types if the back end handles them
4879 // correctly.
4880 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004881 return ABIArgInfo::getDirect(llvm::IntegerType::get(
4882 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00004883
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004884 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004885 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004886 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004887 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004888 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004889 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004890 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00004891 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4892 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004893 }
4894
4895 // Otherwise return in memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00004896 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004897 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004898 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004899
4900 // Otherwise this is an AAPCS variant.
4901
Chris Lattner458b2aa2010-07-29 02:16:43 +00004902 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004903 return ABIArgInfo::getIgnore();
4904
Bob Wilson1d9269a2011-11-02 04:51:36 +00004905 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00004906 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00004907 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004908 uint64_t Members;
4909 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004910 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00004911 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00004912 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004913 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00004914 }
4915
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004916 // Aggregates <= 4 bytes are returned in r0; other aggregates
4917 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004918 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004919 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00004920 if (getDataLayout().isBigEndian())
4921 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00004922 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00004923
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004924 // Return in the smallest viable integer type.
4925 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00004926 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004927 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00004928 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
4929 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00004930 }
4931
Oliver Stannard405bded2014-02-11 09:25:50 +00004932 markAllocatedGPRs(1, 1);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004933 return ABIArgInfo::getIndirect(0);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004934}
4935
Manman Renfef9e312012-10-16 19:18:39 +00004936/// isIllegalVector - check whether Ty is an illegal vector type.
4937bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
4938 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4939 // Check whether VT is legal.
4940 unsigned NumElements = VT->getNumElements();
4941 uint64_t Size = getContext().getTypeSize(VT);
4942 // NumElements should be power of 2.
4943 if ((NumElements & (NumElements - 1)) != 0)
4944 return true;
4945 // Size should be greater than 32 bits.
4946 return Size <= 32;
4947 }
4948 return false;
4949}
4950
Reid Klecknere9f6a712014-10-31 17:10:41 +00004951bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4952 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
4953 // double, or 64-bit or 128-bit vectors.
4954 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4955 if (BT->getKind() == BuiltinType::Float ||
4956 BT->getKind() == BuiltinType::Double ||
4957 BT->getKind() == BuiltinType::LongDouble)
4958 return true;
4959 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4960 unsigned VecSize = getContext().getTypeSize(VT);
4961 if (VecSize == 64 || VecSize == 128)
4962 return true;
4963 }
4964 return false;
4965}
4966
4967bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4968 uint64_t Members) const {
4969 return Members <= 4;
4970}
4971
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004972llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner5e016ae2010-06-27 07:15:29 +00004973 CodeGenFunction &CGF) const {
Chris Lattnerece04092012-02-07 00:39:47 +00004974 llvm::Type *BP = CGF.Int8PtrTy;
4975 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004976
4977 CGBuilderTy &Builder = CGF.Builder;
Chris Lattnerece04092012-02-07 00:39:47 +00004978 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004979 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rencca54d02012-10-16 19:01:37 +00004980
Tim Northover1711cc92013-06-21 23:05:33 +00004981 if (isEmptyRecord(getContext(), Ty, true)) {
4982 // These are ignored for parameter passing purposes.
4983 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4984 return Builder.CreateBitCast(Addr, PTy);
4985 }
4986
Manman Rencca54d02012-10-16 19:01:37 +00004987 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindola11d994b2011-08-02 22:33:37 +00004988 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Renfef9e312012-10-16 19:18:39 +00004989 bool IsIndirect = false;
Manman Rencca54d02012-10-16 19:01:37 +00004990
4991 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
4992 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren67effb92012-10-16 19:51:48 +00004993 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
4994 getABIKind() == ARMABIInfo::AAPCS)
4995 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
4996 else
4997 TyAlign = 4;
Manman Renfef9e312012-10-16 19:18:39 +00004998 // Use indirect if size of the illegal vector is bigger than 16 bytes.
4999 if (isIllegalVectorType(Ty) && Size > 16) {
5000 IsIndirect = true;
5001 Size = 4;
5002 TyAlign = 4;
5003 }
Manman Rencca54d02012-10-16 19:01:37 +00005004
5005 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindola11d994b2011-08-02 22:33:37 +00005006 if (TyAlign > 4) {
5007 assert((TyAlign & (TyAlign - 1)) == 0 &&
5008 "Alignment is not power of 2!");
5009 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
5010 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
5011 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rencca54d02012-10-16 19:01:37 +00005012 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindola11d994b2011-08-02 22:33:37 +00005013 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005014
5015 uint64_t Offset =
Manman Rencca54d02012-10-16 19:01:37 +00005016 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005017 llvm::Value *NextAddr =
Chris Lattner5e016ae2010-06-27 07:15:29 +00005018 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005019 "ap.next");
5020 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5021
Manman Renfef9e312012-10-16 19:18:39 +00005022 if (IsIndirect)
5023 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren67effb92012-10-16 19:51:48 +00005024 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rencca54d02012-10-16 19:01:37 +00005025 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
5026 // may not be correctly aligned for the vector type. We create an aligned
5027 // temporary space and copy the content over from ap.cur to the temporary
5028 // space. This is necessary if the natural alignment of the type is greater
5029 // than the ABI alignment.
5030 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
5031 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
5032 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
5033 "var.align");
5034 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
5035 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
5036 Builder.CreateMemCpy(Dst, Src,
5037 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
5038 TyAlign, false);
5039 Addr = AlignedTemp; //The content is in aligned location.
5040 }
5041 llvm::Type *PTy =
5042 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5043 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5044
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005045 return AddrTyped;
5046}
5047
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005048namespace {
5049
Derek Schuffa2020962012-10-16 22:30:41 +00005050class NaClARMABIInfo : public ABIInfo {
5051 public:
5052 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5053 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005054 void computeInfo(CGFunctionInfo &FI) const override;
5055 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5056 CodeGenFunction &CGF) const override;
Derek Schuffa2020962012-10-16 22:30:41 +00005057 private:
5058 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
5059 ARMABIInfo NInfo; // Used for everything else.
5060};
5061
5062class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
5063 public:
5064 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
5065 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
5066};
5067
Benjamin Kramer1cdb23d2012-10-20 13:02:06 +00005068}
5069
Derek Schuffa2020962012-10-16 22:30:41 +00005070void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5071 if (FI.getASTCallingConvention() == CC_PnaclCall)
5072 PInfo.computeInfo(FI);
5073 else
5074 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
5075}
5076
5077llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5078 CodeGenFunction &CGF) const {
5079 // Always use the native convention; calling pnacl-style varargs functions
5080 // is unsupported.
5081 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
5082}
5083
Chris Lattner0cf24192010-06-28 20:05:43 +00005084//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005085// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005086//===----------------------------------------------------------------------===//
5087
5088namespace {
5089
Justin Holewinski83e96682012-05-24 17:43:12 +00005090class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005091public:
Justin Holewinski36837432013-03-30 14:38:24 +00005092 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005093
5094 ABIArgInfo classifyReturnType(QualType RetTy) const;
5095 ABIArgInfo classifyArgumentType(QualType Ty) const;
5096
Craig Topper4f12f102014-03-12 06:41:41 +00005097 void computeInfo(CGFunctionInfo &FI) const override;
5098 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5099 CodeGenFunction &CFG) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005100};
5101
Justin Holewinski83e96682012-05-24 17:43:12 +00005102class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005103public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005104 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5105 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005106
5107 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5108 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005109private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005110 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5111 // resulting MDNode to the nvvm.annotations MDNode.
5112 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005113};
5114
Justin Holewinski83e96682012-05-24 17:43:12 +00005115ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005116 if (RetTy->isVoidType())
5117 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005118
5119 // note: this is different from default ABI
5120 if (!RetTy->isScalarType())
5121 return ABIArgInfo::getDirect();
5122
5123 // Treat an enum type as its underlying type.
5124 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5125 RetTy = EnumTy->getDecl()->getIntegerType();
5126
5127 return (RetTy->isPromotableIntegerType() ?
5128 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005129}
5130
Justin Holewinski83e96682012-05-24 17:43:12 +00005131ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005132 // Treat an enum type as its underlying type.
5133 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5134 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005135
Eli Bendersky95338a02014-10-29 13:43:21 +00005136 // Return aggregates type as indirect by value
5137 if (isAggregateTypeForABI(Ty))
5138 return ABIArgInfo::getIndirect(0, /* byval */ true);
5139
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005140 return (Ty->isPromotableIntegerType() ?
5141 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005142}
5143
Justin Holewinski83e96682012-05-24 17:43:12 +00005144void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005145 if (!getCXXABI().classifyReturnType(FI))
5146 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005147 for (auto &I : FI.arguments())
5148 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005149
5150 // Always honor user-specified calling convention.
5151 if (FI.getCallingConvention() != llvm::CallingConv::C)
5152 return;
5153
John McCall882987f2013-02-28 19:01:20 +00005154 FI.setEffectiveCallingConvention(getRuntimeCC());
5155}
5156
Justin Holewinski83e96682012-05-24 17:43:12 +00005157llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5158 CodeGenFunction &CFG) const {
5159 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005160}
5161
Justin Holewinski83e96682012-05-24 17:43:12 +00005162void NVPTXTargetCodeGenInfo::
5163SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5164 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005165 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5166 if (!FD) return;
5167
5168 llvm::Function *F = cast<llvm::Function>(GV);
5169
5170 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005171 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005172 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005173 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005174 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005175 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005176 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5177 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005178 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005179 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005180 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005181 }
Justin Holewinski38031972011-10-05 17:58:44 +00005182
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005183 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005184 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005185 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005186 // __global__ functions cannot be called from the device, we do not
5187 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005188 if (FD->hasAttr<CUDAGlobalAttr>()) {
5189 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5190 addNVVMMetadata(F, "kernel", 1);
5191 }
5192 if (FD->hasAttr<CUDALaunchBoundsAttr>()) {
5193 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
5194 addNVVMMetadata(F, "maxntidx",
5195 FD->getAttr<CUDALaunchBoundsAttr>()->getMaxThreads());
5196 // min blocks is a default argument for CUDALaunchBoundsAttr, so getting a
5197 // zero value from getMinBlocks either means it was not specified in
5198 // __launch_bounds__ or the user specified a 0 value. In both cases, we
5199 // don't have to add a PTX directive.
5200 int MinCTASM = FD->getAttr<CUDALaunchBoundsAttr>()->getMinBlocks();
5201 if (MinCTASM > 0) {
5202 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5203 addNVVMMetadata(F, "minctasm", MinCTASM);
5204 }
5205 }
Justin Holewinski38031972011-10-05 17:58:44 +00005206 }
5207}
5208
Eli Benderskye06a2c42014-04-15 16:57:05 +00005209void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5210 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005211 llvm::Module *M = F->getParent();
5212 llvm::LLVMContext &Ctx = M->getContext();
5213
5214 // Get "nvvm.annotations" metadata node
5215 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5216
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005217 llvm::Metadata *MDVals[] = {
5218 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5219 llvm::ConstantAsMetadata::get(
5220 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005221 // Append metadata to nvvm.annotations
5222 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5223}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005224}
5225
5226//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005227// SystemZ ABI Implementation
5228//===----------------------------------------------------------------------===//
5229
5230namespace {
5231
5232class SystemZABIInfo : public ABIInfo {
5233public:
5234 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5235
5236 bool isPromotableIntegerType(QualType Ty) const;
5237 bool isCompoundType(QualType Ty) const;
5238 bool isFPArgumentType(QualType Ty) const;
5239
5240 ABIArgInfo classifyReturnType(QualType RetTy) const;
5241 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5242
Craig Topper4f12f102014-03-12 06:41:41 +00005243 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005244 if (!getCXXABI().classifyReturnType(FI))
5245 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005246 for (auto &I : FI.arguments())
5247 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005248 }
5249
Craig Topper4f12f102014-03-12 06:41:41 +00005250 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5251 CodeGenFunction &CGF) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005252};
5253
5254class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5255public:
5256 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
5257 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
5258};
5259
5260}
5261
5262bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5263 // Treat an enum type as its underlying type.
5264 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5265 Ty = EnumTy->getDecl()->getIntegerType();
5266
5267 // Promotable integer types are required to be promoted by the ABI.
5268 if (Ty->isPromotableIntegerType())
5269 return true;
5270
5271 // 32-bit values must also be promoted.
5272 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5273 switch (BT->getKind()) {
5274 case BuiltinType::Int:
5275 case BuiltinType::UInt:
5276 return true;
5277 default:
5278 return false;
5279 }
5280 return false;
5281}
5282
5283bool SystemZABIInfo::isCompoundType(QualType Ty) const {
5284 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
5285}
5286
5287bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5288 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5289 switch (BT->getKind()) {
5290 case BuiltinType::Float:
5291 case BuiltinType::Double:
5292 return true;
5293 default:
5294 return false;
5295 }
5296
5297 if (const RecordType *RT = Ty->getAsStructureType()) {
5298 const RecordDecl *RD = RT->getDecl();
5299 bool Found = false;
5300
5301 // If this is a C++ record, check the bases first.
5302 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005303 for (const auto &I : CXXRD->bases()) {
5304 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005305
5306 // Empty bases don't affect things either way.
5307 if (isEmptyRecord(getContext(), Base, true))
5308 continue;
5309
5310 if (Found)
5311 return false;
5312 Found = isFPArgumentType(Base);
5313 if (!Found)
5314 return false;
5315 }
5316
5317 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005318 for (const auto *FD : RD->fields()) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005319 // Empty bitfields don't affect things either way.
5320 // Unlike isSingleElementStruct(), empty structure and array fields
5321 // do count. So do anonymous bitfields that aren't zero-sized.
5322 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5323 return true;
5324
5325 // Unlike isSingleElementStruct(), arrays do not count.
5326 // Nested isFPArgumentType structures still do though.
5327 if (Found)
5328 return false;
5329 Found = isFPArgumentType(FD->getType());
5330 if (!Found)
5331 return false;
5332 }
5333
5334 // Unlike isSingleElementStruct(), trailing padding is allowed.
5335 // An 8-byte aligned struct s { float f; } is passed as a double.
5336 return Found;
5337 }
5338
5339 return false;
5340}
5341
5342llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5343 CodeGenFunction &CGF) const {
5344 // Assume that va_list type is correct; should be pointer to LLVM type:
5345 // struct {
5346 // i64 __gpr;
5347 // i64 __fpr;
5348 // i8 *__overflow_arg_area;
5349 // i8 *__reg_save_area;
5350 // };
5351
5352 // Every argument occupies 8 bytes and is passed by preference in either
5353 // GPRs or FPRs.
5354 Ty = CGF.getContext().getCanonicalType(Ty);
5355 ABIArgInfo AI = classifyArgumentType(Ty);
5356 bool InFPRs = isFPArgumentType(Ty);
5357
5358 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
5359 bool IsIndirect = AI.isIndirect();
5360 unsigned UnpaddedBitSize;
5361 if (IsIndirect) {
5362 APTy = llvm::PointerType::getUnqual(APTy);
5363 UnpaddedBitSize = 64;
5364 } else
5365 UnpaddedBitSize = getContext().getTypeSize(Ty);
5366 unsigned PaddedBitSize = 64;
5367 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
5368
5369 unsigned PaddedSize = PaddedBitSize / 8;
5370 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
5371
5372 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
5373 if (InFPRs) {
5374 MaxRegs = 4; // Maximum of 4 FPR arguments
5375 RegCountField = 1; // __fpr
5376 RegSaveIndex = 16; // save offset for f0
5377 RegPadding = 0; // floats are passed in the high bits of an FPR
5378 } else {
5379 MaxRegs = 5; // Maximum of 5 GPR arguments
5380 RegCountField = 0; // __gpr
5381 RegSaveIndex = 2; // save offset for r2
5382 RegPadding = Padding; // values are passed in the low bits of a GPR
5383 }
5384
5385 llvm::Value *RegCountPtr =
5386 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
5387 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
5388 llvm::Type *IndexTy = RegCount->getType();
5389 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5390 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005391 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005392
5393 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5394 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5395 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5396 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5397
5398 // Emit code to load the value if it was passed in registers.
5399 CGF.EmitBlock(InRegBlock);
5400
5401 // Work out the address of an argument register.
5402 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
5403 llvm::Value *ScaledRegCount =
5404 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5405 llvm::Value *RegBase =
5406 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
5407 llvm::Value *RegOffset =
5408 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
5409 llvm::Value *RegSaveAreaPtr =
5410 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
5411 llvm::Value *RegSaveArea =
5412 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
5413 llvm::Value *RawRegAddr =
5414 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
5415 llvm::Value *RegAddr =
5416 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
5417
5418 // Update the register count
5419 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5420 llvm::Value *NewRegCount =
5421 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5422 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5423 CGF.EmitBranch(ContBlock);
5424
5425 // Emit code to load the value if it was passed in memory.
5426 CGF.EmitBlock(InMemBlock);
5427
5428 // Work out the address of a stack argument.
5429 llvm::Value *OverflowArgAreaPtr =
5430 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
5431 llvm::Value *OverflowArgArea =
5432 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
5433 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
5434 llvm::Value *RawMemAddr =
5435 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
5436 llvm::Value *MemAddr =
5437 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
5438
5439 // Update overflow_arg_area_ptr pointer
5440 llvm::Value *NewOverflowArgArea =
5441 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
5442 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5443 CGF.EmitBranch(ContBlock);
5444
5445 // Return the appropriate result.
5446 CGF.EmitBlock(ContBlock);
5447 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
5448 ResAddr->addIncoming(RegAddr, InRegBlock);
5449 ResAddr->addIncoming(MemAddr, InMemBlock);
5450
5451 if (IsIndirect)
5452 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
5453
5454 return ResAddr;
5455}
5456
Ulrich Weigand47445072013-05-06 16:26:41 +00005457ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5458 if (RetTy->isVoidType())
5459 return ABIArgInfo::getIgnore();
5460 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
5461 return ABIArgInfo::getIndirect(0);
5462 return (isPromotableIntegerType(RetTy) ?
5463 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5464}
5465
5466ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5467 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005468 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigand47445072013-05-06 16:26:41 +00005469 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
5470
5471 // Integers and enums are extended to full register width.
5472 if (isPromotableIntegerType(Ty))
5473 return ABIArgInfo::getExtend();
5474
5475 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
5476 uint64_t Size = getContext().getTypeSize(Ty);
5477 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
Richard Sandifordcdd86882013-12-04 09:59:57 +00005478 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005479
5480 // Handle small structures.
5481 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5482 // Structures with flexible arrays have variable length, so really
5483 // fail the size test above.
5484 const RecordDecl *RD = RT->getDecl();
5485 if (RD->hasFlexibleArrayMember())
Richard Sandifordcdd86882013-12-04 09:59:57 +00005486 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005487
5488 // The structure is passed as an unextended integer, a float, or a double.
5489 llvm::Type *PassTy;
5490 if (isFPArgumentType(Ty)) {
5491 assert(Size == 32 || Size == 64);
5492 if (Size == 32)
5493 PassTy = llvm::Type::getFloatTy(getVMContext());
5494 else
5495 PassTy = llvm::Type::getDoubleTy(getVMContext());
5496 } else
5497 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5498 return ABIArgInfo::getDirect(PassTy);
5499 }
5500
5501 // Non-structure compounds are passed indirectly.
5502 if (isCompoundType(Ty))
Richard Sandifordcdd86882013-12-04 09:59:57 +00005503 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005504
Craig Topper8a13c412014-05-21 05:09:00 +00005505 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005506}
5507
5508//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005509// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005510//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005511
5512namespace {
5513
5514class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5515public:
Chris Lattner2b037972010-07-29 02:01:43 +00005516 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5517 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005518 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005519 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005520};
5521
5522}
5523
5524void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5525 llvm::GlobalValue *GV,
5526 CodeGen::CodeGenModule &M) const {
5527 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5528 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5529 // Handle 'interrupt' attribute:
5530 llvm::Function *F = cast<llvm::Function>(GV);
5531
5532 // Step 1: Set ISR calling convention.
5533 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5534
5535 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005536 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005537
5538 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005539 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005540 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5541 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005542 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005543 }
5544}
5545
Chris Lattner0cf24192010-06-28 20:05:43 +00005546//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005547// MIPS ABI Implementation. This works for both little-endian and
5548// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005549//===----------------------------------------------------------------------===//
5550
John McCall943fae92010-05-27 06:19:26 +00005551namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005552class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005553 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005554 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5555 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005556 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005557 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005558 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005559 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005560public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005561 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005562 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005563 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005564
5565 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005566 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005567 void computeInfo(CGFunctionInfo &FI) const override;
5568 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5569 CodeGenFunction &CGF) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005570};
5571
John McCall943fae92010-05-27 06:19:26 +00005572class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005573 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005574public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005575 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5576 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005577 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005578
Craig Topper4f12f102014-03-12 06:41:41 +00005579 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005580 return 29;
5581 }
5582
Reed Kotler373feca2013-01-16 17:10:28 +00005583 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005584 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005585 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5586 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005587 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005588 if (FD->hasAttr<Mips16Attr>()) {
5589 Fn->addFnAttr("mips16");
5590 }
5591 else if (FD->hasAttr<NoMips16Attr>()) {
5592 Fn->addFnAttr("nomips16");
5593 }
Reed Kotler373feca2013-01-16 17:10:28 +00005594 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005595
John McCall943fae92010-05-27 06:19:26 +00005596 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005597 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005598
Craig Topper4f12f102014-03-12 06:41:41 +00005599 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005600 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005601 }
John McCall943fae92010-05-27 06:19:26 +00005602};
5603}
5604
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005605void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005606 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005607 llvm::IntegerType *IntTy =
5608 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005609
5610 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5611 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5612 ArgList.push_back(IntTy);
5613
5614 // If necessary, add one more integer type to ArgList.
5615 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5616
5617 if (R)
5618 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005619}
5620
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005621// In N32/64, an aligned double precision floating point field is passed in
5622// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005623llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005624 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5625
5626 if (IsO32) {
5627 CoerceToIntArgs(TySize, ArgList);
5628 return llvm::StructType::get(getVMContext(), ArgList);
5629 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005630
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005631 if (Ty->isComplexType())
5632 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005633
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005634 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005635
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005636 // Unions/vectors are passed in integer registers.
5637 if (!RT || !RT->isStructureOrClassType()) {
5638 CoerceToIntArgs(TySize, ArgList);
5639 return llvm::StructType::get(getVMContext(), ArgList);
5640 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005641
5642 const RecordDecl *RD = RT->getDecl();
5643 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005644 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005645
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005646 uint64_t LastOffset = 0;
5647 unsigned idx = 0;
5648 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5649
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005650 // Iterate over fields in the struct/class and check if there are any aligned
5651 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005652 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5653 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005654 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005655 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5656
5657 if (!BT || BT->getKind() != BuiltinType::Double)
5658 continue;
5659
5660 uint64_t Offset = Layout.getFieldOffset(idx);
5661 if (Offset % 64) // Ignore doubles that are not aligned.
5662 continue;
5663
5664 // Add ((Offset - LastOffset) / 64) args of type i64.
5665 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5666 ArgList.push_back(I64);
5667
5668 // Add double type.
5669 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5670 LastOffset = Offset + 64;
5671 }
5672
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005673 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5674 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005675
5676 return llvm::StructType::get(getVMContext(), ArgList);
5677}
5678
Akira Hatanakaddd66342013-10-29 18:41:15 +00005679llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5680 uint64_t Offset) const {
5681 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005682 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005683
Akira Hatanakaddd66342013-10-29 18:41:15 +00005684 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005685}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005686
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005687ABIArgInfo
5688MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanaka1632af62012-01-09 19:31:25 +00005689 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005690 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005691 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005692
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005693 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5694 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005695 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5696 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005697
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005698 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005699 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005700 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005701 return ABIArgInfo::getIgnore();
5702
Mark Lacey3825e832013-10-06 01:33:34 +00005703 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005704 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00005705 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005706 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005707
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005708 // If we have reached here, aggregates are passed directly by coercing to
5709 // another structure type. Padding is inserted if the offset of the
5710 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005711 ABIArgInfo ArgInfo =
5712 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5713 getPaddingType(OrigOffset, CurrOffset));
5714 ArgInfo.setInReg(true);
5715 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005716 }
5717
5718 // Treat an enum type as its underlying type.
5719 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5720 Ty = EnumTy->getDecl()->getIntegerType();
5721
Daniel Sanders5b445b32014-10-24 14:42:42 +00005722 // All integral types are promoted to the GPR width.
5723 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005724 return ABIArgInfo::getExtend();
5725
Akira Hatanakaddd66342013-10-29 18:41:15 +00005726 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005727 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005728}
5729
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005730llvm::Type*
5731MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005732 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005733 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005734
Akira Hatanakab6f74432012-02-09 18:49:26 +00005735 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005736 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005737 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5738 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005739
Akira Hatanakab6f74432012-02-09 18:49:26 +00005740 // N32/64 returns struct/classes in floating point registers if the
5741 // following conditions are met:
5742 // 1. The size of the struct/class is no larger than 128-bit.
5743 // 2. The struct/class has one or two fields all of which are floating
5744 // point types.
5745 // 3. The offset of the first field is zero (this follows what gcc does).
5746 //
5747 // Any other composite results are returned in integer registers.
5748 //
5749 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5750 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5751 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005752 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005753
Akira Hatanakab6f74432012-02-09 18:49:26 +00005754 if (!BT || !BT->isFloatingPoint())
5755 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005756
David Blaikie2d7c57e2012-04-30 02:36:29 +00005757 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005758 }
5759
5760 if (b == e)
5761 return llvm::StructType::get(getVMContext(), RTList,
5762 RD->hasAttr<PackedAttr>());
5763
5764 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005765 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005766 }
5767
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005768 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005769 return llvm::StructType::get(getVMContext(), RTList);
5770}
5771
Akira Hatanakab579fe52011-06-02 00:09:17 +00005772ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005773 uint64_t Size = getContext().getTypeSize(RetTy);
5774
Daniel Sandersed39f582014-09-04 13:28:14 +00005775 if (RetTy->isVoidType())
5776 return ABIArgInfo::getIgnore();
5777
5778 // O32 doesn't treat zero-sized structs differently from other structs.
5779 // However, N32/N64 ignores zero sized return values.
5780 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005781 return ABIArgInfo::getIgnore();
5782
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005783 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005784 if (Size <= 128) {
5785 if (RetTy->isAnyComplexType())
5786 return ABIArgInfo::getDirect();
5787
Daniel Sanderse5018b62014-09-04 15:05:39 +00005788 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00005789 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00005790 if (!IsO32 ||
5791 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
5792 ABIArgInfo ArgInfo =
5793 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
5794 ArgInfo.setInReg(true);
5795 return ArgInfo;
5796 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005797 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00005798
5799 return ABIArgInfo::getIndirect(0);
5800 }
5801
5802 // Treat an enum type as its underlying type.
5803 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5804 RetTy = EnumTy->getDecl()->getIntegerType();
5805
5806 return (RetTy->isPromotableIntegerType() ?
5807 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5808}
5809
5810void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00005811 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00005812 if (!getCXXABI().classifyReturnType(FI))
5813 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00005814
5815 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005816 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00005817
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005818 for (auto &I : FI.arguments())
5819 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00005820}
5821
5822llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5823 CodeGenFunction &CGF) const {
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005824 llvm::Type *BP = CGF.Int8PtrTy;
5825 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00005826
5827 // Integer arguments are promoted 32-bit on O32 and 64-bit on N32/N64.
5828 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
5829 if (Ty->isIntegerType() &&
5830 CGF.getContext().getIntWidth(Ty) < SlotSizeInBits) {
5831 Ty = CGF.getContext().getIntTypeForBitwidth(SlotSizeInBits,
5832 Ty->isSignedIntegerType());
5833 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005834
5835 CGBuilderTy &Builder = CGF.Builder;
5836 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5837 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Daniel Sanders8d36a612014-09-22 13:27:06 +00005838 int64_t TypeAlign =
5839 std::min(getContext().getTypeAlign(Ty) / 8, StackAlignInBytes);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005840 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5841 llvm::Value *AddrTyped;
5842 unsigned PtrWidth = getTarget().getPointerWidth(0);
5843 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
5844
5845 if (TypeAlign > MinABIStackAlignInBytes) {
5846 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
5847 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
5848 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
5849 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
5850 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
5851 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
5852 }
5853 else
5854 AddrTyped = Builder.CreateBitCast(Addr, PTy);
5855
5856 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
5857 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Daniel Sanders59229dc2014-11-19 10:01:35 +00005858 unsigned ArgSizeInBits = CGF.getContext().getTypeSize(Ty);
5859 uint64_t Offset = llvm::RoundUpToAlignment(ArgSizeInBits / 8, TypeAlign);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00005860 llvm::Value *NextAddr =
5861 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
5862 "ap.next");
5863 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5864
5865 return AddrTyped;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005866}
5867
John McCall943fae92010-05-27 06:19:26 +00005868bool
5869MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5870 llvm::Value *Address) const {
5871 // This information comes from gcc's implementation, which seems to
5872 // as canonical as it gets.
5873
John McCall943fae92010-05-27 06:19:26 +00005874 // Everything on MIPS is 4 bytes. Double-precision FP registers
5875 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005876 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00005877
5878 // 0-31 are the general purpose registers, $0 - $31.
5879 // 32-63 are the floating-point registers, $f0 - $f31.
5880 // 64 and 65 are the multiply/divide registers, $hi and $lo.
5881 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00005882 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00005883
5884 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
5885 // They are one bit wide and ignored here.
5886
5887 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
5888 // (coprocessor 1 is the FP unit)
5889 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
5890 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
5891 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005892 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00005893 return false;
5894}
5895
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005896//===----------------------------------------------------------------------===//
5897// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
5898// Currently subclassed only to implement custom OpenCL C function attribute
5899// handling.
5900//===----------------------------------------------------------------------===//
5901
5902namespace {
5903
5904class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
5905public:
5906 TCETargetCodeGenInfo(CodeGenTypes &CGT)
5907 : DefaultTargetCodeGenInfo(CGT) {}
5908
Craig Topper4f12f102014-03-12 06:41:41 +00005909 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5910 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005911};
5912
5913void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
5914 llvm::GlobalValue *GV,
5915 CodeGen::CodeGenModule &M) const {
5916 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5917 if (!FD) return;
5918
5919 llvm::Function *F = cast<llvm::Function>(GV);
5920
David Blaikiebbafb8a2012-03-11 07:00:24 +00005921 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005922 if (FD->hasAttr<OpenCLKernelAttr>()) {
5923 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005924 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00005925 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
5926 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005927 // Convert the reqd_work_group_size() attributes to metadata.
5928 llvm::LLVMContext &Context = F->getContext();
5929 llvm::NamedMDNode *OpenCLMetadata =
5930 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5931
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005932 SmallVector<llvm::Metadata *, 5> Operands;
5933 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005934
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005935 Operands.push_back(
5936 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5937 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
5938 Operands.push_back(
5939 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5940 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
5941 Operands.push_back(
5942 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
5943 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005944
5945 // Add a boolean constant operand for "required" (true) or "hint" (false)
5946 // for implementing the work_group_size_hint attr later. Currently
5947 // always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005948 Operands.push_back(
5949 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00005950 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5951 }
5952 }
5953 }
5954}
5955
5956}
John McCall943fae92010-05-27 06:19:26 +00005957
Tony Linthicum76329bf2011-12-12 21:14:55 +00005958//===----------------------------------------------------------------------===//
5959// Hexagon ABI Implementation
5960//===----------------------------------------------------------------------===//
5961
5962namespace {
5963
5964class HexagonABIInfo : public ABIInfo {
5965
5966
5967public:
5968 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5969
5970private:
5971
5972 ABIArgInfo classifyReturnType(QualType RetTy) const;
5973 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5974
Craig Topper4f12f102014-03-12 06:41:41 +00005975 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005976
Craig Topper4f12f102014-03-12 06:41:41 +00005977 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5978 CodeGenFunction &CGF) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00005979};
5980
5981class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5982public:
5983 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5984 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5985
Craig Topper4f12f102014-03-12 06:41:41 +00005986 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00005987 return 29;
5988 }
5989};
5990
5991}
5992
5993void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005994 if (!getCXXABI().classifyReturnType(FI))
5995 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005996 for (auto &I : FI.arguments())
5997 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00005998}
5999
6000ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6001 if (!isAggregateTypeForABI(Ty)) {
6002 // Treat an enum type as its underlying type.
6003 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6004 Ty = EnumTy->getDecl()->getIntegerType();
6005
6006 return (Ty->isPromotableIntegerType() ?
6007 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6008 }
6009
6010 // Ignore empty records.
6011 if (isEmptyRecord(getContext(), Ty, true))
6012 return ABIArgInfo::getIgnore();
6013
Mark Lacey3825e832013-10-06 01:33:34 +00006014 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00006015 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006016
6017 uint64_t Size = getContext().getTypeSize(Ty);
6018 if (Size > 64)
6019 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6020 // Pass in the smallest viable integer type.
6021 else if (Size > 32)
6022 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6023 else if (Size > 16)
6024 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6025 else if (Size > 8)
6026 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6027 else
6028 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6029}
6030
6031ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6032 if (RetTy->isVoidType())
6033 return ABIArgInfo::getIgnore();
6034
6035 // Large vector types should be returned via memory.
6036 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
6037 return ABIArgInfo::getIndirect(0);
6038
6039 if (!isAggregateTypeForABI(RetTy)) {
6040 // Treat an enum type as its underlying type.
6041 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6042 RetTy = EnumTy->getDecl()->getIntegerType();
6043
6044 return (RetTy->isPromotableIntegerType() ?
6045 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6046 }
6047
Tony Linthicum76329bf2011-12-12 21:14:55 +00006048 if (isEmptyRecord(getContext(), RetTy, true))
6049 return ABIArgInfo::getIgnore();
6050
6051 // Aggregates <= 8 bytes are returned in r0; other aggregates
6052 // are returned indirectly.
6053 uint64_t Size = getContext().getTypeSize(RetTy);
6054 if (Size <= 64) {
6055 // Return in the smallest viable integer type.
6056 if (Size <= 8)
6057 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6058 if (Size <= 16)
6059 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6060 if (Size <= 32)
6061 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6062 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6063 }
6064
6065 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
6066}
6067
6068llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattnerece04092012-02-07 00:39:47 +00006069 CodeGenFunction &CGF) const {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006070 // FIXME: Need to handle alignment
Chris Lattnerece04092012-02-07 00:39:47 +00006071 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006072
6073 CGBuilderTy &Builder = CGF.Builder;
6074 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
6075 "ap");
6076 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6077 llvm::Type *PTy =
6078 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
6079 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
6080
6081 uint64_t Offset =
6082 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
6083 llvm::Value *NextAddr =
6084 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
6085 "ap.next");
6086 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
6087
6088 return AddrTyped;
6089}
6090
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006091//===----------------------------------------------------------------------===//
6092// AMDGPU ABI Implementation
6093//===----------------------------------------------------------------------===//
6094
6095namespace {
6096
6097class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6098public:
6099 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6100 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6101 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6102 CodeGen::CodeGenModule &M) const override;
6103};
6104
6105}
6106
6107void AMDGPUTargetCodeGenInfo::SetTargetAttributes(
6108 const Decl *D,
6109 llvm::GlobalValue *GV,
6110 CodeGen::CodeGenModule &M) const {
6111 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6112 if (!FD)
6113 return;
6114
6115 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6116 llvm::Function *F = cast<llvm::Function>(GV);
6117 uint32_t NumVGPR = Attr->getNumVGPR();
6118 if (NumVGPR != 0)
6119 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6120 }
6121
6122 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6123 llvm::Function *F = cast<llvm::Function>(GV);
6124 unsigned NumSGPR = Attr->getNumSGPR();
6125 if (NumSGPR != 0)
6126 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6127 }
6128}
6129
Tony Linthicum76329bf2011-12-12 21:14:55 +00006130
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006131//===----------------------------------------------------------------------===//
6132// SPARC v9 ABI Implementation.
6133// Based on the SPARC Compliance Definition version 2.4.1.
6134//
6135// Function arguments a mapped to a nominal "parameter array" and promoted to
6136// registers depending on their type. Each argument occupies 8 or 16 bytes in
6137// the array, structs larger than 16 bytes are passed indirectly.
6138//
6139// One case requires special care:
6140//
6141// struct mixed {
6142// int i;
6143// float f;
6144// };
6145//
6146// When a struct mixed is passed by value, it only occupies 8 bytes in the
6147// parameter array, but the int is passed in an integer register, and the float
6148// is passed in a floating point register. This is represented as two arguments
6149// with the LLVM IR inreg attribute:
6150//
6151// declare void f(i32 inreg %i, float inreg %f)
6152//
6153// The code generator will only allocate 4 bytes from the parameter array for
6154// the inreg arguments. All other arguments are allocated a multiple of 8
6155// bytes.
6156//
6157namespace {
6158class SparcV9ABIInfo : public ABIInfo {
6159public:
6160 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6161
6162private:
6163 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006164 void computeInfo(CGFunctionInfo &FI) const override;
6165 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6166 CodeGenFunction &CGF) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006167
6168 // Coercion type builder for structs passed in registers. The coercion type
6169 // serves two purposes:
6170 //
6171 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6172 // in registers.
6173 // 2. Expose aligned floating point elements as first-level elements, so the
6174 // code generator knows to pass them in floating point registers.
6175 //
6176 // We also compute the InReg flag which indicates that the struct contains
6177 // aligned 32-bit floats.
6178 //
6179 struct CoerceBuilder {
6180 llvm::LLVMContext &Context;
6181 const llvm::DataLayout &DL;
6182 SmallVector<llvm::Type*, 8> Elems;
6183 uint64_t Size;
6184 bool InReg;
6185
6186 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6187 : Context(c), DL(dl), Size(0), InReg(false) {}
6188
6189 // Pad Elems with integers until Size is ToSize.
6190 void pad(uint64_t ToSize) {
6191 assert(ToSize >= Size && "Cannot remove elements");
6192 if (ToSize == Size)
6193 return;
6194
6195 // Finish the current 64-bit word.
6196 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6197 if (Aligned > Size && Aligned <= ToSize) {
6198 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6199 Size = Aligned;
6200 }
6201
6202 // Add whole 64-bit words.
6203 while (Size + 64 <= ToSize) {
6204 Elems.push_back(llvm::Type::getInt64Ty(Context));
6205 Size += 64;
6206 }
6207
6208 // Final in-word padding.
6209 if (Size < ToSize) {
6210 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6211 Size = ToSize;
6212 }
6213 }
6214
6215 // Add a floating point element at Offset.
6216 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6217 // Unaligned floats are treated as integers.
6218 if (Offset % Bits)
6219 return;
6220 // The InReg flag is only required if there are any floats < 64 bits.
6221 if (Bits < 64)
6222 InReg = true;
6223 pad(Offset);
6224 Elems.push_back(Ty);
6225 Size = Offset + Bits;
6226 }
6227
6228 // Add a struct type to the coercion type, starting at Offset (in bits).
6229 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6230 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6231 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6232 llvm::Type *ElemTy = StrTy->getElementType(i);
6233 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6234 switch (ElemTy->getTypeID()) {
6235 case llvm::Type::StructTyID:
6236 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6237 break;
6238 case llvm::Type::FloatTyID:
6239 addFloat(ElemOffset, ElemTy, 32);
6240 break;
6241 case llvm::Type::DoubleTyID:
6242 addFloat(ElemOffset, ElemTy, 64);
6243 break;
6244 case llvm::Type::FP128TyID:
6245 addFloat(ElemOffset, ElemTy, 128);
6246 break;
6247 case llvm::Type::PointerTyID:
6248 if (ElemOffset % 64 == 0) {
6249 pad(ElemOffset);
6250 Elems.push_back(ElemTy);
6251 Size += 64;
6252 }
6253 break;
6254 default:
6255 break;
6256 }
6257 }
6258 }
6259
6260 // Check if Ty is a usable substitute for the coercion type.
6261 bool isUsableType(llvm::StructType *Ty) const {
6262 if (Ty->getNumElements() != Elems.size())
6263 return false;
6264 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
6265 if (Elems[i] != Ty->getElementType(i))
6266 return false;
6267 return true;
6268 }
6269
6270 // Get the coercion type as a literal struct type.
6271 llvm::Type *getType() const {
6272 if (Elems.size() == 1)
6273 return Elems.front();
6274 else
6275 return llvm::StructType::get(Context, Elems);
6276 }
6277 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006278};
6279} // end anonymous namespace
6280
6281ABIArgInfo
6282SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6283 if (Ty->isVoidType())
6284 return ABIArgInfo::getIgnore();
6285
6286 uint64_t Size = getContext().getTypeSize(Ty);
6287
6288 // Anything too big to fit in registers is passed with an explicit indirect
6289 // pointer / sret pointer.
6290 if (Size > SizeLimit)
6291 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
6292
6293 // Treat an enum type as its underlying type.
6294 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6295 Ty = EnumTy->getDecl()->getIntegerType();
6296
6297 // Integer types smaller than a register are extended.
6298 if (Size < 64 && Ty->isIntegerType())
6299 return ABIArgInfo::getExtend();
6300
6301 // Other non-aggregates go in registers.
6302 if (!isAggregateTypeForABI(Ty))
6303 return ABIArgInfo::getDirect();
6304
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006305 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6306 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6307 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6308 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
6309
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006310 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006311 // Build a coercion type from the LLVM struct type.
6312 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6313 if (!StrTy)
6314 return ABIArgInfo::getDirect();
6315
6316 CoerceBuilder CB(getVMContext(), getDataLayout());
6317 CB.addStruct(0, StrTy);
6318 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6319
6320 // Try to use the original type for coercion.
6321 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6322
6323 if (CB.InReg)
6324 return ABIArgInfo::getDirectInReg(CoerceTy);
6325 else
6326 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006327}
6328
6329llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6330 CodeGenFunction &CGF) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006331 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6332 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6333 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6334 AI.setCoerceToType(ArgTy);
6335
6336 llvm::Type *BPP = CGF.Int8PtrPtrTy;
6337 CGBuilderTy &Builder = CGF.Builder;
6338 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
6339 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
6340 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6341 llvm::Value *ArgAddr;
6342 unsigned Stride;
6343
6344 switch (AI.getKind()) {
6345 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006346 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006347 llvm_unreachable("Unsupported ABI kind for va_arg");
6348
6349 case ABIArgInfo::Extend:
6350 Stride = 8;
6351 ArgAddr = Builder
6352 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
6353 "extend");
6354 break;
6355
6356 case ABIArgInfo::Direct:
6357 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6358 ArgAddr = Addr;
6359 break;
6360
6361 case ABIArgInfo::Indirect:
6362 Stride = 8;
6363 ArgAddr = Builder.CreateBitCast(Addr,
6364 llvm::PointerType::getUnqual(ArgPtrTy),
6365 "indirect");
6366 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
6367 break;
6368
6369 case ABIArgInfo::Ignore:
6370 return llvm::UndefValue::get(ArgPtrTy);
6371 }
6372
6373 // Update VAList.
6374 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
6375 Builder.CreateStore(Addr, VAListAddrAsBPP);
6376
6377 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006378}
6379
6380void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6381 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006382 for (auto &I : FI.arguments())
6383 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006384}
6385
6386namespace {
6387class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6388public:
6389 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6390 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006391
Craig Topper4f12f102014-03-12 06:41:41 +00006392 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006393 return 14;
6394 }
6395
6396 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006397 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006398};
6399} // end anonymous namespace
6400
Roman Divackyf02c9942014-02-24 18:46:27 +00006401bool
6402SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6403 llvm::Value *Address) const {
6404 // This is calculated from the LLVM and GCC tables and verified
6405 // against gcc output. AFAIK all ABIs use the same encoding.
6406
6407 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6408
6409 llvm::IntegerType *i8 = CGF.Int8Ty;
6410 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6411 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6412
6413 // 0-31: the 8-byte general-purpose registers
6414 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6415
6416 // 32-63: f0-31, the 4-byte floating-point registers
6417 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6418
6419 // Y = 64
6420 // PSR = 65
6421 // WIM = 66
6422 // TBR = 67
6423 // PC = 68
6424 // NPC = 69
6425 // FSR = 70
6426 // CSR = 71
6427 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
6428
6429 // 72-87: d0-15, the 8-byte floating-point registers
6430 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6431
6432 return false;
6433}
6434
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006435
Robert Lytton0e076492013-08-13 09:43:10 +00006436//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006437// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006438//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006439
Robert Lytton0e076492013-08-13 09:43:10 +00006440namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006441
6442/// A SmallStringEnc instance is used to build up the TypeString by passing
6443/// it by reference between functions that append to it.
6444typedef llvm::SmallString<128> SmallStringEnc;
6445
6446/// TypeStringCache caches the meta encodings of Types.
6447///
6448/// The reason for caching TypeStrings is two fold:
6449/// 1. To cache a type's encoding for later uses;
6450/// 2. As a means to break recursive member type inclusion.
6451///
6452/// A cache Entry can have a Status of:
6453/// NonRecursive: The type encoding is not recursive;
6454/// Recursive: The type encoding is recursive;
6455/// Incomplete: An incomplete TypeString;
6456/// IncompleteUsed: An incomplete TypeString that has been used in a
6457/// Recursive type encoding.
6458///
6459/// A NonRecursive entry will have all of its sub-members expanded as fully
6460/// as possible. Whilst it may contain types which are recursive, the type
6461/// itself is not recursive and thus its encoding may be safely used whenever
6462/// the type is encountered.
6463///
6464/// A Recursive entry will have all of its sub-members expanded as fully as
6465/// possible. The type itself is recursive and it may contain other types which
6466/// are recursive. The Recursive encoding must not be used during the expansion
6467/// of a recursive type's recursive branch. For simplicity the code uses
6468/// IncompleteCount to reject all usage of Recursive encodings for member types.
6469///
6470/// An Incomplete entry is always a RecordType and only encodes its
6471/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6472/// are placed into the cache during type expansion as a means to identify and
6473/// handle recursive inclusion of types as sub-members. If there is recursion
6474/// the entry becomes IncompleteUsed.
6475///
6476/// During the expansion of a RecordType's members:
6477///
6478/// If the cache contains a NonRecursive encoding for the member type, the
6479/// cached encoding is used;
6480///
6481/// If the cache contains a Recursive encoding for the member type, the
6482/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6483///
6484/// If the member is a RecordType, an Incomplete encoding is placed into the
6485/// cache to break potential recursive inclusion of itself as a sub-member;
6486///
6487/// Once a member RecordType has been expanded, its temporary incomplete
6488/// entry is removed from the cache. If a Recursive encoding was swapped out
6489/// it is swapped back in;
6490///
6491/// If an incomplete entry is used to expand a sub-member, the incomplete
6492/// entry is marked as IncompleteUsed. The cache keeps count of how many
6493/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6494///
6495/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6496/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6497/// Else the member is part of a recursive type and thus the recursion has
6498/// been exited too soon for the encoding to be correct for the member.
6499///
6500class TypeStringCache {
6501 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6502 struct Entry {
6503 std::string Str; // The encoded TypeString for the type.
6504 enum Status State; // Information about the encoding in 'Str'.
6505 std::string Swapped; // A temporary place holder for a Recursive encoding
6506 // during the expansion of RecordType's members.
6507 };
6508 std::map<const IdentifierInfo *, struct Entry> Map;
6509 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6510 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6511public:
Robert Lyttond263f142014-05-06 09:38:54 +00006512 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006513 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6514 bool removeIncomplete(const IdentifierInfo *ID);
6515 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6516 bool IsRecursive);
6517 StringRef lookupStr(const IdentifierInfo *ID);
6518};
6519
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006520/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006521/// FieldEncoding is a helper for this ordering process.
6522class FieldEncoding {
6523 bool HasName;
6524 std::string Enc;
6525public:
6526 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {};
6527 StringRef str() {return Enc.c_str();};
6528 bool operator<(const FieldEncoding &rhs) const {
6529 if (HasName != rhs.HasName) return HasName;
6530 return Enc < rhs.Enc;
6531 }
6532};
6533
Robert Lytton7d1db152013-08-19 09:46:39 +00006534class XCoreABIInfo : public DefaultABIInfo {
6535public:
6536 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006537 llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6538 CodeGenFunction &CGF) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006539};
6540
Robert Lyttond21e2d72014-03-03 13:45:29 +00006541class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006542 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006543public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006544 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006545 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006546 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6547 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006548};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006549
Robert Lytton2d196952013-10-11 10:29:34 +00006550} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006551
Robert Lytton7d1db152013-08-19 09:46:39 +00006552llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
6553 CodeGenFunction &CGF) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006554 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006555
Robert Lytton2d196952013-10-11 10:29:34 +00006556 // Get the VAList.
Robert Lytton7d1db152013-08-19 09:46:39 +00006557 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
6558 CGF.Int8PtrPtrTy);
6559 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton7d1db152013-08-19 09:46:39 +00006560
Robert Lytton2d196952013-10-11 10:29:34 +00006561 // Handle the argument.
6562 ABIArgInfo AI = classifyArgumentType(Ty);
6563 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6564 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6565 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006566 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton2d196952013-10-11 10:29:34 +00006567 llvm::Value *Val;
Andy Gibbsd9ba4722013-10-14 07:02:04 +00006568 uint64_t ArgSize = 0;
Robert Lytton7d1db152013-08-19 09:46:39 +00006569 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006570 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006571 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006572 llvm_unreachable("Unsupported ABI kind for va_arg");
6573 case ABIArgInfo::Ignore:
Robert Lytton2d196952013-10-11 10:29:34 +00006574 Val = llvm::UndefValue::get(ArgPtrTy);
6575 ArgSize = 0;
6576 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006577 case ABIArgInfo::Extend:
6578 case ABIArgInfo::Direct:
Robert Lytton2d196952013-10-11 10:29:34 +00006579 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
6580 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6581 if (ArgSize < 4)
6582 ArgSize = 4;
6583 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006584 case ABIArgInfo::Indirect:
6585 llvm::Value *ArgAddr;
6586 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
6587 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006588 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
6589 ArgSize = 4;
6590 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006591 }
Robert Lytton2d196952013-10-11 10:29:34 +00006592
6593 // Increment the VAList.
6594 if (ArgSize) {
6595 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
6596 Builder.CreateStore(APN, VAListAddrAsBPP);
6597 }
6598 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006599}
Robert Lytton0e076492013-08-13 09:43:10 +00006600
Robert Lytton844aeeb2014-05-02 09:33:20 +00006601/// During the expansion of a RecordType, an incomplete TypeString is placed
6602/// into the cache as a means to identify and break recursion.
6603/// If there is a Recursive encoding in the cache, it is swapped out and will
6604/// be reinserted by removeIncomplete().
6605/// All other types of encoding should have been used rather than arriving here.
6606void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6607 std::string StubEnc) {
6608 if (!ID)
6609 return;
6610 Entry &E = Map[ID];
6611 assert( (E.Str.empty() || E.State == Recursive) &&
6612 "Incorrectly use of addIncomplete");
6613 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6614 E.Swapped.swap(E.Str); // swap out the Recursive
6615 E.Str.swap(StubEnc);
6616 E.State = Incomplete;
6617 ++IncompleteCount;
6618}
6619
6620/// Once the RecordType has been expanded, the temporary incomplete TypeString
6621/// must be removed from the cache.
6622/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6623/// Returns true if the RecordType was defined recursively.
6624bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6625 if (!ID)
6626 return false;
6627 auto I = Map.find(ID);
6628 assert(I != Map.end() && "Entry not present");
6629 Entry &E = I->second;
6630 assert( (E.State == Incomplete ||
6631 E.State == IncompleteUsed) &&
6632 "Entry must be an incomplete type");
6633 bool IsRecursive = false;
6634 if (E.State == IncompleteUsed) {
6635 // We made use of our Incomplete encoding, thus we are recursive.
6636 IsRecursive = true;
6637 --IncompleteUsedCount;
6638 }
6639 if (E.Swapped.empty())
6640 Map.erase(I);
6641 else {
6642 // Swap the Recursive back.
6643 E.Swapped.swap(E.Str);
6644 E.Swapped.clear();
6645 E.State = Recursive;
6646 }
6647 --IncompleteCount;
6648 return IsRecursive;
6649}
6650
6651/// Add the encoded TypeString to the cache only if it is NonRecursive or
6652/// Recursive (viz: all sub-members were expanded as fully as possible).
6653void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6654 bool IsRecursive) {
6655 if (!ID || IncompleteUsedCount)
6656 return; // No key or it is is an incomplete sub-type so don't add.
6657 Entry &E = Map[ID];
6658 if (IsRecursive && !E.Str.empty()) {
6659 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6660 "This is not the same Recursive entry");
6661 // The parent container was not recursive after all, so we could have used
6662 // this Recursive sub-member entry after all, but we assumed the worse when
6663 // we started viz: IncompleteCount!=0.
6664 return;
6665 }
6666 assert(E.Str.empty() && "Entry already present");
6667 E.Str = Str.str();
6668 E.State = IsRecursive? Recursive : NonRecursive;
6669}
6670
6671/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6672/// are recursively expanding a type (IncompleteCount != 0) and the cached
6673/// encoding is Recursive, return an empty StringRef.
6674StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6675 if (!ID)
6676 return StringRef(); // We have no key.
6677 auto I = Map.find(ID);
6678 if (I == Map.end())
6679 return StringRef(); // We have no encoding.
6680 Entry &E = I->second;
6681 if (E.State == Recursive && IncompleteCount)
6682 return StringRef(); // We don't use Recursive encodings for member types.
6683
6684 if (E.State == Incomplete) {
6685 // The incomplete type is being used to break out of recursion.
6686 E.State = IncompleteUsed;
6687 ++IncompleteUsedCount;
6688 }
6689 return E.Str.c_str();
6690}
6691
6692/// The XCore ABI includes a type information section that communicates symbol
6693/// type information to the linker. The linker uses this information to verify
6694/// safety/correctness of things such as array bound and pointers et al.
6695/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6696/// This type information (TypeString) is emitted into meta data for all global
6697/// symbols: definitions, declarations, functions & variables.
6698///
6699/// The TypeString carries type, qualifier, name, size & value details.
6700/// Please see 'Tools Development Guide' section 2.16.2 for format details:
6701/// <https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf>
6702/// The output is tested by test/CodeGen/xcore-stringtype.c.
6703///
6704static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6705 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6706
6707/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6708void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6709 CodeGen::CodeGenModule &CGM) const {
6710 SmallStringEnc Enc;
6711 if (getTypeString(Enc, D, CGM, TSC)) {
6712 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006713 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6714 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006715 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6716 llvm::NamedMDNode *MD =
6717 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6718 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6719 }
6720}
6721
6722static bool appendType(SmallStringEnc &Enc, QualType QType,
6723 const CodeGen::CodeGenModule &CGM,
6724 TypeStringCache &TSC);
6725
6726/// Helper function for appendRecordType().
6727/// Builds a SmallVector containing the encoded field types in declaration order.
6728static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6729 const RecordDecl *RD,
6730 const CodeGen::CodeGenModule &CGM,
6731 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006732 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006733 SmallStringEnc Enc;
6734 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006735 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006736 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006737 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006738 Enc += "b(";
6739 llvm::raw_svector_ostream OS(Enc);
6740 OS.resync();
Hans Wennborga302cd92014-08-21 16:06:57 +00006741 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006742 OS.flush();
6743 Enc += ':';
6744 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006745 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006746 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006747 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006748 Enc += ')';
6749 Enc += '}';
Hans Wennborga302cd92014-08-21 16:06:57 +00006750 FE.push_back(FieldEncoding(!Field->getName().empty(), Enc));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006751 }
6752 return true;
6753}
6754
6755/// Appends structure and union types to Enc and adds encoding to cache.
6756/// Recursively calls appendType (via extractFieldType) for each field.
6757/// Union types have their fields ordered according to the ABI.
6758static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6759 const CodeGen::CodeGenModule &CGM,
6760 TypeStringCache &TSC, const IdentifierInfo *ID) {
6761 // Append the cached TypeString if we have one.
6762 StringRef TypeString = TSC.lookupStr(ID);
6763 if (!TypeString.empty()) {
6764 Enc += TypeString;
6765 return true;
6766 }
6767
6768 // Start to emit an incomplete TypeString.
6769 size_t Start = Enc.size();
6770 Enc += (RT->isUnionType()? 'u' : 's');
6771 Enc += '(';
6772 if (ID)
6773 Enc += ID->getName();
6774 Enc += "){";
6775
6776 // We collect all encoded fields and order as necessary.
6777 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006778 const RecordDecl *RD = RT->getDecl()->getDefinition();
6779 if (RD && !RD->field_empty()) {
6780 // An incomplete TypeString stub is placed in the cache for this RecordType
6781 // so that recursive calls to this RecordType will use it whilst building a
6782 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006783 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006784 std::string StubEnc(Enc.substr(Start).str());
6785 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
6786 TSC.addIncomplete(ID, std::move(StubEnc));
6787 if (!extractFieldType(FE, RD, CGM, TSC)) {
6788 (void) TSC.removeIncomplete(ID);
6789 return false;
6790 }
6791 IsRecursive = TSC.removeIncomplete(ID);
6792 // The ABI requires unions to be sorted but not structures.
6793 // See FieldEncoding::operator< for sort algorithm.
6794 if (RT->isUnionType())
6795 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006796 // We can now complete the TypeString.
6797 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006798 for (unsigned I = 0; I != E; ++I) {
6799 if (I)
6800 Enc += ',';
6801 Enc += FE[I].str();
6802 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006803 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00006804 Enc += '}';
6805 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
6806 return true;
6807}
6808
6809/// Appends enum types to Enc and adds the encoding to the cache.
6810static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
6811 TypeStringCache &TSC,
6812 const IdentifierInfo *ID) {
6813 // Append the cached TypeString if we have one.
6814 StringRef TypeString = TSC.lookupStr(ID);
6815 if (!TypeString.empty()) {
6816 Enc += TypeString;
6817 return true;
6818 }
6819
6820 size_t Start = Enc.size();
6821 Enc += "e(";
6822 if (ID)
6823 Enc += ID->getName();
6824 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006825
6826 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006827 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006828 SmallVector<FieldEncoding, 16> FE;
6829 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
6830 ++I) {
6831 SmallStringEnc EnumEnc;
6832 EnumEnc += "m(";
6833 EnumEnc += I->getName();
6834 EnumEnc += "){";
6835 I->getInitVal().toString(EnumEnc);
6836 EnumEnc += '}';
6837 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
6838 }
6839 std::sort(FE.begin(), FE.end());
6840 unsigned E = FE.size();
6841 for (unsigned I = 0; I != E; ++I) {
6842 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00006843 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006844 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006845 }
6846 }
6847 Enc += '}';
6848 TSC.addIfComplete(ID, Enc.substr(Start), false);
6849 return true;
6850}
6851
6852/// Appends type's qualifier to Enc.
6853/// This is done prior to appending the type's encoding.
6854static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
6855 // Qualifiers are emitted in alphabetical order.
6856 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
6857 int Lookup = 0;
6858 if (QT.isConstQualified())
6859 Lookup += 1<<0;
6860 if (QT.isRestrictQualified())
6861 Lookup += 1<<1;
6862 if (QT.isVolatileQualified())
6863 Lookup += 1<<2;
6864 Enc += Table[Lookup];
6865}
6866
6867/// Appends built-in types to Enc.
6868static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
6869 const char *EncType;
6870 switch (BT->getKind()) {
6871 case BuiltinType::Void:
6872 EncType = "0";
6873 break;
6874 case BuiltinType::Bool:
6875 EncType = "b";
6876 break;
6877 case BuiltinType::Char_U:
6878 EncType = "uc";
6879 break;
6880 case BuiltinType::UChar:
6881 EncType = "uc";
6882 break;
6883 case BuiltinType::SChar:
6884 EncType = "sc";
6885 break;
6886 case BuiltinType::UShort:
6887 EncType = "us";
6888 break;
6889 case BuiltinType::Short:
6890 EncType = "ss";
6891 break;
6892 case BuiltinType::UInt:
6893 EncType = "ui";
6894 break;
6895 case BuiltinType::Int:
6896 EncType = "si";
6897 break;
6898 case BuiltinType::ULong:
6899 EncType = "ul";
6900 break;
6901 case BuiltinType::Long:
6902 EncType = "sl";
6903 break;
6904 case BuiltinType::ULongLong:
6905 EncType = "ull";
6906 break;
6907 case BuiltinType::LongLong:
6908 EncType = "sll";
6909 break;
6910 case BuiltinType::Float:
6911 EncType = "ft";
6912 break;
6913 case BuiltinType::Double:
6914 EncType = "d";
6915 break;
6916 case BuiltinType::LongDouble:
6917 EncType = "ld";
6918 break;
6919 default:
6920 return false;
6921 }
6922 Enc += EncType;
6923 return true;
6924}
6925
6926/// Appends a pointer encoding to Enc before calling appendType for the pointee.
6927static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
6928 const CodeGen::CodeGenModule &CGM,
6929 TypeStringCache &TSC) {
6930 Enc += "p(";
6931 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
6932 return false;
6933 Enc += ')';
6934 return true;
6935}
6936
6937/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00006938static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
6939 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00006940 const CodeGen::CodeGenModule &CGM,
6941 TypeStringCache &TSC, StringRef NoSizeEnc) {
6942 if (AT->getSizeModifier() != ArrayType::Normal)
6943 return false;
6944 Enc += "a(";
6945 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6946 CAT->getSize().toStringUnsigned(Enc);
6947 else
6948 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
6949 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00006950 // The Qualifiers should be attached to the type rather than the array.
6951 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006952 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
6953 return false;
6954 Enc += ')';
6955 return true;
6956}
6957
6958/// Appends a function encoding to Enc, calling appendType for the return type
6959/// and the arguments.
6960static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
6961 const CodeGen::CodeGenModule &CGM,
6962 TypeStringCache &TSC) {
6963 Enc += "f{";
6964 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
6965 return false;
6966 Enc += "}(";
6967 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
6968 // N.B. we are only interested in the adjusted param types.
6969 auto I = FPT->param_type_begin();
6970 auto E = FPT->param_type_end();
6971 if (I != E) {
6972 do {
6973 if (!appendType(Enc, *I, CGM, TSC))
6974 return false;
6975 ++I;
6976 if (I != E)
6977 Enc += ',';
6978 } while (I != E);
6979 if (FPT->isVariadic())
6980 Enc += ",va";
6981 } else {
6982 if (FPT->isVariadic())
6983 Enc += "va";
6984 else
6985 Enc += '0';
6986 }
6987 }
6988 Enc += ')';
6989 return true;
6990}
6991
6992/// Handles the type's qualifier before dispatching a call to handle specific
6993/// type encodings.
6994static bool appendType(SmallStringEnc &Enc, QualType QType,
6995 const CodeGen::CodeGenModule &CGM,
6996 TypeStringCache &TSC) {
6997
6998 QualType QT = QType.getCanonicalType();
6999
Robert Lytton6adb20f2014-06-05 09:06:21 +00007000 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7001 // The Qualifiers should be attached to the type rather than the array.
7002 // Thus we don't call appendQualifier() here.
7003 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7004
Robert Lytton844aeeb2014-05-02 09:33:20 +00007005 appendQualifier(Enc, QT);
7006
7007 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7008 return appendBuiltinType(Enc, BT);
7009
Robert Lytton844aeeb2014-05-02 09:33:20 +00007010 if (const PointerType *PT = QT->getAs<PointerType>())
7011 return appendPointerType(Enc, PT, CGM, TSC);
7012
7013 if (const EnumType *ET = QT->getAs<EnumType>())
7014 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7015
7016 if (const RecordType *RT = QT->getAsStructureType())
7017 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7018
7019 if (const RecordType *RT = QT->getAsUnionType())
7020 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7021
7022 if (const FunctionType *FT = QT->getAs<FunctionType>())
7023 return appendFunctionType(Enc, FT, CGM, TSC);
7024
7025 return false;
7026}
7027
7028static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7029 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7030 if (!D)
7031 return false;
7032
7033 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7034 if (FD->getLanguageLinkage() != CLanguageLinkage)
7035 return false;
7036 return appendType(Enc, FD->getType(), CGM, TSC);
7037 }
7038
7039 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7040 if (VD->getLanguageLinkage() != CLanguageLinkage)
7041 return false;
7042 QualType QT = VD->getType().getCanonicalType();
7043 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7044 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007045 // The Qualifiers should be attached to the type rather than the array.
7046 // Thus we don't call appendQualifier() here.
7047 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007048 }
7049 return appendType(Enc, QT, CGM, TSC);
7050 }
7051 return false;
7052}
7053
7054
Robert Lytton0e076492013-08-13 09:43:10 +00007055//===----------------------------------------------------------------------===//
7056// Driver code
7057//===----------------------------------------------------------------------===//
7058
Rafael Espindola9f834732014-09-19 01:54:22 +00007059const llvm::Triple &CodeGenModule::getTriple() const {
7060 return getTarget().getTriple();
7061}
7062
7063bool CodeGenModule::supportsCOMDAT() const {
7064 return !getTriple().isOSBinFormatMachO();
7065}
7066
Chris Lattner2b037972010-07-29 02:01:43 +00007067const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007068 if (TheTargetCodeGenInfo)
7069 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007070
John McCallc8e01702013-04-16 22:48:15 +00007071 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007072 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007073 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007074 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007075
Derek Schuff09338a22012-09-06 17:37:28 +00007076 case llvm::Triple::le32:
7077 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007078 case llvm::Triple::mips:
7079 case llvm::Triple::mipsel:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007080 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7081
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007082 case llvm::Triple::mips64:
7083 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007084 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7085
Tim Northover25e8a672014-05-24 12:51:25 +00007086 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007087 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007088 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007089 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007090 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007091
Tim Northover573cbee2014-05-24 12:52:07 +00007092 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007093 }
7094
Daniel Dunbard59655c2009-09-12 00:59:49 +00007095 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007096 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007097 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007098 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007099 {
7100 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007101 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007102 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007103 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007104 (CodeGenOpts.FloatABI != "soft" &&
7105 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007106 Kind = ARMABIInfo::AAPCS_VFP;
7107
Derek Schuffa2020962012-10-16 22:30:41 +00007108 switch (Triple.getOS()) {
Eli Benderskyd7c92032012-12-04 18:38:10 +00007109 case llvm::Triple::NaCl:
Derek Schuffa2020962012-10-16 22:30:41 +00007110 return *(TheTargetCodeGenInfo =
7111 new NaClARMTargetCodeGenInfo(Types, Kind));
7112 default:
7113 return *(TheTargetCodeGenInfo =
7114 new ARMTargetCodeGenInfo(Types, Kind));
7115 }
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007116 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007117
John McCallea8d8bb2010-03-11 00:10:12 +00007118 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007119 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007120 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007121 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007122 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007123 if (getTarget().getABI() == "elfv2")
7124 Kind = PPC64_SVR4_ABIInfo::ELFv2;
7125
Ulrich Weigandb7122372014-07-21 00:48:09 +00007126 return *(TheTargetCodeGenInfo =
7127 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7128 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007129 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007130 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007131 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007132 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007133 if (getTarget().getABI() == "elfv1")
7134 Kind = PPC64_SVR4_ABIInfo::ELFv1;
7135
Ulrich Weigandb7122372014-07-21 00:48:09 +00007136 return *(TheTargetCodeGenInfo =
7137 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind));
7138 }
John McCallea8d8bb2010-03-11 00:10:12 +00007139
Peter Collingbournec947aae2012-05-20 23:28:41 +00007140 case llvm::Triple::nvptx:
7141 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007142 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007143
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007144 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007145 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007146
Ulrich Weigand47445072013-05-06 16:26:41 +00007147 case llvm::Triple::systemz:
7148 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
7149
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007150 case llvm::Triple::tce:
7151 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7152
Eli Friedman33465822011-07-08 23:31:17 +00007153 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007154 bool IsDarwinVectorABI = Triple.isOSDarwin();
7155 bool IsSmallStructInRegABI =
7156 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007157 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007158
John McCall1fe2a8c2013-06-18 02:46:29 +00007159 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedmana98d1f82012-01-25 22:46:34 +00007160 return *(TheTargetCodeGenInfo =
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007161 new WinX86_32TargetCodeGenInfo(Types,
John McCall1fe2a8c2013-06-18 02:46:29 +00007162 IsDarwinVectorABI, IsSmallStructInRegABI,
7163 IsWin32FloatStructABI,
Reid Klecknere43f0fe2013-05-08 13:44:39 +00007164 CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007165 } else {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007166 return *(TheTargetCodeGenInfo =
John McCall1fe2a8c2013-06-18 02:46:29 +00007167 new X86_32TargetCodeGenInfo(Types,
7168 IsDarwinVectorABI, IsSmallStructInRegABI,
7169 IsWin32FloatStructABI,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00007170 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007171 }
Eli Friedman33465822011-07-08 23:31:17 +00007172 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007173
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007174 case llvm::Triple::x86_64: {
Alp Toker4925ba72014-06-07 23:30:42 +00007175 bool HasAVX = getTarget().getABI() == "avx";
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007176
Chris Lattner04dc9572010-08-31 16:44:54 +00007177 switch (Triple.getOS()) {
7178 case llvm::Triple::Win32:
Alexander Musman09184fe2014-09-30 05:29:28 +00007179 return *(TheTargetCodeGenInfo =
7180 new WinX86_64TargetCodeGenInfo(Types, HasAVX));
Eli Benderskyd7c92032012-12-04 18:38:10 +00007181 case llvm::Triple::NaCl:
Alexander Musman09184fe2014-09-30 05:29:28 +00007182 return *(TheTargetCodeGenInfo =
7183 new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007184 default:
Alexander Musman09184fe2014-09-30 05:29:28 +00007185 return *(TheTargetCodeGenInfo =
7186 new X86_64TargetCodeGenInfo(Types, HasAVX));
Chris Lattner04dc9572010-08-31 16:44:54 +00007187 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007188 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007189 case llvm::Triple::hexagon:
7190 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007191 case llvm::Triple::r600:
7192 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007193 case llvm::Triple::sparcv9:
7194 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007195 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007196 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007197 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007198}