blob: fa66fcbe9457da20246c5ef78d92de125f33dabc [file] [log] [blame]
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000018#include "CodeGenFunction.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Sandeep Patel34c1af82011-04-05 00:23:47 +000020#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar2c0843f2009-08-24 08:52:16 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000022#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Type.h"
Daniel Dunbar28df7a52009-12-03 09:13:49 +000024#include "llvm/Support/raw_ostream.h"
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000025using namespace clang;
26using namespace CodeGen;
27
John McCallaeeb7012010-05-27 06:19:26 +000028static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
29 llvm::Value *Array,
30 llvm::Value *Value,
31 unsigned FirstIndex,
32 unsigned LastIndex) {
33 // Alternatively, we could emit this as a loop in the source.
34 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
35 llvm::Value *Cell = Builder.CreateConstInBoundsGEP1_32(Array, I);
36 Builder.CreateStore(Value, Cell);
37 }
38}
39
John McCalld608cdb2010-08-22 10:59:02 +000040static bool isAggregateTypeForABI(QualType T) {
John McCall9d232c82013-03-07 21:37:08 +000041 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalld608cdb2010-08-22 10:59:02 +000042 T->isMemberFunctionPointerType();
43}
44
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000045ABIInfo::~ABIInfo() {}
46
Mark Lacey23630722013-10-06 01:33:34 +000047static bool isRecordReturnIndirect(const RecordType *RT,
48 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000049 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
50 if (!RD)
51 return false;
Mark Lacey23630722013-10-06 01:33:34 +000052 return CXXABI.isReturnTypeIndirect(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000053}
54
55
Mark Lacey23630722013-10-06 01:33:34 +000056static bool isRecordReturnIndirect(QualType T, CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000057 const RecordType *RT = T->getAs<RecordType>();
58 if (!RT)
59 return false;
Mark Lacey23630722013-10-06 01:33:34 +000060 return isRecordReturnIndirect(RT, CXXABI);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000061}
62
63static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey23630722013-10-06 01:33:34 +000064 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000065 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
66 if (!RD)
67 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000068 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000069}
70
71static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey23630722013-10-06 01:33:34 +000072 CGCXXABI &CXXABI) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000073 const RecordType *RT = T->getAs<RecordType>();
74 if (!RT)
75 return CGCXXABI::RAA_Default;
Mark Lacey23630722013-10-06 01:33:34 +000076 return getRecordArgABI(RT, CXXABI);
77}
78
79CGCXXABI &ABIInfo::getCXXABI() const {
80 return CGT.getCXXABI();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +000081}
82
Chris Lattnerea044322010-07-29 02:01:43 +000083ASTContext &ABIInfo::getContext() const {
84 return CGT.getContext();
85}
86
87llvm::LLVMContext &ABIInfo::getVMContext() const {
88 return CGT.getLLVMContext();
89}
90
Micah Villmow25a6a842012-10-08 16:25:52 +000091const llvm::DataLayout &ABIInfo::getDataLayout() const {
92 return CGT.getDataLayout();
Chris Lattnerea044322010-07-29 02:01:43 +000093}
94
John McCall64aa4b32013-04-16 22:48:15 +000095const TargetInfo &ABIInfo::getTarget() const {
96 return CGT.getTarget();
97}
Chris Lattnerea044322010-07-29 02:01:43 +000098
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +000099void ABIArgInfo::dump() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000100 raw_ostream &OS = llvm::errs();
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000101 OS << "(ABIArgInfo Kind=";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000102 switch (TheKind) {
103 case Direct:
Chris Lattner800588f2010-07-29 06:26:06 +0000104 OS << "Direct Type=";
Chris Lattner2acc6e32011-07-18 04:24:23 +0000105 if (llvm::Type *Ty = getCoerceToType())
Chris Lattner800588f2010-07-29 06:26:06 +0000106 Ty->print(OS);
107 else
108 OS << "null";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000109 break;
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000110 case Extend:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000111 OS << "Extend";
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +0000112 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000113 case Ignore:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000114 OS << "Ignore";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000115 break;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000116 case Indirect:
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000117 OS << "Indirect Align=" << getIndirectAlign()
Joerg Sonnenbergere9b5d772011-07-15 18:23:44 +0000118 << " ByVal=" << getIndirectByVal()
Daniel Dunbarcf3b6f22010-09-16 20:42:02 +0000119 << " Realign=" << getIndirectRealign();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000120 break;
121 case Expand:
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000122 OS << "Expand";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000123 break;
124 }
Daniel Dunbar28df7a52009-12-03 09:13:49 +0000125 OS << ")\n";
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000126}
127
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000128TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
129
John McCall49e34be2011-08-30 01:42:09 +0000130// If someone can figure out a general rule for this, that would be great.
131// It's probably just doomed to be platform-dependent, though.
132unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
133 // Verified for:
134 // x86-64 FreeBSD, Linux, Darwin
135 // x86-32 FreeBSD, Linux, Darwin
136 // PowerPC Linux, Darwin
137 // ARM Darwin (*not* EABI)
Tim Northoverc264e162013-01-31 12:13:10 +0000138 // AArch64 Linux
John McCall49e34be2011-08-30 01:42:09 +0000139 return 32;
140}
141
John McCallde5d3c72012-02-17 03:33:10 +0000142bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
143 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +0000144 // The following conventions are known to require this to be false:
145 // x86_stdcall
146 // MIPS
147 // For everything else, we just prefer false unless we opt out.
148 return false;
149}
150
Reid Kleckner3190ca92013-05-08 13:44:39 +0000151void
152TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
153 llvm::SmallString<24> &Opt) const {
154 // This assumes the user is passing a library name like "rt" instead of a
155 // filename like "librt.a/so", and that they don't care whether it's static or
156 // dynamic.
157 Opt = "-l";
158 Opt += Lib;
159}
160
Daniel Dunbar98303b92009-09-13 08:03:58 +0000161static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000162
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000163/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000164/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar98303b92009-09-13 08:03:58 +0000165static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
166 bool AllowArrays) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000167 if (FD->isUnnamedBitfield())
168 return true;
169
170 QualType FT = FD->getType();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000171
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000172 // Constant arrays of empty records count as empty, strip them off.
173 // Constant arrays of zero length always count as empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000174 if (AllowArrays)
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000175 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
176 if (AT->getSize() == 0)
177 return true;
Daniel Dunbar98303b92009-09-13 08:03:58 +0000178 FT = AT->getElementType();
Eli Friedman7e7ad3f2011-11-18 03:47:20 +0000179 }
Daniel Dunbar98303b92009-09-13 08:03:58 +0000180
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000181 const RecordType *RT = FT->getAs<RecordType>();
182 if (!RT)
183 return false;
184
185 // C++ record fields are never empty, at least in the Itanium ABI.
186 //
187 // FIXME: We should use a predicate for whether this behavior is true in the
188 // current ABI.
189 if (isa<CXXRecordDecl>(RT->getDecl()))
190 return false;
191
Daniel Dunbar98303b92009-09-13 08:03:58 +0000192 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000193}
194
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000195/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000196/// fields. Note that a structure with a flexible array member is not
197/// considered empty.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000198static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000199 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000200 if (!RT)
201 return 0;
202 const RecordDecl *RD = RT->getDecl();
203 if (RD->hasFlexibleArrayMember())
204 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000205
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000206 // If this is a C++ record, check the bases first.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000207 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Argyrios Kyrtzidisc5f18f32011-05-17 02:17:52 +0000208 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
209 e = CXXRD->bases_end(); i != e; ++i)
210 if (!isEmptyRecord(Context, i->getType(), true))
211 return false;
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000212
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000213 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
214 i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000215 if (!isEmptyField(Context, *i, AllowArrays))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000216 return false;
217 return true;
218}
219
220/// isSingleElementStruct - Determine if a structure is a "single
221/// element struct", i.e. it has exactly one non-empty field or
222/// exactly one field which is itself a single element
223/// struct. Structures with flexible array members are never
224/// considered single element structs.
225///
226/// \return The field declaration for the single non-empty field, if
227/// it exists.
228static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
229 const RecordType *RT = T->getAsStructureType();
230 if (!RT)
231 return 0;
232
233 const RecordDecl *RD = RT->getDecl();
234 if (RD->hasFlexibleArrayMember())
235 return 0;
236
237 const Type *Found = 0;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000238
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000239 // If this is a C++ record, check the bases first.
240 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
241 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
242 e = CXXRD->bases_end(); i != e; ++i) {
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000243 // Ignore empty records.
Daniel Dunbar5ea68612010-05-17 16:46:00 +0000244 if (isEmptyRecord(Context, i->getType(), true))
Daniel Dunbar9430d5a2010-05-11 21:15:36 +0000245 continue;
246
247 // If we already found an element then this isn't a single-element struct.
248 if (Found)
249 return 0;
250
251 // If this is non-empty and not a single element struct, the composite
252 // cannot be a single element struct.
253 Found = isSingleElementStruct(i->getType(), Context);
254 if (!Found)
255 return 0;
256 }
257 }
258
259 // Check for single element.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000260 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
261 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000262 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000263 QualType FT = FD->getType();
264
265 // Ignore empty fields.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000266 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000267 continue;
268
269 // If we already found an element then this isn't a single-element
270 // struct.
271 if (Found)
272 return 0;
273
274 // Treat single element arrays as the element.
275 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
276 if (AT->getSize().getZExtValue() != 1)
277 break;
278 FT = AT->getElementType();
279 }
280
John McCalld608cdb2010-08-22 10:59:02 +0000281 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000282 Found = FT.getTypePtr();
283 } else {
284 Found = isSingleElementStruct(FT, Context);
285 if (!Found)
286 return 0;
287 }
288 }
289
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000290 // We don't consider a struct a single-element struct if it has
291 // padding beyond the element type.
292 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
293 return 0;
294
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000295 return Found;
296}
297
298static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmandb748a32012-11-29 23:21:04 +0000299 // Treat complex types as the element type.
300 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
301 Ty = CTy->getElementType();
302
303 // Check for a type which we know has a simple scalar argument-passing
304 // convention without any padding. (We're specifically looking for 32
305 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbara1842d32010-05-14 03:40:53 +0000306 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmandb748a32012-11-29 23:21:04 +0000307 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000308 return false;
309
310 uint64_t Size = Context.getTypeSize(Ty);
311 return Size == 32 || Size == 64;
312}
313
Daniel Dunbar53012f42009-11-09 01:33:53 +0000314/// canExpandIndirectArgument - Test whether an argument type which is to be
315/// passed indirectly (on the stack) would have the equivalent layout if it was
316/// expanded into separate arguments. If so, we prefer to do the latter to avoid
317/// inhibiting optimizations.
318///
319// FIXME: This predicate is missing many cases, currently it just follows
320// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
321// should probably make this smarter, or better yet make the LLVM backend
322// capable of handling it.
323static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
324 // We can only expand structure types.
325 const RecordType *RT = Ty->getAs<RecordType>();
326 if (!RT)
327 return false;
328
329 // We can only expand (C) structures.
330 //
331 // FIXME: This needs to be generalized to handle classes as well.
332 const RecordDecl *RD = RT->getDecl();
333 if (!RD->isStruct() || isa<CXXRecordDecl>(RD))
334 return false;
335
Eli Friedman506d4e32011-11-18 01:32:26 +0000336 uint64_t Size = 0;
337
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000338 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
339 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000340 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000341
342 if (!is32Or64BitBasicType(FD->getType(), Context))
343 return false;
344
345 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
346 // how to expand them yet, and the predicate for telling if a bitfield still
347 // counts as "basic" is more complicated than what we were doing previously.
348 if (FD->isBitField())
349 return false;
Eli Friedman506d4e32011-11-18 01:32:26 +0000350
351 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000352 }
353
Eli Friedman506d4e32011-11-18 01:32:26 +0000354 // Make sure there are not any holes in the struct.
355 if (Size != Context.getTypeSize(Ty))
356 return false;
357
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000358 return true;
359}
360
361namespace {
362/// DefaultABIInfo - The default implementation for ABI specific
363/// details. This implementation provides information which results in
364/// self-consistent and sensible LLVM IR generation, but does not
365/// conform to any particular ABI.
366class DefaultABIInfo : public ABIInfo {
Chris Lattnerea044322010-07-29 02:01:43 +0000367public:
368 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000369
Chris Lattnera3c109b2010-07-29 02:16:43 +0000370 ABIArgInfo classifyReturnType(QualType RetTy) const;
371 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000372
Chris Lattneree5dcd02010-07-29 02:31:05 +0000373 virtual void computeInfo(CGFunctionInfo &FI) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000374 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000375 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
376 it != ie; ++it)
Chris Lattnera3c109b2010-07-29 02:16:43 +0000377 it->info = classifyArgumentType(it->type);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000378 }
379
380 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
381 CodeGenFunction &CGF) const;
382};
383
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000384class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
385public:
Chris Lattnerea044322010-07-29 02:01:43 +0000386 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
387 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000388};
389
390llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
391 CodeGenFunction &CGF) const {
392 return 0;
393}
394
Chris Lattnera3c109b2010-07-29 02:16:43 +0000395ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Jan Wen Voung90306932011-11-03 00:59:44 +0000396 if (isAggregateTypeForABI(Ty)) {
397 // Records with non trivial destructors/constructors should not be passed
398 // by value.
Mark Lacey23630722013-10-06 01:33:34 +0000399 if (isRecordReturnIndirect(Ty, getCXXABI()))
Jan Wen Voung90306932011-11-03 00:59:44 +0000400 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
401
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000402 return ABIArgInfo::getIndirect(0);
Jan Wen Voung90306932011-11-03 00:59:44 +0000403 }
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000404
Chris Lattnera14db752010-03-11 18:19:55 +0000405 // Treat an enum type as its underlying type.
406 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
407 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000408
Chris Lattnera14db752010-03-11 18:19:55 +0000409 return (Ty->isPromotableIntegerType() ?
410 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000411}
412
Bob Wilson0024f942011-01-10 23:54:17 +0000413ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
414 if (RetTy->isVoidType())
415 return ABIArgInfo::getIgnore();
416
417 if (isAggregateTypeForABI(RetTy))
418 return ABIArgInfo::getIndirect(0);
419
420 // Treat an enum type as its underlying type.
421 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
422 RetTy = EnumTy->getDecl()->getIntegerType();
423
424 return (RetTy->isPromotableIntegerType() ?
425 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
426}
427
Derek Schuff9ed63f82012-09-06 17:37:28 +0000428//===----------------------------------------------------------------------===//
429// le32/PNaCl bitcode ABI Implementation
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000430//
431// This is a simplified version of the x86_32 ABI. Arguments and return values
432// are always passed on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000433//===----------------------------------------------------------------------===//
434
435class PNaClABIInfo : public ABIInfo {
436 public:
437 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
438
439 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000440 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff9ed63f82012-09-06 17:37:28 +0000441
442 virtual void computeInfo(CGFunctionInfo &FI) const;
443 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
444 CodeGenFunction &CGF) const;
445};
446
447class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
448 public:
449 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
450 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
451};
452
453void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
454 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
455
Derek Schuff9ed63f82012-09-06 17:37:28 +0000456 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
457 it != ie; ++it)
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000458 it->info = classifyArgumentType(it->type);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000459 }
460
461llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
462 CodeGenFunction &CGF) const {
463 return 0;
464}
465
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000466/// \brief Classify argument of given type \p Ty.
467ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff9ed63f82012-09-06 17:37:28 +0000468 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +0000469 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000470 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Derek Schuff9ed63f82012-09-06 17:37:28 +0000471 return ABIArgInfo::getIndirect(0);
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000472 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
473 // Treat an enum type as its underlying type.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000474 Ty = EnumTy->getDecl()->getIntegerType();
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000475 } else if (Ty->isFloatingType()) {
476 // Floating-point types don't go inreg.
477 return ABIArgInfo::getDirect();
Derek Schuff9ed63f82012-09-06 17:37:28 +0000478 }
Eli Benderskyc0783dc2013-04-08 21:31:01 +0000479
480 return (Ty->isPromotableIntegerType() ?
481 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff9ed63f82012-09-06 17:37:28 +0000482}
483
484ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
485 if (RetTy->isVoidType())
486 return ABIArgInfo::getIgnore();
487
Eli Benderskye45dfd12013-04-04 22:49:35 +0000488 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff9ed63f82012-09-06 17:37:28 +0000489 if (isAggregateTypeForABI(RetTy))
490 return ABIArgInfo::getIndirect(0);
491
492 // Treat an enum type as its underlying type.
493 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
494 RetTy = EnumTy->getDecl()->getIntegerType();
495
496 return (RetTy->isPromotableIntegerType() ?
497 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
498}
499
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000500/// IsX86_MMXType - Return true if this is an MMX type.
501bool IsX86_MMXType(llvm::Type *IRType) {
502 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendlingbb465d72010-10-18 03:41:31 +0000503 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
504 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
505 IRType->getScalarSizeInBits() != 64;
506}
507
Jay Foadef6de3d2011-07-11 09:56:20 +0000508static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000509 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000510 llvm::Type* Ty) {
Tim Northover1bea6532013-06-07 00:04:50 +0000511 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
512 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
513 // Invalid MMX constraint
514 return 0;
515 }
516
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000517 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover1bea6532013-06-07 00:04:50 +0000518 }
519
520 // No operation needed
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000521 return Ty;
522}
523
Chris Lattnerdce5ad02010-06-28 20:05:43 +0000524//===----------------------------------------------------------------------===//
525// X86-32 ABI Implementation
526//===----------------------------------------------------------------------===//
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000527
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000528/// X86_32ABIInfo - The X86-32 ABI information.
529class X86_32ABIInfo : public ABIInfo {
Rafael Espindolab48280b2012-07-31 02:44:24 +0000530 enum Class {
531 Integer,
532 Float
533 };
534
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000535 static const unsigned MinABIStackAlignInBytes = 4;
536
David Chisnall1e4249c2009-08-17 23:08:21 +0000537 bool IsDarwinVectorABI;
538 bool IsSmallStructInRegABI;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000539 bool IsWin32StructABI;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000540 unsigned DefaultNumRegisterParameters;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000541
542 static bool isRegisterSize(unsigned Size) {
543 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
544 }
545
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000546 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context,
547 unsigned callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000548
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000549 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
550 /// such that the argument will be passed in memory.
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000551 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal,
552 unsigned &FreeRegs) const;
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000553
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000554 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbare59d8582010-09-16 20:42:06 +0000555 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000556
Rafael Espindolab48280b2012-07-31 02:44:24 +0000557 Class classify(QualType Ty) const;
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000558 ABIArgInfo classifyReturnType(QualType RetTy,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000559 unsigned callingConvention) const;
Rafael Espindolab6932692012-10-24 01:58:58 +0000560 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs,
561 bool IsFastCall) const;
562 bool shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000563 bool IsFastCall, bool &NeedsPadding) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000564
Rafael Espindolab33a3c42012-07-23 23:30:29 +0000565public:
566
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000567 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000568 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
569 CodeGenFunction &CGF) const;
570
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000571 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindolab48280b2012-07-31 02:44:24 +0000572 unsigned r)
Eli Friedmanc3e0fb42011-07-08 23:31:17 +0000573 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000574 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000575};
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000576
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000577class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
578public:
Eli Friedman55fc7e22012-01-25 22:46:34 +0000579 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000580 bool d, bool p, bool w, unsigned r)
581 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis74f72932010-02-13 15:54:06 +0000582
John McCallb8b52972013-06-18 02:46:29 +0000583 static bool isStructReturnInRegABI(
584 const llvm::Triple &Triple, const CodeGenOptions &Opts);
585
Charles Davis74f72932010-02-13 15:54:06 +0000586 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
587 CodeGen::CodeGenModule &CGM) const;
John McCall6374c332010-03-06 00:35:14 +0000588
589 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
590 // Darwin uses different dwarf register numbers for EH.
John McCall64aa4b32013-04-16 22:48:15 +0000591 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCall6374c332010-03-06 00:35:14 +0000592 return 4;
593 }
594
595 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
596 llvm::Value *Address) const;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000597
Jay Foadef6de3d2011-07-11 09:56:20 +0000598 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000599 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +0000600 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000601 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
602 }
603
Peter Collingbourneb914e872013-10-20 21:29:19 +0000604 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
605 unsigned Sig = (0xeb << 0) | // jmp rel8
606 (0x06 << 8) | // .+0x08
607 ('F' << 16) |
608 ('T' << 24);
609 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
610 }
611
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000612};
613
614}
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000615
616/// shouldReturnTypeInRegister - Determine if the given type should be
617/// passed in a register (for the Darwin ABI).
618bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000619 ASTContext &Context,
620 unsigned callingConvention) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000621 uint64_t Size = Context.getTypeSize(Ty);
622
623 // Type must be register sized.
624 if (!isRegisterSize(Size))
625 return false;
626
627 if (Ty->isVectorType()) {
628 // 64- and 128- bit vectors inside structures are not returned in
629 // registers.
630 if (Size == 64 || Size == 128)
631 return false;
632
633 return true;
634 }
635
Daniel Dunbar77115232010-05-15 00:00:30 +0000636 // If this is a builtin, pointer, enum, complex type, member pointer, or
637 // member function pointer it is ok.
Daniel Dunbara1842d32010-05-14 03:40:53 +0000638 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbar55e59e12009-09-24 05:12:36 +0000639 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar77115232010-05-15 00:00:30 +0000640 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000641 return true;
642
643 // Arrays are treated like records.
644 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000645 return shouldReturnTypeInRegister(AT->getElementType(), Context,
646 callingConvention);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000647
648 // Otherwise, it must be a record type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000649 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000650 if (!RT) return false;
651
Anders Carlssona8874232010-01-27 03:25:19 +0000652 // FIXME: Traverse bases here too.
653
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000654 // For thiscall conventions, structures will never be returned in
655 // a register. This is for compatibility with the MSVC ABI
656 if (callingConvention == llvm::CallingConv::X86_ThisCall &&
657 RT->isStructureType()) {
658 return false;
659 }
660
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000661 // Structure types are passed in register if all fields would be
662 // passed in a register.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000663 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(),
664 e = RT->getDecl()->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +0000665 const FieldDecl *FD = *i;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000666
667 // Empty fields are ignored.
Daniel Dunbar98303b92009-09-13 08:03:58 +0000668 if (isEmptyField(Context, FD, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000669 continue;
670
671 // Check fields recursively.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000672 if (!shouldReturnTypeInRegister(FD->getType(), Context,
673 callingConvention))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000674 return false;
675 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000676 return true;
677}
678
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000679ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
680 unsigned callingConvention) const {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000681 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000682 return ABIArgInfo::getIgnore();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000683
Chris Lattnera3c109b2010-07-29 02:16:43 +0000684 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000685 // On Darwin, some vectors are returned in registers.
David Chisnall1e4249c2009-08-17 23:08:21 +0000686 if (IsDarwinVectorABI) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000687 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000688
689 // 128-bit vectors are a special case; they are returned in
690 // registers and we need to make sure to pick a type the LLVM
691 // backend will like.
692 if (Size == 128)
Chris Lattner800588f2010-07-29 06:26:06 +0000693 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattnera3c109b2010-07-29 02:16:43 +0000694 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000695
696 // Always return in register if it fits in a general purpose
697 // register, or if it is 64 bits and has a single element.
698 if ((Size == 8 || Size == 16 || Size == 32) ||
699 (Size == 64 && VT->getNumElements() == 1))
Chris Lattner800588f2010-07-29 06:26:06 +0000700 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +0000701 Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000702
703 return ABIArgInfo::getIndirect(0);
704 }
705
706 return ABIArgInfo::getDirect();
Chris Lattnera3c109b2010-07-29 02:16:43 +0000707 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000708
John McCalld608cdb2010-08-22 10:59:02 +0000709 if (isAggregateTypeForABI(RetTy)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000710 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Mark Lacey23630722013-10-06 01:33:34 +0000711 if (isRecordReturnIndirect(RT, getCXXABI()))
Anders Carlsson40092972009-10-20 22:07:59 +0000712 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000713
Anders Carlsson40092972009-10-20 22:07:59 +0000714 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000715 if (RT->getDecl()->hasFlexibleArrayMember())
716 return ABIArgInfo::getIndirect(0);
Anders Carlsson40092972009-10-20 22:07:59 +0000717 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000718
David Chisnall1e4249c2009-08-17 23:08:21 +0000719 // If specified, structs and unions are always indirect.
720 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000721 return ABIArgInfo::getIndirect(0);
722
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000723 // Small structures which are register sized are generally returned
724 // in a register.
Aaron Ballman6c60c8d2012-02-22 03:04:13 +0000725 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, getContext(),
726 callingConvention)) {
Chris Lattnera3c109b2010-07-29 02:16:43 +0000727 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000728
729 // As a special-case, if the struct is a "single-element" struct, and
730 // the field is of type "float" or "double", return it in a
Eli Friedman55fc7e22012-01-25 22:46:34 +0000731 // floating-point register. (MSVC does not apply this special case.)
732 // We apply a similar transformation for pointer types to improve the
733 // quality of the generated IR.
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000734 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000735 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedman55fc7e22012-01-25 22:46:34 +0000736 || SeltTy->hasPointerRepresentation())
Eli Friedmanbd4d3bc2011-11-18 01:25:50 +0000737 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
738
739 // FIXME: We should be able to narrow this integer in cases with dead
740 // padding.
Chris Lattner800588f2010-07-29 06:26:06 +0000741 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000742 }
743
744 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000745 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000746
Chris Lattnera3c109b2010-07-29 02:16:43 +0000747 // Treat an enum type as its underlying type.
748 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
749 RetTy = EnumTy->getDecl()->getIntegerType();
750
751 return (RetTy->isPromotableIntegerType() ?
752 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000753}
754
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000755static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
756 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
757}
758
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000759static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
760 const RecordType *RT = Ty->getAs<RecordType>();
761 if (!RT)
762 return 0;
763 const RecordDecl *RD = RT->getDecl();
764
765 // If this is a C++ record, check the bases first.
766 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
767 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
768 e = CXXRD->bases_end(); i != e; ++i)
769 if (!isRecordWithSSEVectorType(Context, i->getType()))
770 return false;
771
772 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
773 i != e; ++i) {
774 QualType FT = i->getType();
775
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000776 if (isSSEVectorType(Context, FT))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000777 return true;
778
779 if (isRecordWithSSEVectorType(Context, FT))
780 return true;
781 }
782
783 return false;
784}
785
Daniel Dunbare59d8582010-09-16 20:42:06 +0000786unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
787 unsigned Align) const {
788 // Otherwise, if the alignment is less than or equal to the minimum ABI
789 // alignment, just use the default; the backend will handle this.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000790 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbare59d8582010-09-16 20:42:06 +0000791 return 0; // Use default alignment.
792
793 // On non-Darwin, the stack type alignment is always 4.
794 if (!IsDarwinVectorABI) {
795 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000796 return MinABIStackAlignInBytes;
Daniel Dunbare59d8582010-09-16 20:42:06 +0000797 }
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000798
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000799 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedmanf4bd4d82012-06-05 19:40:46 +0000800 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
801 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbar93ae9472010-09-16 20:42:00 +0000802 return 16;
803
804 return MinABIStackAlignInBytes;
Daniel Dunbarfb67d6c2010-09-16 20:41:56 +0000805}
806
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000807ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
808 unsigned &FreeRegs) const {
809 if (!ByVal) {
810 if (FreeRegs) {
811 --FreeRegs; // Non byval indirects just use one pointer.
812 return ABIArgInfo::getIndirectInReg(0, false);
813 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000814 return ABIArgInfo::getIndirect(0, false);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000815 }
Daniel Dunbar46c54fb2010-04-21 19:49:55 +0000816
Daniel Dunbare59d8582010-09-16 20:42:06 +0000817 // Compute the byval alignment.
818 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
819 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
820 if (StackAlign == 0)
Chris Lattnerde92d732011-05-22 23:35:00 +0000821 return ABIArgInfo::getIndirect(4);
Daniel Dunbare59d8582010-09-16 20:42:06 +0000822
823 // If the stack alignment is less than the type alignment, realign the
824 // argument.
825 if (StackAlign < TypeAlign)
826 return ABIArgInfo::getIndirect(StackAlign, /*ByVal=*/true,
827 /*Realign=*/true);
828
829 return ABIArgInfo::getIndirect(StackAlign);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000830}
831
Rafael Espindolab48280b2012-07-31 02:44:24 +0000832X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
833 const Type *T = isSingleElementStruct(Ty, getContext());
834 if (!T)
835 T = Ty.getTypePtr();
836
837 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
838 BuiltinType::Kind K = BT->getKind();
839 if (K == BuiltinType::Float || K == BuiltinType::Double)
840 return Float;
841 }
842 return Integer;
843}
844
Rafael Espindolab6932692012-10-24 01:58:58 +0000845bool X86_32ABIInfo::shouldUseInReg(QualType Ty, unsigned &FreeRegs,
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000846 bool IsFastCall, bool &NeedsPadding) const {
847 NeedsPadding = false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000848 Class C = classify(Ty);
849 if (C == Float)
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000850 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000851
Rafael Espindolab6932692012-10-24 01:58:58 +0000852 unsigned Size = getContext().getTypeSize(Ty);
853 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindola5f14fcb2012-10-23 02:04:01 +0000854
855 if (SizeInRegs == 0)
856 return false;
857
Rafael Espindolab48280b2012-07-31 02:44:24 +0000858 if (SizeInRegs > FreeRegs) {
859 FreeRegs = 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000860 return false;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000861 }
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000862
Rafael Espindolab48280b2012-07-31 02:44:24 +0000863 FreeRegs -= SizeInRegs;
Rafael Espindolab6932692012-10-24 01:58:58 +0000864
865 if (IsFastCall) {
866 if (Size > 32)
867 return false;
868
869 if (Ty->isIntegralOrEnumerationType())
870 return true;
871
872 if (Ty->isPointerType())
873 return true;
874
875 if (Ty->isReferenceType())
876 return true;
877
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000878 if (FreeRegs)
879 NeedsPadding = true;
880
Rafael Espindolab6932692012-10-24 01:58:58 +0000881 return false;
882 }
883
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000884 return true;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000885}
886
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000887ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Rafael Espindolab6932692012-10-24 01:58:58 +0000888 unsigned &FreeRegs,
889 bool IsFastCall) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000890 // FIXME: Set alignment on indirect arguments.
John McCalld608cdb2010-08-22 10:59:02 +0000891 if (isAggregateTypeForABI(Ty)) {
Anders Carlssona8874232010-01-27 03:25:19 +0000892 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000893 if (IsWin32StructABI)
894 return getIndirectResult(Ty, true, FreeRegs);
Daniel Dunbardc6d5742010-04-21 19:10:51 +0000895
Mark Lacey23630722013-10-06 01:33:34 +0000896 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +0000897 return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs);
898
899 // Structures with flexible arrays are always indirect.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000900 if (RT->getDecl()->hasFlexibleArrayMember())
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000901 return getIndirectResult(Ty, true, FreeRegs);
Anders Carlssona8874232010-01-27 03:25:19 +0000902 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000903
Eli Friedman5a4d3522011-11-18 00:28:11 +0000904 // Ignore empty structs/unions.
Eli Friedman5a1ac892011-11-18 04:01:36 +0000905 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000906 return ABIArgInfo::getIgnore();
907
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000908 llvm::LLVMContext &LLVMContext = getVMContext();
909 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
910 bool NeedsPadding;
911 if (shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding)) {
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000912 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperb9bad792013-07-08 04:47:18 +0000913 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000914 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
915 return ABIArgInfo::getDirectInReg(Result);
916 }
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000917 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : 0;
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000918
Daniel Dunbar53012f42009-11-09 01:33:53 +0000919 // Expand small (<= 128-bit) record types when we know that the stack layout
920 // of those arguments will match the struct. This is important because the
921 // LLVM backend isn't smart enough to remove byval, which inhibits many
922 // optimizations.
Chris Lattnera3c109b2010-07-29 02:16:43 +0000923 if (getContext().getTypeSize(Ty) <= 4*32 &&
924 canExpandIndirectArgument(Ty, getContext()))
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000925 return ABIArgInfo::getExpandWithPadding(IsFastCall, PaddingType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000926
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000927 return getIndirectResult(Ty, true, FreeRegs);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +0000928 }
929
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000930 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner7b733502010-08-26 20:08:43 +0000931 // On Darwin, some vectors are passed in memory, we handle this by passing
932 // it as an i8/i16/i32/i64.
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000933 if (IsDarwinVectorABI) {
934 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000935 if ((Size == 8 || Size == 16 || Size == 32) ||
936 (Size == 64 && VT->getNumElements() == 1))
937 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
938 Size));
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000939 }
Bill Wendlingbb465d72010-10-18 03:41:31 +0000940
Chad Rosier1f1df1f2013-03-25 21:00:27 +0000941 if (IsX86_MMXType(CGT.ConvertType(Ty)))
942 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000943
Chris Lattnerbbae8b42010-08-26 20:05:13 +0000944 return ABIArgInfo::getDirect();
945 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +0000946
947
Chris Lattnera3c109b2010-07-29 02:16:43 +0000948 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
949 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000950
Rafael Espindolae4aeeaa2012-10-24 01:59:00 +0000951 bool NeedsPadding;
952 bool InReg = shouldUseInReg(Ty, FreeRegs, IsFastCall, NeedsPadding);
Rafael Espindola0b4cc952012-10-19 05:04:37 +0000953
954 if (Ty->isPromotableIntegerType()) {
955 if (InReg)
956 return ABIArgInfo::getExtendInReg();
957 return ABIArgInfo::getExtend();
958 }
959 if (InReg)
960 return ABIArgInfo::getDirectInReg();
961 return ABIArgInfo::getDirect();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000962}
963
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000964void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
965 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(),
966 FI.getCallingConvention());
Rafael Espindolab48280b2012-07-31 02:44:24 +0000967
Rafael Espindolab6932692012-10-24 01:58:58 +0000968 unsigned CC = FI.getCallingConvention();
969 bool IsFastCall = CC == llvm::CallingConv::X86_FastCall;
970 unsigned FreeRegs;
971 if (IsFastCall)
972 FreeRegs = 2;
973 else if (FI.getHasRegParm())
974 FreeRegs = FI.getRegParm();
975 else
976 FreeRegs = DefaultNumRegisterParameters;
Rafael Espindolab48280b2012-07-31 02:44:24 +0000977
978 // If the return value is indirect, then the hidden argument is consuming one
979 // integer register.
980 if (FI.getReturnInfo().isIndirect() && FreeRegs) {
981 --FreeRegs;
982 ABIArgInfo &Old = FI.getReturnInfo();
983 Old = ABIArgInfo::getIndirectInReg(Old.getIndirectAlign(),
984 Old.getIndirectByVal(),
985 Old.getIndirectRealign());
986 }
987
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000988 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
989 it != ie; ++it)
Rafael Espindolab6932692012-10-24 01:58:58 +0000990 it->info = classifyArgumentType(it->type, FreeRegs, IsFastCall);
Rafael Espindolaaa9cf8d2012-07-24 00:01:07 +0000991}
992
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000993llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
994 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +0000995 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +0000996
997 CGBuilderTy &Builder = CGF.Builder;
998 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
999 "ap");
1000 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Eli Friedman7b1fb812011-11-18 02:12:09 +00001001
1002 // Compute if the address needs to be aligned
1003 unsigned Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
1004 Align = getTypeStackAlignInBytes(Ty, Align);
1005 Align = std::max(Align, 4U);
1006 if (Align > 4) {
1007 // addr = (addr + align - 1) & -align;
1008 llvm::Value *Offset =
1009 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1);
1010 Addr = CGF.Builder.CreateGEP(Addr, Offset);
1011 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(Addr,
1012 CGF.Int32Ty);
1013 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -Align);
1014 Addr = CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1015 Addr->getType(),
1016 "ap.cur.aligned");
1017 }
1018
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001019 llvm::Type *PTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +00001020 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001021 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1022
1023 uint64_t Offset =
Eli Friedman7b1fb812011-11-18 02:12:09 +00001024 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001025 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00001026 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001027 "ap.next");
1028 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1029
1030 return AddrTyped;
1031}
1032
Charles Davis74f72932010-02-13 15:54:06 +00001033void X86_32TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
1034 llvm::GlobalValue *GV,
1035 CodeGen::CodeGenModule &CGM) const {
1036 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1037 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1038 // Get the LLVM function.
1039 llvm::Function *Fn = cast<llvm::Function>(GV);
1040
1041 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendling0d583392012-10-15 20:36:26 +00001042 llvm::AttrBuilder B;
Bill Wendlinge91e9ec2012-10-14 03:28:14 +00001043 B.addStackAlignmentAttr(16);
Bill Wendling909b6de2013-01-23 00:21:06 +00001044 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1045 llvm::AttributeSet::get(CGM.getLLVMContext(),
1046 llvm::AttributeSet::FunctionIndex,
1047 B));
Charles Davis74f72932010-02-13 15:54:06 +00001048 }
1049 }
1050}
1051
John McCall6374c332010-03-06 00:35:14 +00001052bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1053 CodeGen::CodeGenFunction &CGF,
1054 llvm::Value *Address) const {
1055 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCall6374c332010-03-06 00:35:14 +00001056
Chris Lattner8b418682012-02-07 00:39:47 +00001057 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001058
John McCall6374c332010-03-06 00:35:14 +00001059 // 0-7 are the eight integer registers; the order is different
1060 // on Darwin (for EH), but the range is the same.
1061 // 8 is %eip.
John McCallaeeb7012010-05-27 06:19:26 +00001062 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCall6374c332010-03-06 00:35:14 +00001063
John McCall64aa4b32013-04-16 22:48:15 +00001064 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCall6374c332010-03-06 00:35:14 +00001065 // 12-16 are st(0..4). Not sure why we stop at 4.
1066 // These have size 16, which is sizeof(long double) on
1067 // platforms with 8-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001068 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCallaeeb7012010-05-27 06:19:26 +00001069 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001070
John McCall6374c332010-03-06 00:35:14 +00001071 } else {
1072 // 9 is %eflags, which doesn't get a size on Darwin for some
1073 // reason.
1074 Builder.CreateStore(Four8, Builder.CreateConstInBoundsGEP1_32(Address, 9));
1075
1076 // 11-16 are st(0..5). Not sure why we stop at 5.
1077 // These have size 12, which is sizeof(long double) on
1078 // platforms with 4-byte alignment for that type.
Chris Lattner8b418682012-02-07 00:39:47 +00001079 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCallaeeb7012010-05-27 06:19:26 +00001080 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1081 }
John McCall6374c332010-03-06 00:35:14 +00001082
1083 return false;
1084}
1085
Chris Lattnerdce5ad02010-06-28 20:05:43 +00001086//===----------------------------------------------------------------------===//
1087// X86-64 ABI Implementation
1088//===----------------------------------------------------------------------===//
1089
1090
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001091namespace {
1092/// X86_64ABIInfo - The X86_64 ABI information.
1093class X86_64ABIInfo : public ABIInfo {
1094 enum Class {
1095 Integer = 0,
1096 SSE,
1097 SSEUp,
1098 X87,
1099 X87Up,
1100 ComplexX87,
1101 NoClass,
1102 Memory
1103 };
1104
1105 /// merge - Implement the X86_64 ABI merging algorithm.
1106 ///
1107 /// Merge an accumulating classification \arg Accum with a field
1108 /// classification \arg Field.
1109 ///
1110 /// \param Accum - The accumulating classification. This should
1111 /// always be either NoClass or the result of a previous merge
1112 /// call. In addition, this should never be Memory (the caller
1113 /// should just return Memory for the aggregate).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001114 static Class merge(Class Accum, Class Field);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001115
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001116 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1117 ///
1118 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1119 /// final MEMORY or SSE classes when necessary.
1120 ///
1121 /// \param AggregateSize - The size of the current aggregate in
1122 /// the classification process.
1123 ///
1124 /// \param Lo - The classification for the parts of the type
1125 /// residing in the low word of the containing object.
1126 ///
1127 /// \param Hi - The classification for the parts of the type
1128 /// residing in the higher words of the containing object.
1129 ///
1130 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1131
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001132 /// classify - Determine the x86_64 register classes in which the
1133 /// given type T should be passed.
1134 ///
1135 /// \param Lo - The classification for the parts of the type
1136 /// residing in the low word of the containing object.
1137 ///
1138 /// \param Hi - The classification for the parts of the type
1139 /// residing in the high word of the containing object.
1140 ///
1141 /// \param OffsetBase - The bit offset of this type in the
1142 /// containing object. Some parameters are classified different
1143 /// depending on whether they straddle an eightbyte boundary.
1144 ///
Eli Friedman7a1b5862013-06-12 00:13:45 +00001145 /// \param isNamedArg - Whether the argument in question is a "named"
1146 /// argument, as used in AMD64-ABI 3.5.7.
1147 ///
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001148 /// If a word is unused its result will be NoClass; if a type should
1149 /// be passed in Memory then at least the classification of \arg Lo
1150 /// will be Memory.
1151 ///
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00001152 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001153 ///
1154 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1155 /// also be ComplexX87.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001156 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1157 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001158
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001159 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001160 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1161 unsigned IROffset, QualType SourceTy,
1162 unsigned SourceOffset) const;
1163 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1164 unsigned IROffset, QualType SourceTy,
1165 unsigned SourceOffset) const;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001166
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001167 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001168 /// such that the argument will be returned in memory.
Chris Lattner9c254f02010-06-29 06:01:59 +00001169 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001170
1171 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001172 /// such that the argument will be passed in memory.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001173 ///
1174 /// \param freeIntRegs - The number of free integer registers remaining
1175 /// available.
1176 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001177
Chris Lattnera3c109b2010-07-29 02:16:43 +00001178 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001179
Bill Wendlingbb465d72010-10-18 03:41:31 +00001180 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbaredfac032012-03-10 01:03:58 +00001181 unsigned freeIntRegs,
Bill Wendlingbb465d72010-10-18 03:41:31 +00001182 unsigned &neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001183 unsigned &neededSSE,
1184 bool isNamedArg) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001185
Eli Friedmanee1ad992011-12-02 00:11:43 +00001186 bool IsIllegalVectorType(QualType Ty) const;
1187
John McCall67a57732011-04-21 01:20:55 +00001188 /// The 0.98 ABI revision clarified a lot of ambiguities,
1189 /// unfortunately in ways that were not always consistent with
1190 /// certain previous compilers. In particular, platforms which
1191 /// required strict binary compatibility with older versions of GCC
1192 /// may need to exempt themselves.
1193 bool honorsRevision0_98() const {
John McCall64aa4b32013-04-16 22:48:15 +00001194 return !getTarget().getTriple().isOSDarwin();
John McCall67a57732011-04-21 01:20:55 +00001195 }
1196
Eli Friedmanee1ad992011-12-02 00:11:43 +00001197 bool HasAVX;
Derek Schuffbabaf312012-10-11 15:52:22 +00001198 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1199 // 64-bit hardware.
1200 bool Has64BitPointers;
Eli Friedmanee1ad992011-12-02 00:11:43 +00001201
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001202public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001203 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool hasavx) :
Derek Schuffbabaf312012-10-11 15:52:22 +00001204 ABIInfo(CGT), HasAVX(hasavx),
Derek Schuff90da80c2012-10-11 18:21:13 +00001205 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001206 }
Chris Lattner9c254f02010-06-29 06:01:59 +00001207
John McCallde5d3c72012-02-17 03:33:10 +00001208 bool isPassedUsingAVXType(QualType type) const {
1209 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00001210 // The freeIntRegs argument doesn't matter here.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001211 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1212 /*isNamedArg*/true);
John McCallde5d3c72012-02-17 03:33:10 +00001213 if (info.isDirect()) {
1214 llvm::Type *ty = info.getCoerceToType();
1215 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1216 return (vectorTy->getBitWidth() > 128);
1217 }
1218 return false;
1219 }
1220
Chris Lattneree5dcd02010-07-29 02:31:05 +00001221 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001222
1223 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1224 CodeGenFunction &CGF) const;
1225};
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001226
Chris Lattnerf13721d2010-08-31 16:44:54 +00001227/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001228class WinX86_64ABIInfo : public ABIInfo {
1229
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001230 ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001231
Chris Lattnerf13721d2010-08-31 16:44:54 +00001232public:
NAKAMURA Takumia7573222011-01-17 22:56:31 +00001233 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1234
1235 virtual void computeInfo(CGFunctionInfo &FI) const;
Chris Lattnerf13721d2010-08-31 16:44:54 +00001236
1237 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1238 CodeGenFunction &CGF) const;
1239};
1240
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001241class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1242public:
Eli Friedmanee1ad992011-12-02 00:11:43 +00001243 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
Derek Schuffbabaf312012-10-11 15:52:22 +00001244 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, HasAVX)) {}
John McCall6374c332010-03-06 00:35:14 +00001245
John McCallde5d3c72012-02-17 03:33:10 +00001246 const X86_64ABIInfo &getABIInfo() const {
1247 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1248 }
1249
John McCall6374c332010-03-06 00:35:14 +00001250 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1251 return 7;
1252 }
1253
1254 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1255 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001256 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001257
John McCallaeeb7012010-05-27 06:19:26 +00001258 // 0-15 are the 16 integer registers.
1259 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001260 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCall6374c332010-03-06 00:35:14 +00001261 return false;
1262 }
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001263
Jay Foadef6de3d2011-07-11 09:56:20 +00001264 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001265 StringRef Constraint,
Jay Foadef6de3d2011-07-11 09:56:20 +00001266 llvm::Type* Ty) const {
Peter Collingbourne4b93d662011-02-19 23:03:58 +00001267 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1268 }
1269
John McCallde5d3c72012-02-17 03:33:10 +00001270 bool isNoProtoCallVariadic(const CallArgList &args,
1271 const FunctionNoProtoType *fnType) const {
John McCall01f151e2011-09-21 08:08:30 +00001272 // The default CC on x86-64 sets %al to the number of SSA
1273 // registers used, and GCC sets this when calling an unprototyped
Eli Friedman3ed79032011-12-01 04:53:19 +00001274 // function, so we override the default behavior. However, don't do
Eli Friedman68805fe2011-12-06 03:08:26 +00001275 // that when AVX types are involved: the ABI explicitly states it is
1276 // undefined, and it doesn't work in practice because of how the ABI
1277 // defines varargs anyway.
Reid Kleckneref072032013-08-27 23:08:25 +00001278 if (fnType->getCallConv() == CC_C) {
Eli Friedman3ed79032011-12-01 04:53:19 +00001279 bool HasAVXType = false;
John McCallde5d3c72012-02-17 03:33:10 +00001280 for (CallArgList::const_iterator
1281 it = args.begin(), ie = args.end(); it != ie; ++it) {
1282 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1283 HasAVXType = true;
1284 break;
Eli Friedman3ed79032011-12-01 04:53:19 +00001285 }
1286 }
John McCallde5d3c72012-02-17 03:33:10 +00001287
Eli Friedman3ed79032011-12-01 04:53:19 +00001288 if (!HasAVXType)
1289 return true;
1290 }
John McCall01f151e2011-09-21 08:08:30 +00001291
John McCallde5d3c72012-02-17 03:33:10 +00001292 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCall01f151e2011-09-21 08:08:30 +00001293 }
1294
Peter Collingbourneb914e872013-10-20 21:29:19 +00001295 llvm::Constant *getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const {
1296 unsigned Sig = (0xeb << 0) | // jmp rel8
1297 (0x0a << 8) | // .+0x0c
1298 ('F' << 16) |
1299 ('T' << 24);
1300 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1301 }
1302
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00001303};
1304
Aaron Ballman89735b92013-05-24 15:06:56 +00001305static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
1306 // If the argument does not end in .lib, automatically add the suffix. This
1307 // matches the behavior of MSVC.
1308 std::string ArgStr = Lib;
1309 if (Lib.size() <= 4 ||
1310 Lib.substr(Lib.size() - 4).compare_lower(".lib") != 0) {
1311 ArgStr += ".lib";
1312 }
1313 return ArgStr;
1314}
1315
Reid Kleckner3190ca92013-05-08 13:44:39 +00001316class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1317public:
John McCallb8b52972013-06-18 02:46:29 +00001318 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1319 bool d, bool p, bool w, unsigned RegParms)
1320 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Kleckner3190ca92013-05-08 13:44:39 +00001321
1322 void getDependentLibraryOption(llvm::StringRef Lib,
1323 llvm::SmallString<24> &Opt) const {
1324 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001325 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001326 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001327
1328 void getDetectMismatchOption(llvm::StringRef Name,
1329 llvm::StringRef Value,
1330 llvm::SmallString<32> &Opt) const {
Eli Friedman572ac322013-06-07 22:42:22 +00001331 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001332 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001333};
1334
Chris Lattnerf13721d2010-08-31 16:44:54 +00001335class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1336public:
1337 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
1338 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
1339
1340 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
1341 return 7;
1342 }
1343
1344 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1345 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00001346 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00001347
Chris Lattnerf13721d2010-08-31 16:44:54 +00001348 // 0-15 are the 16 integer registers.
1349 // 16 is %rip.
Chris Lattner8b418682012-02-07 00:39:47 +00001350 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattnerf13721d2010-08-31 16:44:54 +00001351 return false;
1352 }
Reid Kleckner3190ca92013-05-08 13:44:39 +00001353
1354 void getDependentLibraryOption(llvm::StringRef Lib,
1355 llvm::SmallString<24> &Opt) const {
1356 Opt = "/DEFAULTLIB:";
Aaron Ballman89735b92013-05-24 15:06:56 +00001357 Opt += qualifyWindowsLibrary(Lib);
Reid Kleckner3190ca92013-05-08 13:44:39 +00001358 }
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001359
1360 void getDetectMismatchOption(llvm::StringRef Name,
1361 llvm::StringRef Value,
1362 llvm::SmallString<32> &Opt) const {
Eli Friedman572ac322013-06-07 22:42:22 +00001363 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballmana7ff62f2013-06-04 02:07:14 +00001364 }
Chris Lattnerf13721d2010-08-31 16:44:54 +00001365};
1366
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001367}
1368
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001369void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1370 Class &Hi) const {
1371 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1372 //
1373 // (a) If one of the classes is Memory, the whole argument is passed in
1374 // memory.
1375 //
1376 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1377 // memory.
1378 //
1379 // (c) If the size of the aggregate exceeds two eightbytes and the first
1380 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1381 // argument is passed in memory. NOTE: This is necessary to keep the
1382 // ABI working for processors that don't support the __m256 type.
1383 //
1384 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1385 //
1386 // Some of these are enforced by the merging logic. Others can arise
1387 // only with unions; for example:
1388 // union { _Complex double; unsigned; }
1389 //
1390 // Note that clauses (b) and (c) were added in 0.98.
1391 //
1392 if (Hi == Memory)
1393 Lo = Memory;
1394 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1395 Lo = Memory;
1396 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1397 Lo = Memory;
1398 if (Hi == SSEUp && Lo != SSE)
1399 Hi = SSE;
1400}
1401
Chris Lattner1090a9b2010-06-28 21:43:59 +00001402X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001403 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1404 // classified recursively so that always two fields are
1405 // considered. The resulting class is calculated according to
1406 // the classes of the fields in the eightbyte:
1407 //
1408 // (a) If both classes are equal, this is the resulting class.
1409 //
1410 // (b) If one of the classes is NO_CLASS, the resulting class is
1411 // the other class.
1412 //
1413 // (c) If one of the classes is MEMORY, the result is the MEMORY
1414 // class.
1415 //
1416 // (d) If one of the classes is INTEGER, the result is the
1417 // INTEGER.
1418 //
1419 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
1420 // MEMORY is used as class.
1421 //
1422 // (f) Otherwise class SSE is used.
1423
1424 // Accum should never be memory (we should have returned) or
1425 // ComplexX87 (because this cannot be passed in a structure).
1426 assert((Accum != Memory && Accum != ComplexX87) &&
1427 "Invalid accumulated classification during merge.");
1428 if (Accum == Field || Field == NoClass)
1429 return Accum;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001430 if (Field == Memory)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001431 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001432 if (Accum == NoClass)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001433 return Field;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001434 if (Accum == Integer || Field == Integer)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001435 return Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001436 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
1437 Accum == X87 || Accum == X87Up)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001438 return Memory;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001439 return SSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001440}
1441
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001442void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman7a1b5862013-06-12 00:13:45 +00001443 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001444 // FIXME: This code can be simplified by introducing a simple value class for
1445 // Class pairs with appropriate constructor methods for the various
1446 // situations.
1447
1448 // FIXME: Some of the split computations are wrong; unaligned vectors
1449 // shouldn't be passed in registers for example, so there is no chance they
1450 // can straddle an eightbyte. Verify & simplify.
1451
1452 Lo = Hi = NoClass;
1453
1454 Class &Current = OffsetBase < 64 ? Lo : Hi;
1455 Current = Memory;
1456
John McCall183700f2009-09-21 23:43:11 +00001457 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001458 BuiltinType::Kind k = BT->getKind();
1459
1460 if (k == BuiltinType::Void) {
1461 Current = NoClass;
1462 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
1463 Lo = Integer;
1464 Hi = Integer;
1465 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
1466 Current = Integer;
Derek Schuff7da46f92012-10-11 16:55:58 +00001467 } else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
1468 (k == BuiltinType::LongDouble &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001469 getTarget().getTriple().isOSNaCl())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001470 Current = SSE;
1471 } else if (k == BuiltinType::LongDouble) {
1472 Lo = X87;
1473 Hi = X87Up;
1474 }
1475 // FIXME: _Decimal32 and _Decimal64 are SSE.
1476 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattner1090a9b2010-06-28 21:43:59 +00001477 return;
1478 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001479
Chris Lattner1090a9b2010-06-28 21:43:59 +00001480 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001481 // Classify the underlying integer type.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001482 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattner1090a9b2010-06-28 21:43:59 +00001483 return;
1484 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001485
Chris Lattner1090a9b2010-06-28 21:43:59 +00001486 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001487 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001488 return;
1489 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001490
Chris Lattner1090a9b2010-06-28 21:43:59 +00001491 if (Ty->isMemberPointerType()) {
Derek Schuffbabaf312012-10-11 15:52:22 +00001492 if (Ty->isMemberFunctionPointerType() && Has64BitPointers)
Daniel Dunbar67d438d2010-05-15 00:00:37 +00001493 Lo = Hi = Integer;
1494 else
1495 Current = Integer;
Chris Lattner1090a9b2010-06-28 21:43:59 +00001496 return;
1497 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001498
Chris Lattner1090a9b2010-06-28 21:43:59 +00001499 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001500 uint64_t Size = getContext().getTypeSize(VT);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001501 if (Size == 32) {
1502 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
1503 // float> as integer.
1504 Current = Integer;
1505
1506 // If this type crosses an eightbyte boundary, it should be
1507 // split.
1508 uint64_t EB_Real = (OffsetBase) / 64;
1509 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
1510 if (EB_Real != EB_Imag)
1511 Hi = Lo;
1512 } else if (Size == 64) {
1513 // gcc passes <1 x double> in memory. :(
1514 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
1515 return;
1516
1517 // gcc passes <1 x long long> as INTEGER.
Chris Lattner473f8e72010-08-26 18:03:20 +00001518 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner0fefa412010-08-26 18:13:50 +00001519 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
1520 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
1521 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001522 Current = Integer;
1523 else
1524 Current = SSE;
1525
1526 // If this type crosses an eightbyte boundary, it should be
1527 // split.
1528 if (OffsetBase && OffsetBase != 64)
1529 Hi = Lo;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001530 } else if (Size == 128 || (HasAVX && isNamedArg && Size == 256)) {
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001531 // Arguments of 256-bits are split into four eightbyte chunks. The
1532 // least significant one belongs to class SSE and all the others to class
1533 // SSEUP. The original Lo and Hi design considers that types can't be
1534 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
1535 // This design isn't correct for 256-bits, but since there're no cases
1536 // where the upper parts would need to be inspected, avoid adding
1537 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman7a1b5862013-06-12 00:13:45 +00001538 //
1539 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
1540 // registers if they are "named", i.e. not part of the "..." of a
1541 // variadic function.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001542 Lo = SSE;
1543 Hi = SSEUp;
1544 }
Chris Lattner1090a9b2010-06-28 21:43:59 +00001545 return;
1546 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001547
Chris Lattner1090a9b2010-06-28 21:43:59 +00001548 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001549 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001550
Chris Lattnerea044322010-07-29 02:01:43 +00001551 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001552 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001553 if (Size <= 64)
1554 Current = Integer;
1555 else if (Size <= 128)
1556 Lo = Hi = Integer;
Chris Lattnerea044322010-07-29 02:01:43 +00001557 } else if (ET == getContext().FloatTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001558 Current = SSE;
Derek Schuff7da46f92012-10-11 16:55:58 +00001559 else if (ET == getContext().DoubleTy ||
1560 (ET == getContext().LongDoubleTy &&
Cameron Esfahani57b1da12013-09-14 01:09:11 +00001561 getTarget().getTriple().isOSNaCl()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001562 Lo = Hi = SSE;
Chris Lattnerea044322010-07-29 02:01:43 +00001563 else if (ET == getContext().LongDoubleTy)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001564 Current = ComplexX87;
1565
1566 // If this complex type crosses an eightbyte boundary then it
1567 // should be split.
1568 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattnerea044322010-07-29 02:01:43 +00001569 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001570 if (Hi == NoClass && EB_Real != EB_Imag)
1571 Hi = Lo;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001572
Chris Lattner1090a9b2010-06-28 21:43:59 +00001573 return;
1574 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001575
Chris Lattnerea044322010-07-29 02:01:43 +00001576 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001577 // Arrays are treated like structures.
1578
Chris Lattnerea044322010-07-29 02:01:43 +00001579 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001580
1581 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001582 // than four eightbytes, ..., it has class MEMORY.
1583 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001584 return;
1585
1586 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
1587 // fields, it has class MEMORY.
1588 //
1589 // Only need to check alignment of array base.
Chris Lattnerea044322010-07-29 02:01:43 +00001590 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001591 return;
1592
1593 // Otherwise implement simplified merge. We could be smarter about
1594 // this, but it isn't worth it and would be harder to verify.
1595 Current = NoClass;
Chris Lattnerea044322010-07-29 02:01:43 +00001596 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001597 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes089d8922011-07-12 01:27:38 +00001598
1599 // The only case a 256-bit wide vector could be used is when the array
1600 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1601 // to work for sizes wider than 128, early check and fallback to memory.
1602 if (Size > 128 && EltSize != 256)
1603 return;
1604
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001605 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
1606 Class FieldLo, FieldHi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00001607 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001608 Lo = merge(Lo, FieldLo);
1609 Hi = merge(Hi, FieldHi);
1610 if (Lo == Memory || Hi == Memory)
1611 break;
1612 }
1613
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001614 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001615 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattner1090a9b2010-06-28 21:43:59 +00001616 return;
1617 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001618
Chris Lattner1090a9b2010-06-28 21:43:59 +00001619 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattnerea044322010-07-29 02:01:43 +00001620 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001621
1622 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001623 // than four eightbytes, ..., it has class MEMORY.
1624 if (Size > 256)
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001625 return;
1626
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001627 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
1628 // copy constructor or a non-trivial destructor, it is passed by invisible
1629 // reference.
Mark Lacey23630722013-10-06 01:33:34 +00001630 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001631 return;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001632
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001633 const RecordDecl *RD = RT->getDecl();
1634
1635 // Assume variable sized types are passed in memory.
1636 if (RD->hasFlexibleArrayMember())
1637 return;
1638
Chris Lattnerea044322010-07-29 02:01:43 +00001639 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001640
1641 // Reset Lo class, this will be recomputed.
1642 Current = NoClass;
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001643
1644 // If this is a C++ record, classify the bases first.
1645 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1646 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1647 e = CXXRD->bases_end(); i != e; ++i) {
1648 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1649 "Unexpected base class!");
1650 const CXXRecordDecl *Base =
1651 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
1652
1653 // Classify this field.
1654 //
1655 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
1656 // single eightbyte, each is classified separately. Each eightbyte gets
1657 // initialized to class NO_CLASS.
1658 Class FieldLo, FieldHi;
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001659 uint64_t Offset =
1660 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Eli Friedman7a1b5862013-06-12 00:13:45 +00001661 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbarce9f4232009-11-22 23:01:23 +00001662 Lo = merge(Lo, FieldLo);
1663 Hi = merge(Hi, FieldHi);
1664 if (Lo == Memory || Hi == Memory)
1665 break;
1666 }
1667 }
1668
1669 // Classify the fields one at a time, merging the results.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001670 unsigned idx = 0;
Bruno Cardoso Lopes548e4782011-07-12 22:30:58 +00001671 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001672 i != e; ++i, ++idx) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001673 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
1674 bool BitField = i->isBitField();
1675
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001676 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
1677 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001678 //
Bruno Cardoso Lopesb8981df2011-07-13 21:58:55 +00001679 // The only case a 256-bit wide vector could be used is when the struct
1680 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
1681 // to work for sizes wider than 128, early check and fallback to memory.
1682 //
1683 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
1684 Lo = Memory;
1685 return;
1686 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001687 // Note, skip this test for bit-fields, see below.
Chris Lattnerea044322010-07-29 02:01:43 +00001688 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001689 Lo = Memory;
1690 return;
1691 }
1692
1693 // Classify this field.
1694 //
1695 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
1696 // exceeds a single eightbyte, each is classified
1697 // separately. Each eightbyte gets initialized to class
1698 // NO_CLASS.
1699 Class FieldLo, FieldHi;
1700
1701 // Bit-fields require special handling, they do not force the
1702 // structure to be passed in memory even if unaligned, and
1703 // therefore they can straddle an eightbyte.
1704 if (BitField) {
1705 // Ignore padding bit-fields.
1706 if (i->isUnnamedBitfield())
1707 continue;
1708
1709 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001710 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001711
1712 uint64_t EB_Lo = Offset / 64;
1713 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru9a6002a2013-10-06 09:54:18 +00001714
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001715 if (EB_Lo) {
1716 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
1717 FieldLo = NoClass;
1718 FieldHi = Integer;
1719 } else {
1720 FieldLo = Integer;
1721 FieldHi = EB_Hi ? Integer : NoClass;
1722 }
1723 } else
Eli Friedman7a1b5862013-06-12 00:13:45 +00001724 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001725 Lo = merge(Lo, FieldLo);
1726 Hi = merge(Hi, FieldHi);
1727 if (Lo == Memory || Hi == Memory)
1728 break;
1729 }
1730
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001731 postMerge(Size, Lo, Hi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001732 }
1733}
1734
Chris Lattner9c254f02010-06-29 06:01:59 +00001735ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001736 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1737 // place naturally.
John McCalld608cdb2010-08-22 10:59:02 +00001738 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar46c54fb2010-04-21 19:49:55 +00001739 // Treat an enum type as its underlying type.
1740 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1741 Ty = EnumTy->getDecl()->getIntegerType();
1742
1743 return (Ty->isPromotableIntegerType() ?
1744 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
1745 }
1746
1747 return ABIArgInfo::getIndirect(0);
1748}
1749
Eli Friedmanee1ad992011-12-02 00:11:43 +00001750bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
1751 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
1752 uint64_t Size = getContext().getTypeSize(VecTy);
1753 unsigned LargestVector = HasAVX ? 256 : 128;
1754 if (Size <= 64 || Size > LargestVector)
1755 return true;
1756 }
1757
1758 return false;
1759}
1760
Daniel Dunbaredfac032012-03-10 01:03:58 +00001761ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
1762 unsigned freeIntRegs) const {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001763 // If this is a scalar LLVM value then assume LLVM will pass it in the right
1764 // place naturally.
Daniel Dunbaredfac032012-03-10 01:03:58 +00001765 //
1766 // This assumption is optimistic, as there could be free registers available
1767 // when we need to pass this argument in memory, and LLVM could try to pass
1768 // the argument in the free register. This does not seem to happen currently,
1769 // but this code would be much safer if we could mark the argument with
1770 // 'onstack'. See PR12193.
Eli Friedmanee1ad992011-12-02 00:11:43 +00001771 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001772 // Treat an enum type as its underlying type.
1773 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1774 Ty = EnumTy->getDecl()->getIntegerType();
1775
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00001776 return (Ty->isPromotableIntegerType() ?
1777 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001778 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001779
Mark Lacey23630722013-10-06 01:33:34 +00001780 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00001781 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson0a8f8472009-09-16 15:53:40 +00001782
Chris Lattner855d2272011-05-22 23:21:23 +00001783 // Compute the byval alignment. We specify the alignment of the byval in all
1784 // cases so that the mid-level optimizer knows the alignment of the byval.
1785 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbaredfac032012-03-10 01:03:58 +00001786
1787 // Attempt to avoid passing indirect results using byval when possible. This
1788 // is important for good codegen.
1789 //
1790 // We do this by coercing the value into a scalar type which the backend can
1791 // handle naturally (i.e., without using byval).
1792 //
1793 // For simplicity, we currently only do this when we have exhausted all of the
1794 // free integer registers. Doing this when there are free integer registers
1795 // would require more care, as we would have to ensure that the coerced value
1796 // did not claim the unused register. That would require either reording the
1797 // arguments to the function (so that any subsequent inreg values came first),
1798 // or only doing this optimization when there were no following arguments that
1799 // might be inreg.
1800 //
1801 // We currently expect it to be rare (particularly in well written code) for
1802 // arguments to be passed on the stack when there are still free integer
1803 // registers available (this would typically imply large structs being passed
1804 // by value), so this seems like a fair tradeoff for now.
1805 //
1806 // We can revisit this if the backend grows support for 'onstack' parameter
1807 // attributes. See PR12193.
1808 if (freeIntRegs == 0) {
1809 uint64_t Size = getContext().getTypeSize(Ty);
1810
1811 // If this type fits in an eightbyte, coerce it into the matching integral
1812 // type, which will end up on the stack (with alignment 8).
1813 if (Align == 8 && Size <= 64)
1814 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1815 Size));
1816 }
1817
Chris Lattner855d2272011-05-22 23:21:23 +00001818 return ABIArgInfo::getIndirect(Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00001819}
1820
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001821/// GetByteVectorType - The ABI specifies that a value should be passed in an
1822/// full vector XMM/YMM register. Pick an LLVM IR type that will be passed as a
Chris Lattner0f408f52010-07-29 04:56:46 +00001823/// vector register.
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001824llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001825 llvm::Type *IRType = CGT.ConvertType(Ty);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001826
Chris Lattner15842bd2010-07-29 05:02:29 +00001827 // Wrapper structs that just contain vectors are passed just like vectors,
1828 // strip them off if present.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001829 llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType);
Chris Lattner15842bd2010-07-29 05:02:29 +00001830 while (STy && STy->getNumElements() == 1) {
1831 IRType = STy->getElementType(0);
1832 STy = dyn_cast<llvm::StructType>(IRType);
1833 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001834
Bruno Cardoso Lopes528a8c72011-07-08 22:57:35 +00001835 // If the preferred type is a 16-byte vector, prefer to pass it.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001836 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(IRType)){
1837 llvm::Type *EltTy = VT->getElementType();
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00001838 unsigned BitWidth = VT->getBitWidth();
Tanya Lattnerce275672011-11-28 23:18:11 +00001839 if ((BitWidth >= 128 && BitWidth <= 256) &&
Chris Lattner0f408f52010-07-29 04:56:46 +00001840 (EltTy->isFloatTy() || EltTy->isDoubleTy() ||
1841 EltTy->isIntegerTy(8) || EltTy->isIntegerTy(16) ||
1842 EltTy->isIntegerTy(32) || EltTy->isIntegerTy(64) ||
1843 EltTy->isIntegerTy(128)))
1844 return VT;
1845 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001846
Chris Lattner0f408f52010-07-29 04:56:46 +00001847 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2);
1848}
1849
Chris Lattnere2962be2010-07-29 07:30:00 +00001850/// BitsContainNoUserData - Return true if the specified [start,end) bit range
1851/// is known to either be off the end of the specified type or being in
1852/// alignment padding. The user type specified is known to be at most 128 bits
1853/// in size, and have passed through X86_64ABIInfo::classify with a successful
1854/// classification that put one of the two halves in the INTEGER class.
1855///
1856/// It is conservatively correct to return false.
1857static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
1858 unsigned EndBit, ASTContext &Context) {
1859 // If the bytes being queried are off the end of the type, there is no user
1860 // data hiding here. This handles analysis of builtins, vectors and other
1861 // types that don't contain interesting padding.
1862 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
1863 if (TySize <= StartBit)
1864 return true;
1865
Chris Lattner021c3a32010-07-29 07:43:55 +00001866 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
1867 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
1868 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
1869
1870 // Check each element to see if the element overlaps with the queried range.
1871 for (unsigned i = 0; i != NumElts; ++i) {
1872 // If the element is after the span we care about, then we're done..
1873 unsigned EltOffset = i*EltSize;
1874 if (EltOffset >= EndBit) break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001875
Chris Lattner021c3a32010-07-29 07:43:55 +00001876 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
1877 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
1878 EndBit-EltOffset, Context))
1879 return false;
1880 }
1881 // If it overlaps no elements, then it is safe to process as padding.
1882 return true;
1883 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001884
Chris Lattnere2962be2010-07-29 07:30:00 +00001885 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1886 const RecordDecl *RD = RT->getDecl();
1887 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001888
Chris Lattnere2962be2010-07-29 07:30:00 +00001889 // If this is a C++ record, check the bases first.
1890 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1891 for (CXXRecordDecl::base_class_const_iterator i = CXXRD->bases_begin(),
1892 e = CXXRD->bases_end(); i != e; ++i) {
1893 assert(!i->isVirtual() && !i->getType()->isDependentType() &&
1894 "Unexpected base class!");
1895 const CXXRecordDecl *Base =
1896 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001897
Chris Lattnere2962be2010-07-29 07:30:00 +00001898 // If the base is after the span we care about, ignore it.
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001899 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnere2962be2010-07-29 07:30:00 +00001900 if (BaseOffset >= EndBit) continue;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001901
Chris Lattnere2962be2010-07-29 07:30:00 +00001902 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
1903 if (!BitsContainNoUserData(i->getType(), BaseStart,
1904 EndBit-BaseOffset, Context))
1905 return false;
1906 }
1907 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001908
Chris Lattnere2962be2010-07-29 07:30:00 +00001909 // Verify that no field has data that overlaps the region of interest. Yes
1910 // this could be sped up a lot by being smarter about queried fields,
1911 // however we're only looking at structs up to 16 bytes, so we don't care
1912 // much.
1913 unsigned idx = 0;
1914 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1915 i != e; ++i, ++idx) {
1916 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001917
Chris Lattnere2962be2010-07-29 07:30:00 +00001918 // If we found a field after the region we care about, then we're done.
1919 if (FieldOffset >= EndBit) break;
1920
1921 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
1922 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
1923 Context))
1924 return false;
1925 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001926
Chris Lattnere2962be2010-07-29 07:30:00 +00001927 // If nothing in this record overlapped the area of interest, then we're
1928 // clean.
1929 return true;
1930 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001931
Chris Lattnere2962be2010-07-29 07:30:00 +00001932 return false;
1933}
1934
Chris Lattner0b362002010-07-29 18:39:32 +00001935/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
1936/// float member at the specified offset. For example, {int,{float}} has a
1937/// float at offset 4. It is conservatively correct for this routine to return
1938/// false.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001939static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmow25a6a842012-10-08 16:25:52 +00001940 const llvm::DataLayout &TD) {
Chris Lattner0b362002010-07-29 18:39:32 +00001941 // Base case if we find a float.
1942 if (IROffset == 0 && IRType->isFloatTy())
1943 return true;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001944
Chris Lattner0b362002010-07-29 18:39:32 +00001945 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001946 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner0b362002010-07-29 18:39:32 +00001947 const llvm::StructLayout *SL = TD.getStructLayout(STy);
1948 unsigned Elt = SL->getElementContainingOffset(IROffset);
1949 IROffset -= SL->getElementOffset(Elt);
1950 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
1951 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001952
Chris Lattner0b362002010-07-29 18:39:32 +00001953 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001954 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
1955 llvm::Type *EltTy = ATy->getElementType();
Chris Lattner0b362002010-07-29 18:39:32 +00001956 unsigned EltSize = TD.getTypeAllocSize(EltTy);
1957 IROffset -= IROffset/EltSize*EltSize;
1958 return ContainsFloatAtOffset(EltTy, IROffset, TD);
1959 }
1960
1961 return false;
1962}
1963
Chris Lattnerf47c9442010-07-29 18:13:09 +00001964
1965/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
1966/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001967llvm::Type *X86_64ABIInfo::
1968GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattnerf47c9442010-07-29 18:13:09 +00001969 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnercba8d312010-07-29 18:19:50 +00001970 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattnerf47c9442010-07-29 18:13:09 +00001971 // pass as float if the last 4 bytes is just padding. This happens for
1972 // structs that contain 3 floats.
1973 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
1974 SourceOffset*8+64, getContext()))
1975 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001976
Chris Lattner0b362002010-07-29 18:39:32 +00001977 // We want to pass as <2 x float> if the LLVM IR type contains a float at
1978 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
1979 // case.
Micah Villmow25a6a842012-10-08 16:25:52 +00001980 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
1981 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner22fd4ba2010-08-25 23:39:14 +00001982 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00001983
Chris Lattnerf47c9442010-07-29 18:13:09 +00001984 return llvm::Type::getDoubleTy(getVMContext());
1985}
1986
1987
Chris Lattner0d2656d2010-07-29 17:40:35 +00001988/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
1989/// an 8-byte GPR. This means that we either have a scalar or we are talking
1990/// about the high or low part of an up-to-16-byte struct. This routine picks
1991/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattner49382de2010-07-28 22:44:07 +00001992/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
1993/// etc).
1994///
1995/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
1996/// the source type. IROffset is an offset in bytes into the LLVM IR type that
1997/// the 8-byte value references. PrefType may be null.
1998///
1999/// SourceTy is the source level type for the entire argument. SourceOffset is
2000/// an offset into this that we're processing (which is always either 0 or 8).
2001///
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002002llvm::Type *X86_64ABIInfo::
2003GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner0d2656d2010-07-29 17:40:35 +00002004 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnere2962be2010-07-29 07:30:00 +00002005 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2006 // returning an 8-byte unit starting with it. See if we can safely use it.
2007 if (IROffset == 0) {
2008 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffbabaf312012-10-11 15:52:22 +00002009 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2010 IRType->isIntegerTy(64))
Chris Lattnere2962be2010-07-29 07:30:00 +00002011 return IRType;
Chris Lattner49382de2010-07-28 22:44:07 +00002012
Chris Lattnere2962be2010-07-29 07:30:00 +00002013 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2014 // goodness in the source type is just tail padding. This is allowed to
2015 // kick in for struct {double,int} on the int, but not on
2016 // struct{double,int,int} because we wouldn't return the second int. We
2017 // have to do this analysis on the source type because we can't depend on
2018 // unions being lowered a specific way etc.
2019 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffbabaf312012-10-11 15:52:22 +00002020 IRType->isIntegerTy(32) ||
2021 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2022 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2023 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002024
Chris Lattnere2962be2010-07-29 07:30:00 +00002025 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2026 SourceOffset*8+64, getContext()))
2027 return IRType;
2028 }
2029 }
Chris Lattner49382de2010-07-28 22:44:07 +00002030
Chris Lattner2acc6e32011-07-18 04:24:23 +00002031 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattner49382de2010-07-28 22:44:07 +00002032 // If this is a struct, recurse into the field at the specified offset.
Micah Villmow25a6a842012-10-08 16:25:52 +00002033 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattner49382de2010-07-28 22:44:07 +00002034 if (IROffset < SL->getSizeInBytes()) {
2035 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2036 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002037
Chris Lattner0d2656d2010-07-29 17:40:35 +00002038 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2039 SourceTy, SourceOffset);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002040 }
Chris Lattner49382de2010-07-28 22:44:07 +00002041 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002042
Chris Lattner2acc6e32011-07-18 04:24:23 +00002043 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002044 llvm::Type *EltTy = ATy->getElementType();
Micah Villmow25a6a842012-10-08 16:25:52 +00002045 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner021c3a32010-07-29 07:43:55 +00002046 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner0d2656d2010-07-29 17:40:35 +00002047 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2048 SourceOffset);
Chris Lattner021c3a32010-07-29 07:43:55 +00002049 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002050
Chris Lattner49382de2010-07-28 22:44:07 +00002051 // Okay, we don't have any better idea of what to pass, so we pass this in an
2052 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002053 unsigned TySizeInBytes =
2054 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattner49382de2010-07-28 22:44:07 +00002055
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002056 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002057
Chris Lattner49382de2010-07-28 22:44:07 +00002058 // It is always safe to classify this as an integer type up to i64 that
2059 // isn't larger than the structure.
Chris Lattner9e45a3d2010-07-29 17:34:39 +00002060 return llvm::IntegerType::get(getVMContext(),
2061 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner9c254f02010-06-29 06:01:59 +00002062}
2063
Chris Lattner66e7b682010-09-01 00:50:20 +00002064
2065/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2066/// be used as elements of a two register pair to pass or return, return a
2067/// first class aggregate to represent them. For example, if the low part of
2068/// a by-value argument should be passed as i32* and the high part as float,
2069/// return {i32*, float}.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002070static llvm::Type *
Jay Foadef6de3d2011-07-11 09:56:20 +00002071GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmow25a6a842012-10-08 16:25:52 +00002072 const llvm::DataLayout &TD) {
Chris Lattner66e7b682010-09-01 00:50:20 +00002073 // In order to correctly satisfy the ABI, we need to the high part to start
2074 // at offset 8. If the high and low parts we inferred are both 4-byte types
2075 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2076 // the second element at offset 8. Check for this:
2077 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2078 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Micah Villmow25a6a842012-10-08 16:25:52 +00002079 unsigned HiStart = llvm::DataLayout::RoundUpAlignment(LoSize, HiAlign);
Chris Lattner66e7b682010-09-01 00:50:20 +00002080 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002081
Chris Lattner66e7b682010-09-01 00:50:20 +00002082 // To handle this, we have to increase the size of the low part so that the
2083 // second element will start at an 8 byte offset. We can't increase the size
2084 // of the second element because it might make us access off the end of the
2085 // struct.
2086 if (HiStart != 8) {
2087 // There are only two sorts of types the ABI generation code can produce for
2088 // the low part of a pair that aren't 8 bytes in size: float or i8/i16/i32.
2089 // Promote these to a larger type.
2090 if (Lo->isFloatTy())
2091 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2092 else {
2093 assert(Lo->isIntegerTy() && "Invalid/unknown lo type");
2094 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2095 }
2096 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002097
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002098 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, NULL);
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002099
2100
Chris Lattner66e7b682010-09-01 00:50:20 +00002101 // Verify that the second element is at an 8-byte offset.
2102 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2103 "Invalid x86-64 argument pair!");
2104 return Result;
2105}
2106
Chris Lattner519f68c2010-07-28 23:06:14 +00002107ABIArgInfo X86_64ABIInfo::
Chris Lattnera3c109b2010-07-29 02:16:43 +00002108classifyReturnType(QualType RetTy) const {
Chris Lattner519f68c2010-07-28 23:06:14 +00002109 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2110 // classification algorithm.
2111 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002112 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner519f68c2010-07-28 23:06:14 +00002113
2114 // Check some invariants.
2115 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002116 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2117
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002118 llvm::Type *ResType = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002119 switch (Lo) {
2120 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002121 if (Hi == NoClass)
2122 return ABIArgInfo::getIgnore();
2123 // If the low part is just padding, it takes no register, leave ResType
2124 // null.
2125 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2126 "Unknown missing lo part");
2127 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002128
2129 case SSEUp:
2130 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002131 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002132
2133 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2134 // hidden argument.
2135 case Memory:
2136 return getIndirectReturnResult(RetTy);
2137
2138 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2139 // available register of the sequence %rax, %rdx is used.
2140 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002141 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002142
Chris Lattnereb518b42010-07-29 21:42:50 +00002143 // If we have a sign or zero extended integer, make sure to return Extend
2144 // so that the parameter gets the right LLVM IR attributes.
2145 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2146 // Treat an enum type as its underlying type.
2147 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2148 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002149
Chris Lattnereb518b42010-07-29 21:42:50 +00002150 if (RetTy->isIntegralOrEnumerationType() &&
2151 RetTy->isPromotableIntegerType())
2152 return ABIArgInfo::getExtend();
2153 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002154 break;
2155
2156 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2157 // available SSE register of the sequence %xmm0, %xmm1 is used.
2158 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002159 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattner0b30c672010-07-28 23:12:33 +00002160 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002161
2162 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2163 // returned on the X87 stack in %st0 as 80-bit x87 number.
2164 case X87:
Chris Lattnerea044322010-07-29 02:01:43 +00002165 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattner0b30c672010-07-28 23:12:33 +00002166 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002167
2168 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2169 // part of the value is returned in %st0 and the imaginary part in
2170 // %st1.
2171 case ComplexX87:
2172 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner7650d952011-06-18 22:49:11 +00002173 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattnerea044322010-07-29 02:01:43 +00002174 llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner519f68c2010-07-28 23:06:14 +00002175 NULL);
2176 break;
2177 }
2178
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002179 llvm::Type *HighPart = 0;
Chris Lattner519f68c2010-07-28 23:06:14 +00002180 switch (Hi) {
2181 // Memory was handled previously and X87 should
2182 // never occur as a hi class.
2183 case Memory:
2184 case X87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002185 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner519f68c2010-07-28 23:06:14 +00002186
2187 case ComplexX87: // Previously handled.
Chris Lattner0b30c672010-07-28 23:12:33 +00002188 case NoClass:
2189 break;
Chris Lattner519f68c2010-07-28 23:06:14 +00002190
Chris Lattner3db4dde2010-09-01 00:20:33 +00002191 case Integer:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002192 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002193 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2194 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002195 break;
Chris Lattner3db4dde2010-09-01 00:20:33 +00002196 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002197 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002198 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2199 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner519f68c2010-07-28 23:06:14 +00002200 break;
2201
2202 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002203 // is passed in the next available eightbyte chunk if the last used
2204 // vector register.
Chris Lattner519f68c2010-07-28 23:06:14 +00002205 //
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002206 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner519f68c2010-07-28 23:06:14 +00002207 case SSEUp:
2208 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002209 ResType = GetByteVectorType(RetTy);
Chris Lattner519f68c2010-07-28 23:06:14 +00002210 break;
2211
2212 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2213 // returned together with the previous X87 value in %st0.
2214 case X87Up:
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002215 // If X87Up is preceded by X87, we don't need to do
Chris Lattner519f68c2010-07-28 23:06:14 +00002216 // anything. However, in some cases with unions it may not be
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002217 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner519f68c2010-07-28 23:06:14 +00002218 // extra bits in an SSE reg.
Chris Lattner603519d2010-07-29 17:49:08 +00002219 if (Lo != X87) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002220 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner3db4dde2010-09-01 00:20:33 +00002221 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2222 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner603519d2010-07-29 17:49:08 +00002223 }
Chris Lattner519f68c2010-07-28 23:06:14 +00002224 break;
2225 }
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002226
Chris Lattner3db4dde2010-09-01 00:20:33 +00002227 // If a high part was specified, merge it together with the low part. It is
Chris Lattner645406a2010-09-01 00:24:35 +00002228 // known to pass in the high eightbyte of the result. We do this by forming a
2229 // first class struct aggregate with the high and low part: {low, high}
Chris Lattner66e7b682010-09-01 00:50:20 +00002230 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002231 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner519f68c2010-07-28 23:06:14 +00002232
Chris Lattnereb518b42010-07-29 21:42:50 +00002233 return ABIArgInfo::getDirect(ResType);
Chris Lattner519f68c2010-07-28 23:06:14 +00002234}
2235
Daniel Dunbaredfac032012-03-10 01:03:58 +00002236ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman7a1b5862013-06-12 00:13:45 +00002237 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2238 bool isNamedArg)
Daniel Dunbaredfac032012-03-10 01:03:58 +00002239 const
2240{
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002241 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman7a1b5862013-06-12 00:13:45 +00002242 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002243
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002244 // Check some invariants.
2245 // FIXME: Enforce these by construction.
2246 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002247 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2248
2249 neededInt = 0;
2250 neededSSE = 0;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002251 llvm::Type *ResType = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002252 switch (Lo) {
2253 case NoClass:
Chris Lattner117e3f42010-07-30 04:02:24 +00002254 if (Hi == NoClass)
2255 return ABIArgInfo::getIgnore();
2256 // If the low part is just padding, it takes no register, leave ResType
2257 // null.
2258 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2259 "Unknown missing lo part");
2260 break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002261
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002262 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2263 // on the stack.
2264 case Memory:
2265
2266 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2267 // COMPLEX_X87, it is passed in memory.
2268 case X87:
2269 case ComplexX87:
Mark Lacey23630722013-10-06 01:33:34 +00002270 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedmanded137f2011-06-29 07:04:55 +00002271 ++neededInt;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002272 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002273
2274 case SSEUp:
2275 case X87Up:
David Blaikieb219cfc2011-09-23 05:06:16 +00002276 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002277
2278 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2279 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2280 // and %r9 is used.
2281 case Integer:
Chris Lattner9c254f02010-06-29 06:01:59 +00002282 ++neededInt;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002283
Chris Lattner49382de2010-07-28 22:44:07 +00002284 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002285 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattnereb518b42010-07-29 21:42:50 +00002286
2287 // If we have a sign or zero extended integer, make sure to return Extend
2288 // so that the parameter gets the right LLVM IR attributes.
2289 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2290 // Treat an enum type as its underlying type.
2291 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2292 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002293
Chris Lattnereb518b42010-07-29 21:42:50 +00002294 if (Ty->isIntegralOrEnumerationType() &&
2295 Ty->isPromotableIntegerType())
2296 return ABIArgInfo::getExtend();
2297 }
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002298
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002299 break;
2300
2301 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2302 // available SSE register is used, the registers are taken in the
2303 // order from %xmm0 to %xmm7.
Bill Wendlingbb465d72010-10-18 03:41:31 +00002304 case SSE: {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002305 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman14508ff2011-07-02 00:57:27 +00002306 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling99aaae82010-10-18 23:51:38 +00002307 ++neededSSE;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002308 break;
2309 }
Bill Wendlingbb465d72010-10-18 03:41:31 +00002310 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002311
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002312 llvm::Type *HighPart = 0;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002313 switch (Hi) {
2314 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002315 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002316 // which is passed in memory.
2317 case Memory:
2318 case X87:
2319 case ComplexX87:
David Blaikieb219cfc2011-09-23 05:06:16 +00002320 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002321
2322 case NoClass: break;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002323
Chris Lattner645406a2010-09-01 00:24:35 +00002324 case Integer:
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002325 ++neededInt;
Chris Lattner49382de2010-07-28 22:44:07 +00002326 // Pick an 8-byte type based on the preferred type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002327 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002328
Chris Lattner645406a2010-09-01 00:24:35 +00002329 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2330 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002331 break;
2332
2333 // X87Up generally doesn't occur here (long double is passed in
2334 // memory), except in situations involving unions.
2335 case X87Up:
Chris Lattner645406a2010-09-01 00:24:35 +00002336 case SSE:
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002337 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002338
Chris Lattner645406a2010-09-01 00:24:35 +00002339 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2340 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner117e3f42010-07-30 04:02:24 +00002341
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002342 ++neededSSE;
2343 break;
2344
2345 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2346 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002347 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002348 case SSEUp:
Chris Lattnerab5722e2010-07-28 23:47:21 +00002349 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes4943c152011-07-11 22:41:29 +00002350 ResType = GetByteVectorType(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002351 break;
2352 }
2353
Chris Lattner645406a2010-09-01 00:24:35 +00002354 // If a high part was specified, merge it together with the low part. It is
2355 // known to pass in the high eightbyte of the result. We do this by forming a
2356 // first class struct aggregate with the high and low part: {low, high}
2357 if (HighPart)
Micah Villmow25a6a842012-10-08 16:25:52 +00002358 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencer9cac4942010-10-19 06:39:39 +00002359
Chris Lattnereb518b42010-07-29 21:42:50 +00002360 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002361}
2362
Chris Lattneree5dcd02010-07-29 02:31:05 +00002363void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002364
Chris Lattnera3c109b2010-07-29 02:16:43 +00002365 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002366
2367 // Keep track of the number of assigned registers.
Bill Wendling99aaae82010-10-18 23:51:38 +00002368 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002369
2370 // If the return value is indirect, then the hidden argument is consuming one
2371 // integer register.
2372 if (FI.getReturnInfo().isIndirect())
2373 --freeIntRegs;
2374
Eli Friedman7a1b5862013-06-12 00:13:45 +00002375 bool isVariadic = FI.isVariadic();
2376 unsigned numRequiredArgs = 0;
2377 if (isVariadic)
2378 numRequiredArgs = FI.getRequiredArgs().getNumRequiredArgs();
2379
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002380 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
2381 // get assigned (in left-to-right order) for passing as follows...
2382 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2383 it != ie; ++it) {
Eli Friedman7a1b5862013-06-12 00:13:45 +00002384 bool isNamedArg = true;
2385 if (isVariadic)
Aaron Ballmaneba7d2f2013-06-12 15:03:45 +00002386 isNamedArg = (it - FI.arg_begin()) <
2387 static_cast<signed>(numRequiredArgs);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002388
Bill Wendling99aaae82010-10-18 23:51:38 +00002389 unsigned neededInt, neededSSE;
Daniel Dunbaredfac032012-03-10 01:03:58 +00002390 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Eli Friedman7a1b5862013-06-12 00:13:45 +00002391 neededSSE, isNamedArg);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002392
2393 // AMD64-ABI 3.2.3p3: If there are no registers available for any
2394 // eightbyte of an argument, the whole argument is passed on the
2395 // stack. If registers have already been assigned for some
2396 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling99aaae82010-10-18 23:51:38 +00002397 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002398 freeIntRegs -= neededInt;
2399 freeSSERegs -= neededSSE;
2400 } else {
Daniel Dunbaredfac032012-03-10 01:03:58 +00002401 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002402 }
2403 }
2404}
2405
2406static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
2407 QualType Ty,
2408 CodeGenFunction &CGF) {
2409 llvm::Value *overflow_arg_area_p =
2410 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
2411 llvm::Value *overflow_arg_area =
2412 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
2413
2414 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
2415 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedman8d2fe422011-11-18 02:44:19 +00002416 // It isn't stated explicitly in the standard, but in practice we use
2417 // alignment greater than 16 where necessary.
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002418 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
2419 if (Align > 8) {
Eli Friedman8d2fe422011-11-18 02:44:19 +00002420 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson0032b272009-08-13 21:57:51 +00002421 llvm::Value *Offset =
Eli Friedman8d2fe422011-11-18 02:44:19 +00002422 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002423 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
2424 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner77b89b82010-06-27 07:15:29 +00002425 CGF.Int64Ty);
Eli Friedman8d2fe422011-11-18 02:44:19 +00002426 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002427 overflow_arg_area =
2428 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
2429 overflow_arg_area->getType(),
2430 "overflow_arg_area.align");
2431 }
2432
2433 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002434 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002435 llvm::Value *Res =
2436 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002437 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002438
2439 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
2440 // l->overflow_arg_area + sizeof(type).
2441 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
2442 // an 8 byte boundary.
2443
2444 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson0032b272009-08-13 21:57:51 +00002445 llvm::Value *Offset =
Chris Lattner77b89b82010-06-27 07:15:29 +00002446 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002447 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
2448 "overflow_arg_area.next");
2449 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
2450
2451 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
2452 return Res;
2453}
2454
2455llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2456 CodeGenFunction &CGF) const {
2457 // Assume that va_list type is correct; should be pointer to LLVM type:
2458 // struct {
2459 // i32 gp_offset;
2460 // i32 fp_offset;
2461 // i8* overflow_arg_area;
2462 // i8* reg_save_area;
2463 // };
Bill Wendling99aaae82010-10-18 23:51:38 +00002464 unsigned neededInt, neededSSE;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002465
Chris Lattnera14db752010-03-11 18:19:55 +00002466 Ty = CGF.getContext().getCanonicalType(Ty);
Eli Friedman7a1b5862013-06-12 00:13:45 +00002467 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
2468 /*isNamedArg*/false);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002469
2470 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
2471 // in the registers. If not go to step 7.
2472 if (!neededInt && !neededSSE)
2473 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2474
2475 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
2476 // general purpose registers needed to pass type and num_fp to hold
2477 // the number of floating point registers needed.
2478
2479 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
2480 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
2481 // l->fp_offset > 304 - num_fp * 16 go to step 7.
2482 //
2483 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
2484 // register save space).
2485
2486 llvm::Value *InRegs = 0;
2487 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
2488 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
2489 if (neededInt) {
2490 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
2491 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattner1090a9b2010-06-28 21:43:59 +00002492 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
2493 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002494 }
2495
2496 if (neededSSE) {
2497 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
2498 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
2499 llvm::Value *FitsInFP =
Chris Lattner1090a9b2010-06-28 21:43:59 +00002500 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
2501 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002502 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
2503 }
2504
2505 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
2506 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
2507 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
2508 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
2509
2510 // Emit code to load the value if it was passed in registers.
2511
2512 CGF.EmitBlock(InRegBlock);
2513
2514 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
2515 // an offset of l->gp_offset and/or l->fp_offset. This may require
2516 // copying to a temporary location in case the parameter is passed
2517 // in different register classes or requires an alignment greater
2518 // than 8 for general purpose registers and 16 for XMM registers.
2519 //
2520 // FIXME: This really results in shameful code when we end up needing to
2521 // collect arguments from different places; often what should result in a
2522 // simple assembling of a structure from scattered addresses has many more
2523 // loads than necessary. Can we clean this up?
Chris Lattner2acc6e32011-07-18 04:24:23 +00002524 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002525 llvm::Value *RegAddr =
2526 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
2527 "reg_save_area");
2528 if (neededInt && neededSSE) {
2529 // FIXME: Cleanup.
Chris Lattner800588f2010-07-29 06:26:06 +00002530 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002531 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
Eli Friedmaneeb00622013-06-07 23:20:55 +00002532 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2533 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002534 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002535 llvm::Type *TyLo = ST->getElementType(0);
2536 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattnera8b7a7d2010-08-26 06:28:35 +00002537 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002538 "Unexpected ABI info for mixed regs");
Chris Lattner2acc6e32011-07-18 04:24:23 +00002539 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
2540 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002541 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2542 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002543 llvm::Value *RegLoAddr = TyLo->isFloatingPointTy() ? FPAddr : GPAddr;
2544 llvm::Value *RegHiAddr = TyLo->isFloatingPointTy() ? GPAddr : FPAddr;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002545 llvm::Value *V =
2546 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
2547 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2548 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
2549 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2550
Owen Andersona1cf15f2009-07-14 23:10:40 +00002551 RegAddr = CGF.Builder.CreateBitCast(Tmp,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002552 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002553 } else if (neededInt) {
2554 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
2555 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
Owen Anderson96e0fc72009-07-29 22:16:19 +00002556 llvm::PointerType::getUnqual(LTy));
Eli Friedmaneeb00622013-06-07 23:20:55 +00002557
2558 // Copy to a temporary if necessary to ensure the appropriate alignment.
2559 std::pair<CharUnits, CharUnits> SizeAlign =
2560 CGF.getContext().getTypeInfoInChars(Ty);
2561 uint64_t TySize = SizeAlign.first.getQuantity();
2562 unsigned TyAlign = SizeAlign.second.getQuantity();
2563 if (TyAlign > 8) {
Eli Friedmaneeb00622013-06-07 23:20:55 +00002564 llvm::Value *Tmp = CGF.CreateMemTemp(Ty);
2565 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, 8, false);
2566 RegAddr = Tmp;
2567 }
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002568 } else if (neededSSE == 1) {
2569 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
2570 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
2571 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002572 } else {
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002573 assert(neededSSE == 2 && "Invalid number of needed registers!");
2574 // SSE registers are spaced 16 bytes apart in the register save
2575 // area, we need to collect the two eightbytes together.
2576 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
Chris Lattner1090a9b2010-06-28 21:43:59 +00002577 llvm::Value *RegAddrHi = CGF.Builder.CreateConstGEP1_32(RegAddrLo, 16);
Chris Lattner8b418682012-02-07 00:39:47 +00002578 llvm::Type *DoubleTy = CGF.DoubleTy;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002579 llvm::Type *DblPtrTy =
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002580 llvm::PointerType::getUnqual(DoubleTy);
Eli Friedmaneeb00622013-06-07 23:20:55 +00002581 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, NULL);
2582 llvm::Value *V, *Tmp = CGF.CreateMemTemp(Ty);
2583 Tmp = CGF.Builder.CreateBitCast(Tmp, ST->getPointerTo());
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002584 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
2585 DblPtrTy));
2586 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
2587 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
2588 DblPtrTy));
2589 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
2590 RegAddr = CGF.Builder.CreateBitCast(Tmp,
2591 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002592 }
2593
2594 // AMD64-ABI 3.5.7p5: Step 5. Set:
2595 // l->gp_offset = l->gp_offset + num_gp * 8
2596 // l->fp_offset = l->fp_offset + num_fp * 16.
2597 if (neededInt) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002598 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002599 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
2600 gp_offset_p);
2601 }
2602 if (neededSSE) {
Chris Lattner77b89b82010-06-27 07:15:29 +00002603 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002604 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
2605 fp_offset_p);
2606 }
2607 CGF.EmitBranch(ContBlock);
2608
2609 // Emit code to load the value if it was passed in memory.
2610
2611 CGF.EmitBlock(InMemBlock);
2612 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
2613
2614 // Return the appropriate result.
2615
2616 CGF.EmitBlock(ContBlock);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002617 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(), 2,
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002618 "vaarg.addr");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002619 ResAddr->addIncoming(RegAddr, InRegBlock);
2620 ResAddr->addIncoming(MemAddr, InMemBlock);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00002621 return ResAddr;
2622}
2623
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002624ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002625
2626 if (Ty->isVoidType())
2627 return ABIArgInfo::getIgnore();
2628
2629 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2630 Ty = EnumTy->getDecl()->getIntegerType();
2631
2632 uint64_t Size = getContext().getTypeSize(Ty);
2633
2634 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002635 if (IsReturnType) {
Mark Lacey23630722013-10-06 01:33:34 +00002636 if (isRecordReturnIndirect(RT, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002637 return ABIArgInfo::getIndirect(0, false);
2638 } else {
Mark Lacey23630722013-10-06 01:33:34 +00002639 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002640 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
2641 }
2642
2643 if (RT->getDecl()->hasFlexibleArrayMember())
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002644 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2645
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002646 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
John McCall64aa4b32013-04-16 22:48:15 +00002647 if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
NAKAMURA Takumi6f174332011-02-22 03:56:57 +00002648 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2649 Size));
2650
2651 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
2652 // not 1, 2, 4, or 8 bytes, must be passed by reference."
2653 if (Size <= 64 &&
NAKAMURA Takumiff8be0e2011-01-19 00:11:33 +00002654 (Size & (Size - 1)) == 0)
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002655 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2656 Size));
2657
2658 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
2659 }
2660
2661 if (Ty->isPromotableIntegerType())
2662 return ABIArgInfo::getExtend();
2663
2664 return ABIArgInfo::getDirect();
2665}
2666
2667void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2668
2669 QualType RetTy = FI.getReturnType();
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002670 FI.getReturnInfo() = classify(RetTy, true);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002671
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002672 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2673 it != ie; ++it)
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002674 it->info = classify(it->type, false);
NAKAMURA Takumia7573222011-01-17 22:56:31 +00002675}
2676
Chris Lattnerf13721d2010-08-31 16:44:54 +00002677llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2678 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00002679 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002680
Chris Lattnerf13721d2010-08-31 16:44:54 +00002681 CGBuilderTy &Builder = CGF.Builder;
2682 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
2683 "ap");
2684 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2685 llvm::Type *PTy =
2686 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2687 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
2688
2689 uint64_t Offset =
2690 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 8);
2691 llvm::Value *NextAddr =
2692 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
2693 "ap.next");
2694 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2695
2696 return AddrTyped;
2697}
Chris Lattnerdce5ad02010-06-28 20:05:43 +00002698
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002699namespace {
2700
Derek Schuff263366f2012-10-16 22:30:41 +00002701class NaClX86_64ABIInfo : public ABIInfo {
2702 public:
2703 NaClX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2704 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, HasAVX) {}
2705 virtual void computeInfo(CGFunctionInfo &FI) const;
2706 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2707 CodeGenFunction &CGF) const;
2708 private:
2709 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
2710 X86_64ABIInfo NInfo; // Used for everything else.
2711};
2712
2713class NaClX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2714 public:
2715 NaClX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool HasAVX)
2716 : TargetCodeGenInfo(new NaClX86_64ABIInfo(CGT, HasAVX)) {}
2717};
2718
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00002719}
2720
Derek Schuff263366f2012-10-16 22:30:41 +00002721void NaClX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
2722 if (FI.getASTCallingConvention() == CC_PnaclCall)
2723 PInfo.computeInfo(FI);
2724 else
2725 NInfo.computeInfo(FI);
2726}
2727
2728llvm::Value *NaClX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
2729 CodeGenFunction &CGF) const {
2730 // Always use the native convention; calling pnacl-style varargs functions
2731 // is unuspported.
2732 return NInfo.EmitVAArg(VAListAddr, Ty, CGF);
2733}
2734
2735
John McCallec853ba2010-03-11 00:10:12 +00002736// PowerPC-32
2737
2738namespace {
2739class PPC32TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2740public:
Chris Lattnerea044322010-07-29 02:01:43 +00002741 PPC32TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002742
John McCallec853ba2010-03-11 00:10:12 +00002743 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2744 // This is recovered from gcc output.
2745 return 1; // r1 is the dedicated stack pointer
2746 }
2747
2748 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002749 llvm::Value *Address) const;
John McCallec853ba2010-03-11 00:10:12 +00002750};
2751
2752}
2753
2754bool
2755PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2756 llvm::Value *Address) const {
2757 // This is calculated from the LLVM and GCC tables and verified
2758 // against gcc output. AFAIK all ABIs use the same encoding.
2759
2760 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallec853ba2010-03-11 00:10:12 +00002761
Chris Lattner8b418682012-02-07 00:39:47 +00002762 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallec853ba2010-03-11 00:10:12 +00002763 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
2764 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
2765 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
2766
2767 // 0-31: r0-31, the 4-byte general-purpose registers
John McCallaeeb7012010-05-27 06:19:26 +00002768 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallec853ba2010-03-11 00:10:12 +00002769
2770 // 32-63: fp0-31, the 8-byte floating-point registers
John McCallaeeb7012010-05-27 06:19:26 +00002771 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallec853ba2010-03-11 00:10:12 +00002772
2773 // 64-76 are various 4-byte special-purpose registers:
2774 // 64: mq
2775 // 65: lr
2776 // 66: ctr
2777 // 67: ap
2778 // 68-75 cr0-7
2779 // 76: xer
John McCallaeeb7012010-05-27 06:19:26 +00002780 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallec853ba2010-03-11 00:10:12 +00002781
2782 // 77-108: v0-31, the 16-byte vector registers
John McCallaeeb7012010-05-27 06:19:26 +00002783 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallec853ba2010-03-11 00:10:12 +00002784
2785 // 109: vrsave
2786 // 110: vscr
2787 // 111: spe_acc
2788 // 112: spefscr
2789 // 113: sfp
John McCallaeeb7012010-05-27 06:19:26 +00002790 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallec853ba2010-03-11 00:10:12 +00002791
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00002792 return false;
John McCallec853ba2010-03-11 00:10:12 +00002793}
2794
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002795// PowerPC-64
2796
2797namespace {
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002798/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
2799class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
2800
2801public:
2802 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
2803
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002804 bool isPromotableTypeForABI(QualType Ty) const;
2805
2806 ABIArgInfo classifyReturnType(QualType RetTy) const;
2807 ABIArgInfo classifyArgumentType(QualType Ty) const;
2808
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002809 // TODO: We can add more logic to computeInfo to improve performance.
2810 // Example: For aggregate arguments that fit in a register, we could
2811 // use getDirectInReg (as is done below for structs containing a single
2812 // floating-point value) to avoid pushing them to memory on function
2813 // entry. This would require changing the logic in PPCISelLowering
2814 // when lowering the parameters in the caller and args in the callee.
2815 virtual void computeInfo(CGFunctionInfo &FI) const {
2816 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
2817 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
2818 it != ie; ++it) {
2819 // We rely on the default argument classification for the most part.
2820 // One exception: An aggregate containing a single floating-point
Bill Schmidtb1993102013-07-23 22:15:57 +00002821 // or vector item must be passed in a register if one is available.
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002822 const Type *T = isSingleElementStruct(it->type, getContext());
2823 if (T) {
2824 const BuiltinType *BT = T->getAs<BuiltinType>();
Bill Schmidtb1993102013-07-23 22:15:57 +00002825 if (T->isVectorType() || (BT && BT->isFloatingPoint())) {
Bill Schmidtb1f5fe02012-10-12 19:26:17 +00002826 QualType QT(T, 0);
2827 it->info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
2828 continue;
2829 }
2830 }
2831 it->info = classifyArgumentType(it->type);
2832 }
2833 }
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002834
2835 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr,
2836 QualType Ty,
2837 CodeGenFunction &CGF) const;
2838};
2839
2840class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
2841public:
2842 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT)
2843 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT)) {}
2844
2845 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2846 // This is recovered from gcc output.
2847 return 1; // r1 is the dedicated stack pointer
2848 }
2849
2850 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2851 llvm::Value *Address) const;
2852};
2853
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002854class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
2855public:
2856 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
2857
2858 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
2859 // This is recovered from gcc output.
2860 return 1; // r1 is the dedicated stack pointer
2861 }
2862
2863 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2864 llvm::Value *Address) const;
2865};
2866
2867}
2868
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002869// Return true if the ABI requires Ty to be passed sign- or zero-
2870// extended to 64 bits.
2871bool
2872PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
2873 // Treat an enum type as its underlying type.
2874 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2875 Ty = EnumTy->getDecl()->getIntegerType();
2876
2877 // Promotable integer types are required to be promoted by the ABI.
2878 if (Ty->isPromotableIntegerType())
2879 return true;
2880
2881 // In addition to the usual promotable integer types, we also need to
2882 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
2883 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
2884 switch (BT->getKind()) {
2885 case BuiltinType::Int:
2886 case BuiltinType::UInt:
2887 return true;
2888 default:
2889 break;
2890 }
2891
2892 return false;
2893}
2894
2895ABIArgInfo
2896PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Bill Schmidtc9715fc2012-11-27 02:46:43 +00002897 if (Ty->isAnyComplexType())
2898 return ABIArgInfo::getDirect();
2899
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002900 if (isAggregateTypeForABI(Ty)) {
Mark Lacey23630722013-10-06 01:33:34 +00002901 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00002902 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002903
2904 return ABIArgInfo::getIndirect(0);
2905 }
2906
2907 return (isPromotableTypeForABI(Ty) ?
2908 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2909}
2910
2911ABIArgInfo
2912PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
2913 if (RetTy->isVoidType())
2914 return ABIArgInfo::getIgnore();
2915
Bill Schmidt9e6111a2012-12-17 04:20:17 +00002916 if (RetTy->isAnyComplexType())
2917 return ABIArgInfo::getDirect();
2918
Ulrich Weigand71c0dcc2012-11-05 19:13:42 +00002919 if (isAggregateTypeForABI(RetTy))
2920 return ABIArgInfo::getIndirect(0);
2921
2922 return (isPromotableTypeForABI(RetTy) ?
2923 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2924}
2925
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002926// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
2927llvm::Value *PPC64_SVR4_ABIInfo::EmitVAArg(llvm::Value *VAListAddr,
2928 QualType Ty,
2929 CodeGenFunction &CGF) const {
2930 llvm::Type *BP = CGF.Int8PtrTy;
2931 llvm::Type *BPP = CGF.Int8PtrPtrTy;
2932
2933 CGBuilderTy &Builder = CGF.Builder;
2934 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
2935 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
2936
Bill Schmidt19f8e852013-01-14 17:45:36 +00002937 // Update the va_list pointer. The pointer should be bumped by the
2938 // size of the object. We can trust getTypeSize() except for a complex
2939 // type whose base type is smaller than a doubleword. For these, the
2940 // size of the object is 16 bytes; see below for further explanation.
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002941 unsigned SizeInBytes = CGF.getContext().getTypeSize(Ty) / 8;
Bill Schmidt19f8e852013-01-14 17:45:36 +00002942 QualType BaseTy;
2943 unsigned CplxBaseSize = 0;
2944
2945 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
2946 BaseTy = CTy->getElementType();
2947 CplxBaseSize = CGF.getContext().getTypeSize(BaseTy) / 8;
2948 if (CplxBaseSize < 8)
2949 SizeInBytes = 16;
2950 }
2951
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002952 unsigned Offset = llvm::RoundUpToAlignment(SizeInBytes, 8);
2953 llvm::Value *NextAddr =
2954 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int64Ty, Offset),
2955 "ap.next");
2956 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
2957
Bill Schmidt19f8e852013-01-14 17:45:36 +00002958 // If we have a complex type and the base type is smaller than 8 bytes,
2959 // the ABI calls for the real and imaginary parts to be right-adjusted
2960 // in separate doublewords. However, Clang expects us to produce a
2961 // pointer to a structure with the two parts packed tightly. So generate
2962 // loads of the real and imaginary parts relative to the va_list pointer,
2963 // and store them to a temporary structure.
2964 if (CplxBaseSize && CplxBaseSize < 8) {
2965 llvm::Value *RealAddr = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2966 llvm::Value *ImagAddr = RealAddr;
2967 RealAddr = Builder.CreateAdd(RealAddr, Builder.getInt64(8 - CplxBaseSize));
2968 ImagAddr = Builder.CreateAdd(ImagAddr, Builder.getInt64(16 - CplxBaseSize));
2969 llvm::Type *PBaseTy = llvm::PointerType::getUnqual(CGF.ConvertType(BaseTy));
2970 RealAddr = Builder.CreateIntToPtr(RealAddr, PBaseTy);
2971 ImagAddr = Builder.CreateIntToPtr(ImagAddr, PBaseTy);
2972 llvm::Value *Real = Builder.CreateLoad(RealAddr, false, ".vareal");
2973 llvm::Value *Imag = Builder.CreateLoad(ImagAddr, false, ".vaimag");
2974 llvm::Value *Ptr = CGF.CreateTempAlloca(CGT.ConvertTypeForMem(Ty),
2975 "vacplx");
2976 llvm::Value *RealPtr = Builder.CreateStructGEP(Ptr, 0, ".real");
2977 llvm::Value *ImagPtr = Builder.CreateStructGEP(Ptr, 1, ".imag");
2978 Builder.CreateStore(Real, RealPtr, false);
2979 Builder.CreateStore(Imag, ImagPtr, false);
2980 return Ptr;
2981 }
2982
Bill Schmidt2fc107f2012-10-03 19:18:57 +00002983 // If the argument is smaller than 8 bytes, it is right-adjusted in
2984 // its doubleword slot. Adjust the pointer to pick it up from the
2985 // correct offset.
2986 if (SizeInBytes < 8) {
2987 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int64Ty);
2988 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt64(8 - SizeInBytes));
2989 Addr = Builder.CreateIntToPtr(AddrAsInt, BP);
2990 }
2991
2992 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
2993 return Builder.CreateBitCast(Addr, PTy);
2994}
2995
2996static bool
2997PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2998 llvm::Value *Address) {
Roman Divacky0fbc4b92012-05-09 18:22:46 +00002999 // This is calculated from the LLVM and GCC tables and verified
3000 // against gcc output. AFAIK all ABIs use the same encoding.
3001
3002 CodeGen::CGBuilderTy &Builder = CGF.Builder;
3003
3004 llvm::IntegerType *i8 = CGF.Int8Ty;
3005 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3006 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3007 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3008
3009 // 0-31: r0-31, the 8-byte general-purpose registers
3010 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
3011
3012 // 32-63: fp0-31, the 8-byte floating-point registers
3013 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
3014
3015 // 64-76 are various 4-byte special-purpose registers:
3016 // 64: mq
3017 // 65: lr
3018 // 66: ctr
3019 // 67: ap
3020 // 68-75 cr0-7
3021 // 76: xer
3022 AssignToArrayRange(Builder, Address, Four8, 64, 76);
3023
3024 // 77-108: v0-31, the 16-byte vector registers
3025 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
3026
3027 // 109: vrsave
3028 // 110: vscr
3029 // 111: spe_acc
3030 // 112: spefscr
3031 // 113: sfp
3032 AssignToArrayRange(Builder, Address, Four8, 109, 113);
3033
3034 return false;
3035}
John McCallec853ba2010-03-11 00:10:12 +00003036
Bill Schmidt2fc107f2012-10-03 19:18:57 +00003037bool
3038PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
3039 CodeGen::CodeGenFunction &CGF,
3040 llvm::Value *Address) const {
3041
3042 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3043}
3044
3045bool
3046PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3047 llvm::Value *Address) const {
3048
3049 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
3050}
3051
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003052//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003053// ARM ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003054//===----------------------------------------------------------------------===//
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003055
3056namespace {
3057
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003058class ARMABIInfo : public ABIInfo {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003059public:
3060 enum ABIKind {
3061 APCS = 0,
3062 AAPCS = 1,
3063 AAPCS_VFP
3064 };
3065
3066private:
3067 ABIKind Kind;
3068
3069public:
John McCallbd7370a2013-02-28 19:01:20 +00003070 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
3071 setRuntimeCC();
3072 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003073
John McCall49e34be2011-08-30 01:42:09 +00003074 bool isEABI() const {
John McCall64aa4b32013-04-16 22:48:15 +00003075 StringRef Env = getTarget().getTriple().getEnvironmentName();
Logan Chien94a71422012-09-02 09:30:11 +00003076 return (Env == "gnueabi" || Env == "eabi" ||
3077 Env == "android" || Env == "androideabi");
John McCall49e34be2011-08-30 01:42:09 +00003078 }
3079
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003080 ABIKind getABIKind() const { return Kind; }
3081
Tim Northover64eac852013-10-01 14:34:25 +00003082private:
Chris Lattnera3c109b2010-07-29 02:16:43 +00003083 ABIArgInfo classifyReturnType(QualType RetTy) const;
Manman Ren710c5172012-10-31 19:02:26 +00003084 ABIArgInfo classifyArgumentType(QualType RetTy, int *VFPRegs,
3085 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00003086 bool &IsHA) const;
Manman Ren97f81572012-10-16 19:18:39 +00003087 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003088
Chris Lattneree5dcd02010-07-29 02:31:05 +00003089 virtual void computeInfo(CGFunctionInfo &FI) const;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003090
3091 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3092 CodeGenFunction &CGF) const;
John McCallbd7370a2013-02-28 19:01:20 +00003093
3094 llvm::CallingConv::ID getLLVMDefaultCC() const;
3095 llvm::CallingConv::ID getABIDefaultCC() const;
3096 void setRuntimeCC();
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003097};
3098
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003099class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
3100public:
Chris Lattnerea044322010-07-29 02:01:43 +00003101 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
3102 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCall6374c332010-03-06 00:35:14 +00003103
John McCall49e34be2011-08-30 01:42:09 +00003104 const ARMABIInfo &getABIInfo() const {
3105 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
3106 }
3107
John McCall6374c332010-03-06 00:35:14 +00003108 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3109 return 13;
3110 }
Roman Divacky09345d12011-05-18 19:36:54 +00003111
Chris Lattner5f9e2722011-07-23 10:55:15 +00003112 StringRef getARCRetainAutoreleasedReturnValueMarker() const {
John McCallf85e1932011-06-15 23:02:42 +00003113 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
3114 }
3115
Roman Divacky09345d12011-05-18 19:36:54 +00003116 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3117 llvm::Value *Address) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003118 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divacky09345d12011-05-18 19:36:54 +00003119
3120 // 0-15 are the 16 integer registers.
Chris Lattner8b418682012-02-07 00:39:47 +00003121 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divacky09345d12011-05-18 19:36:54 +00003122 return false;
3123 }
John McCall49e34be2011-08-30 01:42:09 +00003124
3125 unsigned getSizeOfUnwindException() const {
3126 if (getABIInfo().isEABI()) return 88;
3127 return TargetCodeGenInfo::getSizeOfUnwindException();
3128 }
Tim Northover64eac852013-10-01 14:34:25 +00003129
3130 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
3131 CodeGen::CodeGenModule &CGM) const {
3132 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
3133 if (!FD)
3134 return;
3135
3136 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
3137 if (!Attr)
3138 return;
3139
3140 const char *Kind;
3141 switch (Attr->getInterrupt()) {
3142 case ARMInterruptAttr::Generic: Kind = ""; break;
3143 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
3144 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
3145 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
3146 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
3147 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
3148 }
3149
3150 llvm::Function *Fn = cast<llvm::Function>(GV);
3151
3152 Fn->addFnAttr("interrupt", Kind);
3153
3154 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
3155 return;
3156
3157 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
3158 // however this is not necessarily true on taking any interrupt. Instruct
3159 // the backend to perform a realignment as part of the function prologue.
3160 llvm::AttrBuilder B;
3161 B.addStackAlignmentAttr(8);
3162 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
3163 llvm::AttributeSet::get(CGM.getLLVMContext(),
3164 llvm::AttributeSet::FunctionIndex,
3165 B));
3166 }
3167
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00003168};
3169
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00003170}
3171
Chris Lattneree5dcd02010-07-29 02:31:05 +00003172void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Manman Renb3fa55f2012-10-30 23:21:41 +00003173 // To correctly handle Homogeneous Aggregate, we need to keep track of the
Manman Ren710c5172012-10-31 19:02:26 +00003174 // VFP registers allocated so far.
Manman Renb3fa55f2012-10-30 23:21:41 +00003175 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3176 // VFP registers of the appropriate type unallocated then the argument is
3177 // allocated to the lowest-numbered sequence of such registers.
3178 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3179 // unallocated are marked as unavailable.
3180 unsigned AllocatedVFP = 0;
Manman Ren710c5172012-10-31 19:02:26 +00003181 int VFPRegs[16] = { 0 };
Chris Lattnera3c109b2010-07-29 02:16:43 +00003182 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003183 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Manman Renb3fa55f2012-10-30 23:21:41 +00003184 it != ie; ++it) {
3185 unsigned PreAllocation = AllocatedVFP;
3186 bool IsHA = false;
3187 // 6.1.2.3 There is one VFP co-processor register class using registers
3188 // s0-s15 (d0-d7) for passing arguments.
3189 const unsigned NumVFPs = 16;
Manman Ren710c5172012-10-31 19:02:26 +00003190 it->info = classifyArgumentType(it->type, VFPRegs, AllocatedVFP, IsHA);
Manman Renb3fa55f2012-10-30 23:21:41 +00003191 // If we do not have enough VFP registers for the HA, any VFP registers
3192 // that are unallocated are marked as unavailable. To achieve this, we add
3193 // padding of (NumVFPs - PreAllocation) floats.
3194 if (IsHA && AllocatedVFP > NumVFPs && PreAllocation < NumVFPs) {
3195 llvm::Type *PaddingTy = llvm::ArrayType::get(
3196 llvm::Type::getFloatTy(getVMContext()), NumVFPs - PreAllocation);
3197 it->info = ABIArgInfo::getExpandWithPadding(false, PaddingTy);
3198 }
3199 }
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003200
Anton Korobeynikov414d8962011-04-14 20:06:49 +00003201 // Always honor user-specified calling convention.
3202 if (FI.getCallingConvention() != llvm::CallingConv::C)
3203 return;
3204
John McCallbd7370a2013-02-28 19:01:20 +00003205 llvm::CallingConv::ID cc = getRuntimeCC();
3206 if (cc != llvm::CallingConv::C)
3207 FI.setEffectiveCallingConvention(cc);
3208}
Rafael Espindola25117ab2010-06-16 16:13:39 +00003209
John McCallbd7370a2013-02-28 19:01:20 +00003210/// Return the default calling convention that LLVM will use.
3211llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
3212 // The default calling convention that LLVM will infer.
John McCall64aa4b32013-04-16 22:48:15 +00003213 if (getTarget().getTriple().getEnvironmentName()=="gnueabihf")
John McCallbd7370a2013-02-28 19:01:20 +00003214 return llvm::CallingConv::ARM_AAPCS_VFP;
3215 else if (isEABI())
3216 return llvm::CallingConv::ARM_AAPCS;
3217 else
3218 return llvm::CallingConv::ARM_APCS;
3219}
3220
3221/// Return the calling convention that our ABI would like us to use
3222/// as the C calling convention.
3223llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003224 switch (getABIKind()) {
John McCallbd7370a2013-02-28 19:01:20 +00003225 case APCS: return llvm::CallingConv::ARM_APCS;
3226 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
3227 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar5e7bace2009-09-12 01:00:39 +00003228 }
John McCallbd7370a2013-02-28 19:01:20 +00003229 llvm_unreachable("bad ABI kind");
3230}
3231
3232void ARMABIInfo::setRuntimeCC() {
3233 assert(getRuntimeCC() == llvm::CallingConv::C);
3234
3235 // Don't muddy up the IR with a ton of explicit annotations if
3236 // they'd just match what LLVM will infer from the triple.
3237 llvm::CallingConv::ID abiCC = getABIDefaultCC();
3238 if (abiCC != getLLVMDefaultCC())
3239 RuntimeCC = abiCC;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003240}
3241
Bob Wilson194f06a2011-08-03 05:58:22 +00003242/// isHomogeneousAggregate - Return true if a type is an AAPCS-VFP homogeneous
3243/// aggregate. If HAMembers is non-null, the number of base elements
3244/// contained in the type is returned through it; this is used for the
3245/// recursive calls that check aggregate component types.
3246static bool isHomogeneousAggregate(QualType Ty, const Type *&Base,
3247 ASTContext &Context,
3248 uint64_t *HAMembers = 0) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003249 uint64_t Members = 0;
Bob Wilson194f06a2011-08-03 05:58:22 +00003250 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3251 if (!isHomogeneousAggregate(AT->getElementType(), Base, Context, &Members))
3252 return false;
3253 Members *= AT->getSize().getZExtValue();
3254 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3255 const RecordDecl *RD = RT->getDecl();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003256 if (RD->hasFlexibleArrayMember())
Bob Wilson194f06a2011-08-03 05:58:22 +00003257 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003258
Bob Wilson194f06a2011-08-03 05:58:22 +00003259 Members = 0;
3260 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3261 i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003262 const FieldDecl *FD = *i;
Bob Wilson194f06a2011-08-03 05:58:22 +00003263 uint64_t FldMembers;
3264 if (!isHomogeneousAggregate(FD->getType(), Base, Context, &FldMembers))
3265 return false;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003266
3267 Members = (RD->isUnion() ?
3268 std::max(Members, FldMembers) : Members + FldMembers);
Bob Wilson194f06a2011-08-03 05:58:22 +00003269 }
3270 } else {
3271 Members = 1;
3272 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3273 Members = 2;
3274 Ty = CT->getElementType();
3275 }
3276
3277 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
3278 // double, or 64-bit or 128-bit vectors.
3279 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3280 if (BT->getKind() != BuiltinType::Float &&
Tim Northoveradfa45f2012-07-20 22:29:29 +00003281 BT->getKind() != BuiltinType::Double &&
3282 BT->getKind() != BuiltinType::LongDouble)
Bob Wilson194f06a2011-08-03 05:58:22 +00003283 return false;
3284 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3285 unsigned VecSize = Context.getTypeSize(VT);
3286 if (VecSize != 64 && VecSize != 128)
3287 return false;
3288 } else {
3289 return false;
3290 }
3291
3292 // The base type must be the same for all members. Vector types of the
3293 // same total size are treated as being equivalent here.
3294 const Type *TyPtr = Ty.getTypePtr();
3295 if (!Base)
3296 Base = TyPtr;
3297 if (Base != TyPtr &&
3298 (!Base->isVectorType() || !TyPtr->isVectorType() ||
3299 Context.getTypeSize(Base) != Context.getTypeSize(TyPtr)))
3300 return false;
3301 }
3302
3303 // Homogeneous Aggregates can have at most 4 members of the base type.
3304 if (HAMembers)
3305 *HAMembers = Members;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003306
3307 return (Members > 0 && Members <= 4);
Bob Wilson194f06a2011-08-03 05:58:22 +00003308}
3309
Manman Ren710c5172012-10-31 19:02:26 +00003310/// markAllocatedVFPs - update VFPRegs according to the alignment and
3311/// number of VFP registers (unit is S register) requested.
3312static void markAllocatedVFPs(int *VFPRegs, unsigned &AllocatedVFP,
3313 unsigned Alignment,
3314 unsigned NumRequired) {
3315 // Early Exit.
3316 if (AllocatedVFP >= 16)
3317 return;
3318 // C.1.vfp If the argument is a VFP CPRC and there are sufficient consecutive
3319 // VFP registers of the appropriate type unallocated then the argument is
3320 // allocated to the lowest-numbered sequence of such registers.
3321 for (unsigned I = 0; I < 16; I += Alignment) {
3322 bool FoundSlot = true;
3323 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3324 if (J >= 16 || VFPRegs[J]) {
3325 FoundSlot = false;
3326 break;
3327 }
3328 if (FoundSlot) {
3329 for (unsigned J = I, JEnd = I + NumRequired; J < JEnd; J++)
3330 VFPRegs[J] = 1;
3331 AllocatedVFP += NumRequired;
3332 return;
3333 }
3334 }
3335 // C.2.vfp If the argument is a VFP CPRC then any VFP registers that are
3336 // unallocated are marked as unavailable.
3337 for (unsigned I = 0; I < 16; I++)
3338 VFPRegs[I] = 1;
3339 AllocatedVFP = 17; // We do not have enough VFP registers.
3340}
3341
3342ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
3343 unsigned &AllocatedVFP,
Manman Renb3fa55f2012-10-30 23:21:41 +00003344 bool &IsHA) const {
3345 // We update number of allocated VFPs according to
3346 // 6.1.2.1 The following argument types are VFP CPRCs:
3347 // A single-precision floating-point type (including promoted
3348 // half-precision types); A double-precision floating-point type;
3349 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
3350 // with a Base Type of a single- or double-precision floating-point type,
3351 // 64-bit containerized vectors or 128-bit containerized vectors with one
3352 // to four Elements.
3353
Manman Ren97f81572012-10-16 19:18:39 +00003354 // Handle illegal vector types here.
3355 if (isIllegalVectorType(Ty)) {
3356 uint64_t Size = getContext().getTypeSize(Ty);
3357 if (Size <= 32) {
3358 llvm::Type *ResType =
3359 llvm::Type::getInt32Ty(getVMContext());
3360 return ABIArgInfo::getDirect(ResType);
3361 }
3362 if (Size == 64) {
3363 llvm::Type *ResType = llvm::VectorType::get(
3364 llvm::Type::getInt32Ty(getVMContext()), 2);
Manman Ren710c5172012-10-31 19:02:26 +00003365 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Ren97f81572012-10-16 19:18:39 +00003366 return ABIArgInfo::getDirect(ResType);
3367 }
3368 if (Size == 128) {
3369 llvm::Type *ResType = llvm::VectorType::get(
3370 llvm::Type::getInt32Ty(getVMContext()), 4);
Manman Ren710c5172012-10-31 19:02:26 +00003371 markAllocatedVFPs(VFPRegs, AllocatedVFP, 4, 4);
Manman Ren97f81572012-10-16 19:18:39 +00003372 return ABIArgInfo::getDirect(ResType);
3373 }
3374 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3375 }
Manman Ren710c5172012-10-31 19:02:26 +00003376 // Update VFPRegs for legal vector types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003377 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3378 uint64_t Size = getContext().getTypeSize(VT);
3379 // Size of a legal vector should be power of 2 and above 64.
Manman Ren710c5172012-10-31 19:02:26 +00003380 markAllocatedVFPs(VFPRegs, AllocatedVFP, Size >= 128 ? 4 : 2, Size / 32);
Manman Renb3fa55f2012-10-30 23:21:41 +00003381 }
Manman Ren710c5172012-10-31 19:02:26 +00003382 // Update VFPRegs for floating point types.
Manman Renb3fa55f2012-10-30 23:21:41 +00003383 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3384 if (BT->getKind() == BuiltinType::Half ||
3385 BT->getKind() == BuiltinType::Float)
Manman Ren710c5172012-10-31 19:02:26 +00003386 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, 1);
Manman Renb3fa55f2012-10-30 23:21:41 +00003387 if (BT->getKind() == BuiltinType::Double ||
Manman Ren710c5172012-10-31 19:02:26 +00003388 BT->getKind() == BuiltinType::LongDouble)
3389 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003390 }
Manman Ren97f81572012-10-16 19:18:39 +00003391
John McCalld608cdb2010-08-22 10:59:02 +00003392 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003393 // Treat an enum type as its underlying type.
3394 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3395 Ty = EnumTy->getDecl()->getIntegerType();
3396
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003397 return (Ty->isPromotableIntegerType() ?
3398 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003399 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003400
Mark Lacey23630722013-10-06 01:33:34 +00003401 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Tim Northoverf5c3a252013-06-21 22:49:34 +00003402 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
3403
Daniel Dunbar42025572009-09-14 21:54:03 +00003404 // Ignore empty records.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003405 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar42025572009-09-14 21:54:03 +00003406 return ABIArgInfo::getIgnore();
3407
Bob Wilson194f06a2011-08-03 05:58:22 +00003408 if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
Manman Renb3fa55f2012-10-30 23:21:41 +00003409 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
3410 // into VFP registers.
Bob Wilson194f06a2011-08-03 05:58:22 +00003411 const Type *Base = 0;
Manman Renb3fa55f2012-10-30 23:21:41 +00003412 uint64_t Members = 0;
3413 if (isHomogeneousAggregate(Ty, Base, getContext(), &Members)) {
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003414 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Renb3fa55f2012-10-30 23:21:41 +00003415 // Base can be a floating-point or a vector.
3416 if (Base->isVectorType()) {
3417 // ElementSize is in number of floats.
3418 unsigned ElementSize = getContext().getTypeSize(Base) == 64 ? 2 : 4;
Manman Rencb489dd2012-11-06 19:05:29 +00003419 markAllocatedVFPs(VFPRegs, AllocatedVFP, ElementSize,
3420 Members * ElementSize);
Manman Renb3fa55f2012-10-30 23:21:41 +00003421 } else if (Base->isSpecificBuiltinType(BuiltinType::Float))
Manman Ren710c5172012-10-31 19:02:26 +00003422 markAllocatedVFPs(VFPRegs, AllocatedVFP, 1, Members);
Manman Renb3fa55f2012-10-30 23:21:41 +00003423 else {
3424 assert(Base->isSpecificBuiltinType(BuiltinType::Double) ||
3425 Base->isSpecificBuiltinType(BuiltinType::LongDouble));
Manman Ren710c5172012-10-31 19:02:26 +00003426 markAllocatedVFPs(VFPRegs, AllocatedVFP, 2, Members * 2);
Manman Renb3fa55f2012-10-30 23:21:41 +00003427 }
3428 IsHA = true;
Bob Wilson194f06a2011-08-03 05:58:22 +00003429 return ABIArgInfo::getExpand();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003430 }
Bob Wilson194f06a2011-08-03 05:58:22 +00003431 }
3432
Manman Ren634b3d22012-08-13 21:23:55 +00003433 // Support byval for ARM.
Manman Rencb489dd2012-11-06 19:05:29 +00003434 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
3435 // most 8-byte. We realign the indirect argument if type alignment is bigger
3436 // than ABI alignment.
Manman Renfd1ba912012-11-05 22:42:46 +00003437 uint64_t ABIAlign = 4;
3438 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
3439 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3440 getABIKind() == ARMABIInfo::AAPCS)
3441 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Manman Ren885ad692012-11-06 04:58:01 +00003442 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
3443 return ABIArgInfo::getIndirect(0, /*ByVal=*/true,
Manman Rencb489dd2012-11-06 19:05:29 +00003444 /*Realign=*/TyAlign > ABIAlign);
Eli Friedman79f30982012-08-09 00:31:40 +00003445 }
3446
Daniel Dunbar8aa87c72010-09-23 01:54:28 +00003447 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003448 llvm::Type* ElemTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003449 unsigned SizeRegs;
Eli Friedman79f30982012-08-09 00:31:40 +00003450 // FIXME: Try to match the types of the arguments more accurately where
3451 // we can.
3452 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson53fc1a62011-08-01 23:39:04 +00003453 ElemTy = llvm::Type::getInt32Ty(getVMContext());
3454 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren78eb76e2012-06-25 22:04:00 +00003455 } else {
Manman Ren78eb76e2012-06-25 22:04:00 +00003456 ElemTy = llvm::Type::getInt64Ty(getVMContext());
3457 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastings67d097e2011-04-27 17:24:02 +00003458 }
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003459
Chris Lattner9cbe4f02011-07-09 17:41:47 +00003460 llvm::Type *STy =
Chris Lattner7650d952011-06-18 22:49:11 +00003461 llvm::StructType::get(llvm::ArrayType::get(ElemTy, SizeRegs), NULL);
Stuart Hastingsb7f62d02011-04-28 18:16:06 +00003462 return ABIArgInfo::getDirect(STy);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003463}
3464
Chris Lattnera3c109b2010-07-29 02:16:43 +00003465static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar98303b92009-09-13 08:03:58 +00003466 llvm::LLVMContext &VMContext) {
3467 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
3468 // is called integer-like if its size is less than or equal to one word, and
3469 // the offset of each of its addressable sub-fields is zero.
3470
3471 uint64_t Size = Context.getTypeSize(Ty);
3472
3473 // Check that the type fits in a word.
3474 if (Size > 32)
3475 return false;
3476
3477 // FIXME: Handle vector types!
3478 if (Ty->isVectorType())
3479 return false;
3480
Daniel Dunbarb0d58192009-09-14 02:20:34 +00003481 // Float types are never treated as "integer like".
3482 if (Ty->isRealFloatingType())
3483 return false;
3484
Daniel Dunbar98303b92009-09-13 08:03:58 +00003485 // If this is a builtin or pointer type then it is ok.
John McCall183700f2009-09-21 23:43:11 +00003486 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar98303b92009-09-13 08:03:58 +00003487 return true;
3488
Daniel Dunbar45815812010-02-01 23:31:26 +00003489 // Small complex integer types are "integer like".
3490 if (const ComplexType *CT = Ty->getAs<ComplexType>())
3491 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003492
3493 // Single element and zero sized arrays should be allowed, by the definition
3494 // above, but they are not.
3495
3496 // Otherwise, it must be a record type.
3497 const RecordType *RT = Ty->getAs<RecordType>();
3498 if (!RT) return false;
3499
3500 // Ignore records with flexible arrays.
3501 const RecordDecl *RD = RT->getDecl();
3502 if (RD->hasFlexibleArrayMember())
3503 return false;
3504
3505 // Check that all sub-fields are at offset 0, and are themselves "integer
3506 // like".
3507 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3508
3509 bool HadField = false;
3510 unsigned idx = 0;
3511 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3512 i != e; ++i, ++idx) {
David Blaikie581deb32012-06-06 20:45:41 +00003513 const FieldDecl *FD = *i;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003514
Daniel Dunbar679855a2010-01-29 03:22:29 +00003515 // Bit-fields are not addressable, we only need to verify they are "integer
3516 // like". We still have to disallow a subsequent non-bitfield, for example:
3517 // struct { int : 0; int x }
3518 // is non-integer like according to gcc.
3519 if (FD->isBitField()) {
3520 if (!RD->isUnion())
3521 HadField = true;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003522
Daniel Dunbar679855a2010-01-29 03:22:29 +00003523 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3524 return false;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003525
Daniel Dunbar679855a2010-01-29 03:22:29 +00003526 continue;
Daniel Dunbar98303b92009-09-13 08:03:58 +00003527 }
3528
Daniel Dunbar679855a2010-01-29 03:22:29 +00003529 // Check if this field is at offset 0.
3530 if (Layout.getFieldOffset(idx) != 0)
3531 return false;
3532
Daniel Dunbar98303b92009-09-13 08:03:58 +00003533 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
3534 return false;
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00003535
Daniel Dunbar679855a2010-01-29 03:22:29 +00003536 // Only allow at most one field in a structure. This doesn't match the
3537 // wording above, but follows gcc in situations with a field following an
3538 // empty structure.
Daniel Dunbar98303b92009-09-13 08:03:58 +00003539 if (!RD->isUnion()) {
3540 if (HadField)
3541 return false;
3542
3543 HadField = true;
3544 }
3545 }
3546
3547 return true;
3548}
3549
Chris Lattnera3c109b2010-07-29 02:16:43 +00003550ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003551 if (RetTy->isVoidType())
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003552 return ABIArgInfo::getIgnore();
Daniel Dunbar98303b92009-09-13 08:03:58 +00003553
Daniel Dunbarf554b1c2010-09-23 01:54:32 +00003554 // Large vector types should be returned via memory.
3555 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
3556 return ABIArgInfo::getIndirect(0);
3557
John McCalld608cdb2010-08-22 10:59:02 +00003558 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003559 // Treat an enum type as its underlying type.
3560 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3561 RetTy = EnumTy->getDecl()->getIntegerType();
3562
Anton Korobeynikovcc6fa882009-06-06 09:36:29 +00003563 return (RetTy->isPromotableIntegerType() ?
3564 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00003565 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003566
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003567 // Structures with either a non-trivial destructor or a non-trivial
3568 // copy constructor are always indirect.
Mark Lacey23630722013-10-06 01:33:34 +00003569 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Rafael Espindola0eb1d972010-06-08 02:42:08 +00003570 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3571
Daniel Dunbar98303b92009-09-13 08:03:58 +00003572 // Are we following APCS?
3573 if (getABIKind() == APCS) {
Chris Lattnera3c109b2010-07-29 02:16:43 +00003574 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar98303b92009-09-13 08:03:58 +00003575 return ABIArgInfo::getIgnore();
3576
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003577 // Complex types are all returned as packed integers.
3578 //
3579 // FIXME: Consider using 2 x vector types if the back end handles them
3580 // correctly.
3581 if (RetTy->isAnyComplexType())
Chris Lattner800588f2010-07-29 06:26:06 +00003582 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattnera3c109b2010-07-29 02:16:43 +00003583 getContext().getTypeSize(RetTy)));
Daniel Dunbar4cc753f2010-02-01 23:31:19 +00003584
Daniel Dunbar98303b92009-09-13 08:03:58 +00003585 // Integer like structures are returned in r0.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003586 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar98303b92009-09-13 08:03:58 +00003587 // Return in the smallest viable integer type.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003588 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar98303b92009-09-13 08:03:58 +00003589 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003590 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003591 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003592 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3593 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar98303b92009-09-13 08:03:58 +00003594 }
3595
3596 // Otherwise return in memory.
3597 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003598 }
Daniel Dunbar98303b92009-09-13 08:03:58 +00003599
3600 // Otherwise this is an AAPCS variant.
3601
Chris Lattnera3c109b2010-07-29 02:16:43 +00003602 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar16a08082009-09-14 00:56:55 +00003603 return ABIArgInfo::getIgnore();
3604
Bob Wilson3b694fa2011-11-02 04:51:36 +00003605 // Check for homogeneous aggregates with AAPCS-VFP.
3606 if (getABIKind() == AAPCS_VFP) {
3607 const Type *Base = 0;
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003608 if (isHomogeneousAggregate(RetTy, Base, getContext())) {
3609 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson3b694fa2011-11-02 04:51:36 +00003610 // Homogeneous Aggregates are returned directly.
3611 return ABIArgInfo::getDirect();
Anton Korobeynikoveaf856d2012-04-13 11:22:00 +00003612 }
Bob Wilson3b694fa2011-11-02 04:51:36 +00003613 }
3614
Daniel Dunbar98303b92009-09-13 08:03:58 +00003615 // Aggregates <= 4 bytes are returned in r0; other aggregates
3616 // are returned indirectly.
Chris Lattnera3c109b2010-07-29 02:16:43 +00003617 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar16a08082009-09-14 00:56:55 +00003618 if (Size <= 32) {
3619 // Return in the smallest viable integer type.
3620 if (Size <= 8)
Chris Lattner800588f2010-07-29 06:26:06 +00003621 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003622 if (Size <= 16)
Chris Lattner800588f2010-07-29 06:26:06 +00003623 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
3624 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar16a08082009-09-14 00:56:55 +00003625 }
3626
Daniel Dunbar98303b92009-09-13 08:03:58 +00003627 return ABIArgInfo::getIndirect(0);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003628}
3629
Manman Ren97f81572012-10-16 19:18:39 +00003630/// isIllegalVector - check whether Ty is an illegal vector type.
3631bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
3632 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3633 // Check whether VT is legal.
3634 unsigned NumElements = VT->getNumElements();
3635 uint64_t Size = getContext().getTypeSize(VT);
3636 // NumElements should be power of 2.
3637 if ((NumElements & (NumElements - 1)) != 0)
3638 return true;
3639 // Size should be greater than 32 bits.
3640 return Size <= 32;
3641 }
3642 return false;
3643}
3644
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003645llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner77b89b82010-06-27 07:15:29 +00003646 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00003647 llvm::Type *BP = CGF.Int8PtrTy;
3648 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003649
3650 CGBuilderTy &Builder = CGF.Builder;
Chris Lattner8b418682012-02-07 00:39:47 +00003651 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003652 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Manman Rend105e732012-10-16 19:01:37 +00003653
Tim Northover373ac0a2013-06-21 23:05:33 +00003654 if (isEmptyRecord(getContext(), Ty, true)) {
3655 // These are ignored for parameter passing purposes.
3656 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3657 return Builder.CreateBitCast(Addr, PTy);
3658 }
3659
Manman Rend105e732012-10-16 19:01:37 +00003660 uint64_t Size = CGF.getContext().getTypeSize(Ty) / 8;
Rafael Espindolae164c182011-08-02 22:33:37 +00003661 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8;
Manman Ren97f81572012-10-16 19:18:39 +00003662 bool IsIndirect = false;
Manman Rend105e732012-10-16 19:01:37 +00003663
3664 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
3665 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
Manman Ren93371022012-10-16 19:51:48 +00003666 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
3667 getABIKind() == ARMABIInfo::AAPCS)
3668 TyAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
3669 else
3670 TyAlign = 4;
Manman Ren97f81572012-10-16 19:18:39 +00003671 // Use indirect if size of the illegal vector is bigger than 16 bytes.
3672 if (isIllegalVectorType(Ty) && Size > 16) {
3673 IsIndirect = true;
3674 Size = 4;
3675 TyAlign = 4;
3676 }
Manman Rend105e732012-10-16 19:01:37 +00003677
3678 // Handle address alignment for ABI alignment > 4 bytes.
Rafael Espindolae164c182011-08-02 22:33:37 +00003679 if (TyAlign > 4) {
3680 assert((TyAlign & (TyAlign - 1)) == 0 &&
3681 "Alignment is not power of 2!");
3682 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty);
3683 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1));
3684 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1)));
Manman Rend105e732012-10-16 19:01:37 +00003685 Addr = Builder.CreateIntToPtr(AddrAsInt, BP, "ap.align");
Rafael Espindolae164c182011-08-02 22:33:37 +00003686 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003687
3688 uint64_t Offset =
Manman Rend105e732012-10-16 19:01:37 +00003689 llvm::RoundUpToAlignment(Size, 4);
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003690 llvm::Value *NextAddr =
Chris Lattner77b89b82010-06-27 07:15:29 +00003691 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003692 "ap.next");
3693 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
3694
Manman Ren97f81572012-10-16 19:18:39 +00003695 if (IsIndirect)
3696 Addr = Builder.CreateLoad(Builder.CreateBitCast(Addr, BPP));
Manman Ren93371022012-10-16 19:51:48 +00003697 else if (TyAlign < CGF.getContext().getTypeAlign(Ty) / 8) {
Manman Rend105e732012-10-16 19:01:37 +00003698 // We can't directly cast ap.cur to pointer to a vector type, since ap.cur
3699 // may not be correctly aligned for the vector type. We create an aligned
3700 // temporary space and copy the content over from ap.cur to the temporary
3701 // space. This is necessary if the natural alignment of the type is greater
3702 // than the ABI alignment.
3703 llvm::Type *I8PtrTy = Builder.getInt8PtrTy();
3704 CharUnits CharSize = getContext().getTypeSizeInChars(Ty);
3705 llvm::Value *AlignedTemp = CGF.CreateTempAlloca(CGF.ConvertType(Ty),
3706 "var.align");
3707 llvm::Value *Dst = Builder.CreateBitCast(AlignedTemp, I8PtrTy);
3708 llvm::Value *Src = Builder.CreateBitCast(Addr, I8PtrTy);
3709 Builder.CreateMemCpy(Dst, Src,
3710 llvm::ConstantInt::get(CGF.IntPtrTy, CharSize.getQuantity()),
3711 TyAlign, false);
3712 Addr = AlignedTemp; //The content is in aligned location.
3713 }
3714 llvm::Type *PTy =
3715 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
3716 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
3717
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00003718 return AddrTyped;
3719}
3720
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003721namespace {
3722
Derek Schuff263366f2012-10-16 22:30:41 +00003723class NaClARMABIInfo : public ABIInfo {
3724 public:
3725 NaClARMABIInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3726 : ABIInfo(CGT), PInfo(CGT), NInfo(CGT, Kind) {}
3727 virtual void computeInfo(CGFunctionInfo &FI) const;
3728 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3729 CodeGenFunction &CGF) const;
3730 private:
3731 PNaClABIInfo PInfo; // Used for generating calls with pnaclcall callingconv.
3732 ARMABIInfo NInfo; // Used for everything else.
3733};
3734
3735class NaClARMTargetCodeGenInfo : public TargetCodeGenInfo {
3736 public:
3737 NaClARMTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, ARMABIInfo::ABIKind Kind)
3738 : TargetCodeGenInfo(new NaClARMABIInfo(CGT, Kind)) {}
3739};
3740
Benjamin Kramerc6f84cf2012-10-20 13:02:06 +00003741}
3742
Derek Schuff263366f2012-10-16 22:30:41 +00003743void NaClARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
3744 if (FI.getASTCallingConvention() == CC_PnaclCall)
3745 PInfo.computeInfo(FI);
3746 else
3747 static_cast<const ABIInfo&>(NInfo).computeInfo(FI);
3748}
3749
3750llvm::Value *NaClARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3751 CodeGenFunction &CGF) const {
3752 // Always use the native convention; calling pnacl-style varargs functions
3753 // is unsupported.
3754 return static_cast<const ABIInfo&>(NInfo).EmitVAArg(VAListAddr, Ty, CGF);
3755}
3756
Chris Lattnerdce5ad02010-06-28 20:05:43 +00003757//===----------------------------------------------------------------------===//
Tim Northoverc264e162013-01-31 12:13:10 +00003758// AArch64 ABI Implementation
3759//===----------------------------------------------------------------------===//
3760
3761namespace {
3762
3763class AArch64ABIInfo : public ABIInfo {
3764public:
3765 AArch64ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
3766
3767private:
3768 // The AArch64 PCS is explicit about return types and argument types being
3769 // handled identically, so we don't need to draw a distinction between
3770 // Argument and Return classification.
3771 ABIArgInfo classifyGenericType(QualType Ty, int &FreeIntRegs,
3772 int &FreeVFPRegs) const;
3773
3774 ABIArgInfo tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded, bool IsInt,
3775 llvm::Type *DirectTy = 0) const;
3776
3777 virtual void computeInfo(CGFunctionInfo &FI) const;
3778
3779 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3780 CodeGenFunction &CGF) const;
3781};
3782
3783class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
3784public:
3785 AArch64TargetCodeGenInfo(CodeGenTypes &CGT)
3786 :TargetCodeGenInfo(new AArch64ABIInfo(CGT)) {}
3787
3788 const AArch64ABIInfo &getABIInfo() const {
3789 return static_cast<const AArch64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
3790 }
3791
3792 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
3793 return 31;
3794 }
3795
3796 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3797 llvm::Value *Address) const {
3798 // 0-31 are x0-x30 and sp: 8 bytes each
3799 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
3800 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 31);
3801
3802 // 64-95 are v0-v31: 16 bytes each
3803 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
3804 AssignToArrayRange(CGF.Builder, Address, Sixteen8, 64, 95);
3805
3806 return false;
3807 }
3808
3809};
3810
3811}
3812
3813void AArch64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3814 int FreeIntRegs = 8, FreeVFPRegs = 8;
3815
3816 FI.getReturnInfo() = classifyGenericType(FI.getReturnType(),
3817 FreeIntRegs, FreeVFPRegs);
3818
3819 FreeIntRegs = FreeVFPRegs = 8;
3820 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3821 it != ie; ++it) {
3822 it->info = classifyGenericType(it->type, FreeIntRegs, FreeVFPRegs);
3823
3824 }
3825}
3826
3827ABIArgInfo
3828AArch64ABIInfo::tryUseRegs(QualType Ty, int &FreeRegs, int RegsNeeded,
3829 bool IsInt, llvm::Type *DirectTy) const {
3830 if (FreeRegs >= RegsNeeded) {
3831 FreeRegs -= RegsNeeded;
3832 return ABIArgInfo::getDirect(DirectTy);
3833 }
3834
3835 llvm::Type *Padding = 0;
3836
3837 // We need padding so that later arguments don't get filled in anyway. That
3838 // wouldn't happen if only ByVal arguments followed in the same category, but
3839 // a large structure will simply seem to be a pointer as far as LLVM is
3840 // concerned.
3841 if (FreeRegs > 0) {
3842 if (IsInt)
3843 Padding = llvm::Type::getInt64Ty(getVMContext());
3844 else
3845 Padding = llvm::Type::getFloatTy(getVMContext());
3846
3847 // Either [N x i64] or [N x float].
3848 Padding = llvm::ArrayType::get(Padding, FreeRegs);
3849 FreeRegs = 0;
3850 }
3851
3852 return ABIArgInfo::getIndirect(getContext().getTypeAlign(Ty) / 8,
3853 /*IsByVal=*/ true, /*Realign=*/ false,
3854 Padding);
3855}
3856
3857
3858ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
3859 int &FreeIntRegs,
3860 int &FreeVFPRegs) const {
3861 // Can only occurs for return, but harmless otherwise.
3862 if (Ty->isVoidType())
3863 return ABIArgInfo::getIgnore();
3864
3865 // Large vector types should be returned via memory. There's no such concept
3866 // in the ABI, but they'd be over 16 bytes anyway so no matter how they're
3867 // classified they'd go into memory (see B.3).
3868 if (Ty->isVectorType() && getContext().getTypeSize(Ty) > 128) {
3869 if (FreeIntRegs > 0)
3870 --FreeIntRegs;
3871 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
3872 }
3873
3874 // All non-aggregate LLVM types have a concrete ABI representation so they can
3875 // be passed directly. After this block we're guaranteed to be in a
3876 // complicated case.
3877 if (!isAggregateTypeForABI(Ty)) {
3878 // Treat an enum type as its underlying type.
3879 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3880 Ty = EnumTy->getDecl()->getIntegerType();
3881
3882 if (Ty->isFloatingType() || Ty->isVectorType())
3883 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ false);
3884
3885 assert(getContext().getTypeSize(Ty) <= 128 &&
3886 "unexpectedly large scalar type");
3887
3888 int RegsNeeded = getContext().getTypeSize(Ty) > 64 ? 2 : 1;
3889
3890 // If the type may need padding registers to ensure "alignment", we must be
3891 // careful when this is accounted for. Increasing the effective size covers
3892 // all cases.
3893 if (getContext().getTypeAlign(Ty) == 128)
3894 RegsNeeded += FreeIntRegs % 2 != 0;
3895
3896 return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
3897 }
3898
Mark Lacey23630722013-10-06 01:33:34 +00003899 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003900 if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
Tim Northoverc264e162013-01-31 12:13:10 +00003901 --FreeIntRegs;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00003902 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tim Northoverc264e162013-01-31 12:13:10 +00003903 }
3904
3905 if (isEmptyRecord(getContext(), Ty, true)) {
3906 if (!getContext().getLangOpts().CPlusPlus) {
3907 // Empty structs outside C++ mode are a GNU extension, so no ABI can
3908 // possibly tell us what to do. It turns out (I believe) that GCC ignores
3909 // the object for parameter-passsing purposes.
3910 return ABIArgInfo::getIgnore();
3911 }
3912
3913 // The combination of C++98 9p5 (sizeof(struct) != 0) and the pseudocode
3914 // description of va_arg in the PCS require that an empty struct does
3915 // actually occupy space for parameter-passing. I'm hoping for a
3916 // clarification giving an explicit paragraph to point to in future.
3917 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ 1, /*IsInt=*/ true,
3918 llvm::Type::getInt8Ty(getVMContext()));
3919 }
3920
3921 // Homogeneous vector aggregates get passed in registers or on the stack.
3922 const Type *Base = 0;
3923 uint64_t NumMembers = 0;
3924 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)) {
3925 assert(Base && "Base class should be set for homogeneous aggregate");
3926 // Homogeneous aggregates are passed and returned directly.
3927 return tryUseRegs(Ty, FreeVFPRegs, /*RegsNeeded=*/ NumMembers,
3928 /*IsInt=*/ false);
3929 }
3930
3931 uint64_t Size = getContext().getTypeSize(Ty);
3932 if (Size <= 128) {
3933 // Small structs can use the same direct type whether they're in registers
3934 // or on the stack.
3935 llvm::Type *BaseTy;
3936 unsigned NumBases;
3937 int SizeInRegs = (Size + 63) / 64;
3938
3939 if (getContext().getTypeAlign(Ty) == 128) {
3940 BaseTy = llvm::Type::getIntNTy(getVMContext(), 128);
3941 NumBases = 1;
3942
3943 // If the type may need padding registers to ensure "alignment", we must
3944 // be careful when this is accounted for. Increasing the effective size
3945 // covers all cases.
3946 SizeInRegs += FreeIntRegs % 2 != 0;
3947 } else {
3948 BaseTy = llvm::Type::getInt64Ty(getVMContext());
3949 NumBases = SizeInRegs;
3950 }
3951 llvm::Type *DirectTy = llvm::ArrayType::get(BaseTy, NumBases);
3952
3953 return tryUseRegs(Ty, FreeIntRegs, /*RegsNeeded=*/ SizeInRegs,
3954 /*IsInt=*/ true, DirectTy);
3955 }
3956
3957 // If the aggregate is > 16 bytes, it's passed and returned indirectly. In
3958 // LLVM terms the return uses an "sret" pointer, but that's handled elsewhere.
3959 --FreeIntRegs;
3960 return ABIArgInfo::getIndirect(0, /* byVal = */ false);
3961}
3962
3963llvm::Value *AArch64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
3964 CodeGenFunction &CGF) const {
3965 // The AArch64 va_list type and handling is specified in the Procedure Call
3966 // Standard, section B.4:
3967 //
3968 // struct {
3969 // void *__stack;
3970 // void *__gr_top;
3971 // void *__vr_top;
3972 // int __gr_offs;
3973 // int __vr_offs;
3974 // };
3975
3976 assert(!CGF.CGM.getDataLayout().isBigEndian()
3977 && "va_arg not implemented for big-endian AArch64");
3978
3979 int FreeIntRegs = 8, FreeVFPRegs = 8;
3980 Ty = CGF.getContext().getCanonicalType(Ty);
3981 ABIArgInfo AI = classifyGenericType(Ty, FreeIntRegs, FreeVFPRegs);
3982
3983 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
3984 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3985 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
3986 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3987
3988 llvm::Value *reg_offs_p = 0, *reg_offs = 0;
3989 int reg_top_index;
3990 int RegSize;
3991 if (FreeIntRegs < 8) {
3992 assert(FreeVFPRegs == 8 && "Arguments never split between int & VFP regs");
3993 // 3 is the field number of __gr_offs
3994 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
3995 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
3996 reg_top_index = 1; // field number for __gr_top
3997 RegSize = 8 * (8 - FreeIntRegs);
3998 } else {
3999 assert(FreeVFPRegs < 8 && "Argument must go in VFP or int regs");
4000 // 4 is the field number of __vr_offs.
4001 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
4002 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4003 reg_top_index = 2; // field number for __vr_top
4004 RegSize = 16 * (8 - FreeVFPRegs);
4005 }
4006
4007 //=======================================
4008 // Find out where argument was passed
4009 //=======================================
4010
4011 // If reg_offs >= 0 we're already using the stack for this type of
4012 // argument. We don't want to keep updating reg_offs (in case it overflows,
4013 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4014 // whatever they get).
4015 llvm::Value *UsingStack = 0;
4016 UsingStack = CGF.Builder.CreateICmpSGE(reg_offs,
4017 llvm::ConstantInt::get(CGF.Int32Ty, 0));
4018
4019 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4020
4021 // Otherwise, at least some kind of argument could go in these registers, the
4022 // quesiton is whether this particular type is too big.
4023 CGF.EmitBlock(MaybeRegBlock);
4024
4025 // Integer arguments may need to correct register alignment (for example a
4026 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4027 // align __gr_offs to calculate the potential address.
4028 if (FreeIntRegs < 8 && AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4029 int Align = getContext().getTypeAlign(Ty) / 8;
4030
4031 reg_offs = CGF.Builder.CreateAdd(reg_offs,
4032 llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4033 "align_regoffs");
4034 reg_offs = CGF.Builder.CreateAnd(reg_offs,
4035 llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4036 "aligned_regoffs");
4037 }
4038
4039 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
4040 llvm::Value *NewOffset = 0;
4041 NewOffset = CGF.Builder.CreateAdd(reg_offs,
4042 llvm::ConstantInt::get(CGF.Int32Ty, RegSize),
4043 "new_reg_offs");
4044 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4045
4046 // Now we're in a position to decide whether this argument really was in
4047 // registers or not.
4048 llvm::Value *InRegs = 0;
4049 InRegs = CGF.Builder.CreateICmpSLE(NewOffset,
4050 llvm::ConstantInt::get(CGF.Int32Ty, 0),
4051 "inreg");
4052
4053 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4054
4055 //=======================================
4056 // Argument was in registers
4057 //=======================================
4058
4059 // Now we emit the code for if the argument was originally passed in
4060 // registers. First start the appropriate block:
4061 CGF.EmitBlock(InRegBlock);
4062
4063 llvm::Value *reg_top_p = 0, *reg_top = 0;
4064 reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
4065 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
4066 llvm::Value *BaseAddr = CGF.Builder.CreateGEP(reg_top, reg_offs);
4067 llvm::Value *RegAddr = 0;
4068 llvm::Type *MemTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4069
4070 if (!AI.isDirect()) {
4071 // If it's been passed indirectly (actually a struct), whatever we find from
4072 // stored registers or on the stack will actually be a struct **.
4073 MemTy = llvm::PointerType::getUnqual(MemTy);
4074 }
4075
4076 const Type *Base = 0;
4077 uint64_t NumMembers;
4078 if (isHomogeneousAggregate(Ty, Base, getContext(), &NumMembers)
4079 && NumMembers > 1) {
4080 // Homogeneous aggregates passed in registers will have their elements split
4081 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4082 // qN+1, ...). We reload and store into a temporary local variable
4083 // contiguously.
4084 assert(AI.isDirect() && "Homogeneous aggregates should be passed directly");
4085 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4086 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
4087 llvm::Value *Tmp = CGF.CreateTempAlloca(HFATy);
4088
4089 for (unsigned i = 0; i < NumMembers; ++i) {
4090 llvm::Value *BaseOffset = llvm::ConstantInt::get(CGF.Int32Ty, 16 * i);
4091 llvm::Value *LoadAddr = CGF.Builder.CreateGEP(BaseAddr, BaseOffset);
4092 LoadAddr = CGF.Builder.CreateBitCast(LoadAddr,
4093 llvm::PointerType::getUnqual(BaseTy));
4094 llvm::Value *StoreAddr = CGF.Builder.CreateStructGEP(Tmp, i);
4095
4096 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4097 CGF.Builder.CreateStore(Elem, StoreAddr);
4098 }
4099
4100 RegAddr = CGF.Builder.CreateBitCast(Tmp, MemTy);
4101 } else {
4102 // Otherwise the object is contiguous in memory
4103 RegAddr = CGF.Builder.CreateBitCast(BaseAddr, MemTy);
4104 }
4105
4106 CGF.EmitBranch(ContBlock);
4107
4108 //=======================================
4109 // Argument was on the stack
4110 //=======================================
4111 CGF.EmitBlock(OnStackBlock);
4112
4113 llvm::Value *stack_p = 0, *OnStackAddr = 0;
4114 stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
4115 OnStackAddr = CGF.Builder.CreateLoad(stack_p, "stack");
4116
4117 // Again, stack arguments may need realigmnent. In this case both integer and
4118 // floating-point ones might be affected.
4119 if (AI.isDirect() && getContext().getTypeAlign(Ty) > 64) {
4120 int Align = getContext().getTypeAlign(Ty) / 8;
4121
4122 OnStackAddr = CGF.Builder.CreatePtrToInt(OnStackAddr, CGF.Int64Ty);
4123
4124 OnStackAddr = CGF.Builder.CreateAdd(OnStackAddr,
4125 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
4126 "align_stack");
4127 OnStackAddr = CGF.Builder.CreateAnd(OnStackAddr,
4128 llvm::ConstantInt::get(CGF.Int64Ty, -Align),
4129 "align_stack");
4130
4131 OnStackAddr = CGF.Builder.CreateIntToPtr(OnStackAddr, CGF.Int8PtrTy);
4132 }
4133
4134 uint64_t StackSize;
4135 if (AI.isDirect())
4136 StackSize = getContext().getTypeSize(Ty) / 8;
4137 else
4138 StackSize = 8;
4139
4140 // All stack slots are 8 bytes
4141 StackSize = llvm::RoundUpToAlignment(StackSize, 8);
4142
4143 llvm::Value *StackSizeC = llvm::ConstantInt::get(CGF.Int32Ty, StackSize);
4144 llvm::Value *NewStack = CGF.Builder.CreateGEP(OnStackAddr, StackSizeC,
4145 "new_stack");
4146
4147 // Write the new value of __stack for the next call to va_arg
4148 CGF.Builder.CreateStore(NewStack, stack_p);
4149
4150 OnStackAddr = CGF.Builder.CreateBitCast(OnStackAddr, MemTy);
4151
4152 CGF.EmitBranch(ContBlock);
4153
4154 //=======================================
4155 // Tidy up
4156 //=======================================
4157 CGF.EmitBlock(ContBlock);
4158
4159 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(MemTy, 2, "vaarg.addr");
4160 ResAddr->addIncoming(RegAddr, InRegBlock);
4161 ResAddr->addIncoming(OnStackAddr, OnStackBlock);
4162
4163 if (AI.isDirect())
4164 return ResAddr;
4165
4166 return CGF.Builder.CreateLoad(ResAddr, "vaarg.addr");
4167}
4168
4169//===----------------------------------------------------------------------===//
Justin Holewinski2c585b92012-05-24 17:43:12 +00004170// NVPTX ABI Implementation
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004171//===----------------------------------------------------------------------===//
4172
4173namespace {
4174
Justin Holewinski2c585b92012-05-24 17:43:12 +00004175class NVPTXABIInfo : public ABIInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004176public:
Justin Holewinskidca8f332013-03-30 14:38:24 +00004177 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004178
4179 ABIArgInfo classifyReturnType(QualType RetTy) const;
4180 ABIArgInfo classifyArgumentType(QualType Ty) const;
4181
4182 virtual void computeInfo(CGFunctionInfo &FI) const;
4183 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4184 CodeGenFunction &CFG) const;
4185};
4186
Justin Holewinski2c585b92012-05-24 17:43:12 +00004187class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004188public:
Justin Holewinski2c585b92012-05-24 17:43:12 +00004189 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
4190 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Justin Holewinski818eafb2011-10-05 17:58:44 +00004191
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004192 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4193 CodeGen::CodeGenModule &M) const;
Justin Holewinskidca8f332013-03-30 14:38:24 +00004194private:
4195 static void addKernelMetadata(llvm::Function *F);
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004196};
4197
Justin Holewinski2c585b92012-05-24 17:43:12 +00004198ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004199 if (RetTy->isVoidType())
4200 return ABIArgInfo::getIgnore();
4201 if (isAggregateTypeForABI(RetTy))
4202 return ABIArgInfo::getIndirect(0);
4203 return ABIArgInfo::getDirect();
4204}
4205
Justin Holewinski2c585b92012-05-24 17:43:12 +00004206ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004207 if (isAggregateTypeForABI(Ty))
4208 return ABIArgInfo::getIndirect(0);
4209
4210 return ABIArgInfo::getDirect();
4211}
4212
Justin Holewinski2c585b92012-05-24 17:43:12 +00004213void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004214 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4215 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4216 it != ie; ++it)
4217 it->info = classifyArgumentType(it->type);
4218
4219 // Always honor user-specified calling convention.
4220 if (FI.getCallingConvention() != llvm::CallingConv::C)
4221 return;
4222
John McCallbd7370a2013-02-28 19:01:20 +00004223 FI.setEffectiveCallingConvention(getRuntimeCC());
4224}
4225
Justin Holewinski2c585b92012-05-24 17:43:12 +00004226llvm::Value *NVPTXABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4227 CodeGenFunction &CFG) const {
4228 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004229}
4230
Justin Holewinski2c585b92012-05-24 17:43:12 +00004231void NVPTXTargetCodeGenInfo::
4232SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4233 CodeGen::CodeGenModule &M) const{
Justin Holewinski818eafb2011-10-05 17:58:44 +00004234 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4235 if (!FD) return;
4236
4237 llvm::Function *F = cast<llvm::Function>(GV);
4238
4239 // Perform special handling in OpenCL mode
David Blaikie4e4d0842012-03-11 07:00:24 +00004240 if (M.getLangOpts().OpenCL) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004241 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004242 // By default, all functions are device functions
Justin Holewinski818eafb2011-10-05 17:58:44 +00004243 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004244 // OpenCL __kernel functions get kernel metadata
4245 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004246 // And kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004247 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004248 }
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004249 }
Justin Holewinski818eafb2011-10-05 17:58:44 +00004250
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004251 // Perform special handling in CUDA mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00004252 if (M.getLangOpts().CUDA) {
Justin Holewinskidca8f332013-03-30 14:38:24 +00004253 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne744d90b2011-10-06 16:49:54 +00004254 // __global__ functions cannot be called from the device, we do not
4255 // need to set the noinline attribute.
4256 if (FD->getAttr<CUDAGlobalAttr>())
Justin Holewinskidca8f332013-03-30 14:38:24 +00004257 addKernelMetadata(F);
Justin Holewinski818eafb2011-10-05 17:58:44 +00004258 }
4259}
4260
Justin Holewinskidca8f332013-03-30 14:38:24 +00004261void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
4262 llvm::Module *M = F->getParent();
4263 llvm::LLVMContext &Ctx = M->getContext();
4264
4265 // Get "nvvm.annotations" metadata node
4266 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
4267
4268 // Create !{<func-ref>, metadata !"kernel", i32 1} node
4269 llvm::SmallVector<llvm::Value *, 3> MDVals;
4270 MDVals.push_back(F);
4271 MDVals.push_back(llvm::MDString::get(Ctx, "kernel"));
4272 MDVals.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1));
4273
4274 // Append metadata to nvvm.annotations
4275 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
4276}
4277
Justin Holewinski0259c3a2011-04-22 11:10:38 +00004278}
4279
4280//===----------------------------------------------------------------------===//
Ulrich Weigandb8409212013-05-06 16:26:41 +00004281// SystemZ ABI Implementation
4282//===----------------------------------------------------------------------===//
4283
4284namespace {
4285
4286class SystemZABIInfo : public ABIInfo {
4287public:
4288 SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
4289
4290 bool isPromotableIntegerType(QualType Ty) const;
4291 bool isCompoundType(QualType Ty) const;
4292 bool isFPArgumentType(QualType Ty) const;
4293
4294 ABIArgInfo classifyReturnType(QualType RetTy) const;
4295 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
4296
4297 virtual void computeInfo(CGFunctionInfo &FI) const {
4298 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4299 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4300 it != ie; ++it)
4301 it->info = classifyArgumentType(it->type);
4302 }
4303
4304 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4305 CodeGenFunction &CGF) const;
4306};
4307
4308class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
4309public:
4310 SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
4311 : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
4312};
4313
4314}
4315
4316bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
4317 // Treat an enum type as its underlying type.
4318 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4319 Ty = EnumTy->getDecl()->getIntegerType();
4320
4321 // Promotable integer types are required to be promoted by the ABI.
4322 if (Ty->isPromotableIntegerType())
4323 return true;
4324
4325 // 32-bit values must also be promoted.
4326 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4327 switch (BT->getKind()) {
4328 case BuiltinType::Int:
4329 case BuiltinType::UInt:
4330 return true;
4331 default:
4332 return false;
4333 }
4334 return false;
4335}
4336
4337bool SystemZABIInfo::isCompoundType(QualType Ty) const {
4338 return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
4339}
4340
4341bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
4342 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4343 switch (BT->getKind()) {
4344 case BuiltinType::Float:
4345 case BuiltinType::Double:
4346 return true;
4347 default:
4348 return false;
4349 }
4350
4351 if (const RecordType *RT = Ty->getAsStructureType()) {
4352 const RecordDecl *RD = RT->getDecl();
4353 bool Found = false;
4354
4355 // If this is a C++ record, check the bases first.
4356 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4357 for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
4358 E = CXXRD->bases_end(); I != E; ++I) {
4359 QualType Base = I->getType();
4360
4361 // Empty bases don't affect things either way.
4362 if (isEmptyRecord(getContext(), Base, true))
4363 continue;
4364
4365 if (Found)
4366 return false;
4367 Found = isFPArgumentType(Base);
4368 if (!Found)
4369 return false;
4370 }
4371
4372 // Check the fields.
4373 for (RecordDecl::field_iterator I = RD->field_begin(),
4374 E = RD->field_end(); I != E; ++I) {
4375 const FieldDecl *FD = *I;
4376
4377 // Empty bitfields don't affect things either way.
4378 // Unlike isSingleElementStruct(), empty structure and array fields
4379 // do count. So do anonymous bitfields that aren't zero-sized.
4380 if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4381 return true;
4382
4383 // Unlike isSingleElementStruct(), arrays do not count.
4384 // Nested isFPArgumentType structures still do though.
4385 if (Found)
4386 return false;
4387 Found = isFPArgumentType(FD->getType());
4388 if (!Found)
4389 return false;
4390 }
4391
4392 // Unlike isSingleElementStruct(), trailing padding is allowed.
4393 // An 8-byte aligned struct s { float f; } is passed as a double.
4394 return Found;
4395 }
4396
4397 return false;
4398}
4399
4400llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4401 CodeGenFunction &CGF) const {
4402 // Assume that va_list type is correct; should be pointer to LLVM type:
4403 // struct {
4404 // i64 __gpr;
4405 // i64 __fpr;
4406 // i8 *__overflow_arg_area;
4407 // i8 *__reg_save_area;
4408 // };
4409
4410 // Every argument occupies 8 bytes and is passed by preference in either
4411 // GPRs or FPRs.
4412 Ty = CGF.getContext().getCanonicalType(Ty);
4413 ABIArgInfo AI = classifyArgumentType(Ty);
4414 bool InFPRs = isFPArgumentType(Ty);
4415
4416 llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
4417 bool IsIndirect = AI.isIndirect();
4418 unsigned UnpaddedBitSize;
4419 if (IsIndirect) {
4420 APTy = llvm::PointerType::getUnqual(APTy);
4421 UnpaddedBitSize = 64;
4422 } else
4423 UnpaddedBitSize = getContext().getTypeSize(Ty);
4424 unsigned PaddedBitSize = 64;
4425 assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
4426
4427 unsigned PaddedSize = PaddedBitSize / 8;
4428 unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
4429
4430 unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
4431 if (InFPRs) {
4432 MaxRegs = 4; // Maximum of 4 FPR arguments
4433 RegCountField = 1; // __fpr
4434 RegSaveIndex = 16; // save offset for f0
4435 RegPadding = 0; // floats are passed in the high bits of an FPR
4436 } else {
4437 MaxRegs = 5; // Maximum of 5 GPR arguments
4438 RegCountField = 0; // __gpr
4439 RegSaveIndex = 2; // save offset for r2
4440 RegPadding = Padding; // values are passed in the low bits of a GPR
4441 }
4442
4443 llvm::Value *RegCountPtr =
4444 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
4445 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
4446 llvm::Type *IndexTy = RegCount->getType();
4447 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
4448 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
4449 "fits_in_regs");
4450
4451 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4452 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
4453 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
4454 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
4455
4456 // Emit code to load the value if it was passed in registers.
4457 CGF.EmitBlock(InRegBlock);
4458
4459 // Work out the address of an argument register.
4460 llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
4461 llvm::Value *ScaledRegCount =
4462 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
4463 llvm::Value *RegBase =
4464 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
4465 llvm::Value *RegOffset =
4466 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
4467 llvm::Value *RegSaveAreaPtr =
4468 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
4469 llvm::Value *RegSaveArea =
4470 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
4471 llvm::Value *RawRegAddr =
4472 CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
4473 llvm::Value *RegAddr =
4474 CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
4475
4476 // Update the register count
4477 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
4478 llvm::Value *NewRegCount =
4479 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
4480 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
4481 CGF.EmitBranch(ContBlock);
4482
4483 // Emit code to load the value if it was passed in memory.
4484 CGF.EmitBlock(InMemBlock);
4485
4486 // Work out the address of a stack argument.
4487 llvm::Value *OverflowArgAreaPtr =
4488 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
4489 llvm::Value *OverflowArgArea =
4490 CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
4491 llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
4492 llvm::Value *RawMemAddr =
4493 CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
4494 llvm::Value *MemAddr =
4495 CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
4496
4497 // Update overflow_arg_area_ptr pointer
4498 llvm::Value *NewOverflowArgArea =
4499 CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
4500 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
4501 CGF.EmitBranch(ContBlock);
4502
4503 // Return the appropriate result.
4504 CGF.EmitBlock(ContBlock);
4505 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
4506 ResAddr->addIncoming(RegAddr, InRegBlock);
4507 ResAddr->addIncoming(MemAddr, InMemBlock);
4508
4509 if (IsIndirect)
4510 return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
4511
4512 return ResAddr;
4513}
4514
John McCallb8b52972013-06-18 02:46:29 +00004515bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
4516 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4517 assert(Triple.getArch() == llvm::Triple::x86);
4518
4519 switch (Opts.getStructReturnConvention()) {
4520 case CodeGenOptions::SRCK_Default:
4521 break;
4522 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
4523 return false;
4524 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
4525 return true;
4526 }
4527
4528 if (Triple.isOSDarwin())
4529 return true;
4530
4531 switch (Triple.getOS()) {
4532 case llvm::Triple::Cygwin:
4533 case llvm::Triple::MinGW32:
4534 case llvm::Triple::AuroraUX:
4535 case llvm::Triple::DragonFly:
4536 case llvm::Triple::FreeBSD:
4537 case llvm::Triple::OpenBSD:
4538 case llvm::Triple::Bitrig:
4539 case llvm::Triple::Win32:
4540 return true;
4541 default:
4542 return false;
4543 }
4544}
Ulrich Weigandb8409212013-05-06 16:26:41 +00004545
4546ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
4547 if (RetTy->isVoidType())
4548 return ABIArgInfo::getIgnore();
4549 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
4550 return ABIArgInfo::getIndirect(0);
4551 return (isPromotableIntegerType(RetTy) ?
4552 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4553}
4554
4555ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
4556 // Handle the generic C++ ABI.
Mark Lacey23630722013-10-06 01:33:34 +00004557 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Ulrich Weigandb8409212013-05-06 16:26:41 +00004558 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
4559
4560 // Integers and enums are extended to full register width.
4561 if (isPromotableIntegerType(Ty))
4562 return ABIArgInfo::getExtend();
4563
4564 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
4565 uint64_t Size = getContext().getTypeSize(Ty);
4566 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
4567 return ABIArgInfo::getIndirect(0);
4568
4569 // Handle small structures.
4570 if (const RecordType *RT = Ty->getAs<RecordType>()) {
4571 // Structures with flexible arrays have variable length, so really
4572 // fail the size test above.
4573 const RecordDecl *RD = RT->getDecl();
4574 if (RD->hasFlexibleArrayMember())
4575 return ABIArgInfo::getIndirect(0);
4576
4577 // The structure is passed as an unextended integer, a float, or a double.
4578 llvm::Type *PassTy;
4579 if (isFPArgumentType(Ty)) {
4580 assert(Size == 32 || Size == 64);
4581 if (Size == 32)
4582 PassTy = llvm::Type::getFloatTy(getVMContext());
4583 else
4584 PassTy = llvm::Type::getDoubleTy(getVMContext());
4585 } else
4586 PassTy = llvm::IntegerType::get(getVMContext(), Size);
4587 return ABIArgInfo::getDirect(PassTy);
4588 }
4589
4590 // Non-structure compounds are passed indirectly.
4591 if (isCompoundType(Ty))
4592 return ABIArgInfo::getIndirect(0);
4593
4594 return ABIArgInfo::getDirect(0);
4595}
4596
4597//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004598// MSP430 ABI Implementation
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004599//===----------------------------------------------------------------------===//
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004600
4601namespace {
4602
4603class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
4604public:
Chris Lattnerea044322010-07-29 02:01:43 +00004605 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
4606 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004607 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4608 CodeGen::CodeGenModule &M) const;
4609};
4610
4611}
4612
4613void MSP430TargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4614 llvm::GlobalValue *GV,
4615 CodeGen::CodeGenModule &M) const {
4616 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4617 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
4618 // Handle 'interrupt' attribute:
4619 llvm::Function *F = cast<llvm::Function>(GV);
4620
4621 // Step 1: Set ISR calling convention.
4622 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
4623
4624 // Step 2: Add attributes goodness.
Bill Wendling72390b32012-12-20 19:27:06 +00004625 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004626
4627 // Step 3: Emit ISR vector alias.
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004628 unsigned Num = attr->getNumber() / 2;
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004629 new llvm::GlobalAlias(GV->getType(), llvm::Function::ExternalLinkage,
Anton Korobeynikovf419a852012-11-26 18:59:10 +00004630 "__isr_" + Twine(Num),
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00004631 GV, &M.getModule());
4632 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00004633 }
4634}
4635
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004636//===----------------------------------------------------------------------===//
John McCallaeeb7012010-05-27 06:19:26 +00004637// MIPS ABI Implementation. This works for both little-endian and
4638// big-endian variants.
Chris Lattnerdce5ad02010-06-28 20:05:43 +00004639//===----------------------------------------------------------------------===//
4640
John McCallaeeb7012010-05-27 06:19:26 +00004641namespace {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004642class MipsABIInfo : public ABIInfo {
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004643 bool IsO32;
Akira Hatanakac359f202012-07-03 19:24:06 +00004644 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
4645 void CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00004646 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004647 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004648 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004649 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004650public:
Akira Hatanaka550ed202013-10-29 19:00:35 +00004651 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32, bool HasFP64) :
Akira Hatanakac359f202012-07-03 19:24:06 +00004652 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanaka550ed202013-10-29 19:00:35 +00004653 StackAlignInBytes(IsO32 && !HasFP64 ? 8 : 16) {}
Akira Hatanaka619e8872011-06-02 00:09:17 +00004654
4655 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004656 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004657 virtual void computeInfo(CGFunctionInfo &FI) const;
4658 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4659 CodeGenFunction &CGF) const;
4660};
4661
John McCallaeeb7012010-05-27 06:19:26 +00004662class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004663 unsigned SizeOfUnwindException;
John McCallaeeb7012010-05-27 06:19:26 +00004664public:
Akira Hatanaka550ed202013-10-29 19:00:35 +00004665 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32, const TargetInfo &Info)
4666 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32, Info.hasFeature("fp64"))),
Akira Hatanakac0e3b662011-11-02 23:14:57 +00004667 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCallaeeb7012010-05-27 06:19:26 +00004668
4669 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
4670 return 29;
4671 }
4672
Reed Kotler7dfd1822013-01-16 17:10:28 +00004673 void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4674 CodeGen::CodeGenModule &CGM) const {
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004675 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4676 if (!FD) return;
Rafael Espindolad8e6d6d2013-03-19 14:32:23 +00004677 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004678 if (FD->hasAttr<Mips16Attr>()) {
4679 Fn->addFnAttr("mips16");
4680 }
4681 else if (FD->hasAttr<NoMips16Attr>()) {
4682 Fn->addFnAttr("nomips16");
4683 }
Reed Kotler7dfd1822013-01-16 17:10:28 +00004684 }
Reed Kotlerad4b8b42013-03-13 20:40:30 +00004685
John McCallaeeb7012010-05-27 06:19:26 +00004686 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Michael J. Spencer8bea82f2010-08-25 18:17:27 +00004687 llvm::Value *Address) const;
John McCall49e34be2011-08-30 01:42:09 +00004688
4689 unsigned getSizeOfUnwindException() const {
Akira Hatanakae624fa02011-09-20 18:23:28 +00004690 return SizeOfUnwindException;
John McCall49e34be2011-08-30 01:42:09 +00004691 }
John McCallaeeb7012010-05-27 06:19:26 +00004692};
4693}
4694
Akira Hatanakac359f202012-07-03 19:24:06 +00004695void MipsABIInfo::CoerceToIntArgs(uint64_t TySize,
Craig Topper6b9240e2013-07-05 19:34:19 +00004696 SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00004697 llvm::IntegerType *IntTy =
4698 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004699
4700 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
4701 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
4702 ArgList.push_back(IntTy);
4703
4704 // If necessary, add one more integer type to ArgList.
4705 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
4706
4707 if (R)
4708 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004709}
4710
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004711// In N32/64, an aligned double precision floating point field is passed in
4712// a register.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004713llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakac359f202012-07-03 19:24:06 +00004714 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
4715
4716 if (IsO32) {
4717 CoerceToIntArgs(TySize, ArgList);
4718 return llvm::StructType::get(getVMContext(), ArgList);
4719 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004720
Akira Hatanaka2afd23d2012-01-12 00:52:17 +00004721 if (Ty->isComplexType())
4722 return CGT.ConvertType(Ty);
Akira Hatanaka6d1080f2012-01-10 23:12:19 +00004723
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004724 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004725
Akira Hatanakac359f202012-07-03 19:24:06 +00004726 // Unions/vectors are passed in integer registers.
4727 if (!RT || !RT->isStructureOrClassType()) {
4728 CoerceToIntArgs(TySize, ArgList);
4729 return llvm::StructType::get(getVMContext(), ArgList);
4730 }
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004731
4732 const RecordDecl *RD = RT->getDecl();
4733 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004734 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004735
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004736 uint64_t LastOffset = 0;
4737 unsigned idx = 0;
4738 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
4739
Akira Hatanakaa34e9212012-02-09 19:54:16 +00004740 // Iterate over fields in the struct/class and check if there are any aligned
4741 // double fields.
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004742 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
4743 i != e; ++i, ++idx) {
David Blaikie262bc182012-04-30 02:36:29 +00004744 const QualType Ty = i->getType();
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004745 const BuiltinType *BT = Ty->getAs<BuiltinType>();
4746
4747 if (!BT || BT->getKind() != BuiltinType::Double)
4748 continue;
4749
4750 uint64_t Offset = Layout.getFieldOffset(idx);
4751 if (Offset % 64) // Ignore doubles that are not aligned.
4752 continue;
4753
4754 // Add ((Offset - LastOffset) / 64) args of type i64.
4755 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
4756 ArgList.push_back(I64);
4757
4758 // Add double type.
4759 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
4760 LastOffset = Offset + 64;
4761 }
4762
Akira Hatanakac359f202012-07-03 19:24:06 +00004763 CoerceToIntArgs(TySize - LastOffset, IntArgList);
4764 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanakad5a257f2011-11-02 23:54:49 +00004765
4766 return llvm::StructType::get(getVMContext(), ArgList);
4767}
4768
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00004769llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
4770 uint64_t Offset) const {
4771 if (OrigOffset + MinABIStackAlignInBytes > Offset)
4772 return 0;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004773
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00004774 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004775}
Akira Hatanaka9659d592012-01-10 22:44:52 +00004776
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004777ABIArgInfo
4778MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004779 uint64_t OrigOffset = Offset;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004780 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004781 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004782
Akira Hatanakac359f202012-07-03 19:24:06 +00004783 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
4784 (uint64_t)StackAlignInBytes);
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00004785 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
4786 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004787
Akira Hatanakac359f202012-07-03 19:24:06 +00004788 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanaka619e8872011-06-02 00:09:17 +00004789 // Ignore empty aggregates.
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004790 if (TySize == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004791 return ABIArgInfo::getIgnore();
4792
Mark Lacey23630722013-10-06 01:33:34 +00004793 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004794 Offset = OrigOffset + MinABIStackAlignInBytes;
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004795 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004796 }
Akira Hatanaka511949b2011-08-01 18:09:58 +00004797
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004798 // If we have reached here, aggregates are passed directly by coercing to
4799 // another structure type. Padding is inserted if the offset of the
4800 // aggregate is unaligned.
4801 return ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00004802 getPaddingType(OrigOffset, CurrOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004803 }
4804
4805 // Treat an enum type as its underlying type.
4806 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4807 Ty = EnumTy->getDecl()->getIntegerType();
4808
Akira Hatanakaa33fd392012-01-09 19:31:25 +00004809 if (Ty->isPromotableIntegerType())
4810 return ABIArgInfo::getExtend();
4811
Akira Hatanaka7ebd9532013-10-29 18:41:15 +00004812 return ABIArgInfo::getDirect(
4813 0, 0, IsO32 ? 0 : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanaka619e8872011-06-02 00:09:17 +00004814}
4815
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004816llvm::Type*
4817MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakada54ff32012-02-09 18:49:26 +00004818 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakac359f202012-07-03 19:24:06 +00004819 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004820
Akira Hatanakada54ff32012-02-09 18:49:26 +00004821 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004822 const RecordDecl *RD = RT->getDecl();
Akira Hatanakada54ff32012-02-09 18:49:26 +00004823 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
4824 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004825
Akira Hatanakada54ff32012-02-09 18:49:26 +00004826 // N32/64 returns struct/classes in floating point registers if the
4827 // following conditions are met:
4828 // 1. The size of the struct/class is no larger than 128-bit.
4829 // 2. The struct/class has one or two fields all of which are floating
4830 // point types.
4831 // 3. The offset of the first field is zero (this follows what gcc does).
4832 //
4833 // Any other composite results are returned in integer registers.
4834 //
4835 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
4836 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
4837 for (; b != e; ++b) {
David Blaikie262bc182012-04-30 02:36:29 +00004838 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004839
Akira Hatanakada54ff32012-02-09 18:49:26 +00004840 if (!BT || !BT->isFloatingPoint())
4841 break;
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004842
David Blaikie262bc182012-04-30 02:36:29 +00004843 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakada54ff32012-02-09 18:49:26 +00004844 }
4845
4846 if (b == e)
4847 return llvm::StructType::get(getVMContext(), RTList,
4848 RD->hasAttr<PackedAttr>());
4849
4850 RTList.clear();
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004851 }
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004852 }
4853
Akira Hatanakac359f202012-07-03 19:24:06 +00004854 CoerceToIntArgs(Size, RTList);
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004855 return llvm::StructType::get(getVMContext(), RTList);
4856}
4857
Akira Hatanaka619e8872011-06-02 00:09:17 +00004858ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanakaa8536c02012-01-23 23:18:57 +00004859 uint64_t Size = getContext().getTypeSize(RetTy);
4860
4861 if (RetTy->isVoidType() || Size == 0)
Akira Hatanaka619e8872011-06-02 00:09:17 +00004862 return ABIArgInfo::getIgnore();
4863
Akira Hatanaka8aeb1472012-05-11 21:01:17 +00004864 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Mark Lacey23630722013-10-06 01:33:34 +00004865 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004866 return ABIArgInfo::getIndirect(0);
4867
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004868 if (Size <= 128) {
4869 if (RetTy->isAnyComplexType())
4870 return ABIArgInfo::getDirect();
4871
Akira Hatanakac359f202012-07-03 19:24:06 +00004872 // O32 returns integer vectors in registers.
4873 if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
4874 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4875
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00004876 if (!IsO32)
Akira Hatanakac7ecc2e2012-01-04 03:34:42 +00004877 return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
4878 }
Akira Hatanaka619e8872011-06-02 00:09:17 +00004879
4880 return ABIArgInfo::getIndirect(0);
4881 }
4882
4883 // Treat an enum type as its underlying type.
4884 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4885 RetTy = EnumTy->getDecl()->getIntegerType();
4886
4887 return (RetTy->isPromotableIntegerType() ?
4888 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4889}
4890
4891void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakacc662542012-01-12 01:10:09 +00004892 ABIArgInfo &RetInfo = FI.getReturnInfo();
4893 RetInfo = classifyReturnType(FI.getReturnType());
4894
4895 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka91338cf2012-05-11 21:56:58 +00004896 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanakacc662542012-01-12 01:10:09 +00004897
Akira Hatanaka619e8872011-06-02 00:09:17 +00004898 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
4899 it != ie; ++it)
Akira Hatanakaf0cc2082012-01-07 00:25:33 +00004900 it->info = classifyArgumentType(it->type, Offset);
Akira Hatanaka619e8872011-06-02 00:09:17 +00004901}
4902
4903llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
4904 CodeGenFunction &CGF) const {
Chris Lattner8b418682012-02-07 00:39:47 +00004905 llvm::Type *BP = CGF.Int8PtrTy;
4906 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004907
4908 CGBuilderTy &Builder = CGF.Builder;
4909 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
4910 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004911 int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004912 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
4913 llvm::Value *AddrTyped;
John McCall64aa4b32013-04-16 22:48:15 +00004914 unsigned PtrWidth = getTarget().getPointerWidth(0);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004915 llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004916
4917 if (TypeAlign > MinABIStackAlignInBytes) {
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004918 llvm::Value *AddrAsInt = CGF.Builder.CreatePtrToInt(Addr, IntTy);
4919 llvm::Value *Inc = llvm::ConstantInt::get(IntTy, TypeAlign - 1);
4920 llvm::Value *Mask = llvm::ConstantInt::get(IntTy, -TypeAlign);
4921 llvm::Value *Add = CGF.Builder.CreateAdd(AddrAsInt, Inc);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004922 llvm::Value *And = CGF.Builder.CreateAnd(Add, Mask);
4923 AddrTyped = CGF.Builder.CreateIntToPtr(And, PTy);
4924 }
4925 else
4926 AddrTyped = Builder.CreateBitCast(Addr, PTy);
4927
4928 llvm::Value *AlignedAddr = Builder.CreateBitCast(AddrTyped, BP);
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004929 TypeAlign = std::max((unsigned)TypeAlign, MinABIStackAlignInBytes);
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004930 uint64_t Offset =
4931 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, TypeAlign);
4932 llvm::Value *NextAddr =
Akira Hatanaka8f675e42012-01-23 23:59:52 +00004933 Builder.CreateGEP(AlignedAddr, llvm::ConstantInt::get(IntTy, Offset),
Akira Hatanakac35e69d2011-08-01 20:48:01 +00004934 "ap.next");
4935 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
4936
4937 return AddrTyped;
Akira Hatanaka619e8872011-06-02 00:09:17 +00004938}
4939
John McCallaeeb7012010-05-27 06:19:26 +00004940bool
4941MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4942 llvm::Value *Address) const {
4943 // This information comes from gcc's implementation, which seems to
4944 // as canonical as it gets.
4945
John McCallaeeb7012010-05-27 06:19:26 +00004946 // Everything on MIPS is 4 bytes. Double-precision FP registers
4947 // are aliased to pairs of single-precision FP registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004948 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCallaeeb7012010-05-27 06:19:26 +00004949
4950 // 0-31 are the general purpose registers, $0 - $31.
4951 // 32-63 are the floating-point registers, $f0 - $f31.
4952 // 64 and 65 are the multiply/divide registers, $hi and $lo.
4953 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattner8b418682012-02-07 00:39:47 +00004954 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCallaeeb7012010-05-27 06:19:26 +00004955
4956 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
4957 // They are one bit wide and ignored here.
4958
4959 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
4960 // (coprocessor 1 is the FP unit)
4961 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
4962 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
4963 // 176-181 are the DSP accumulator registers.
Chris Lattner8b418682012-02-07 00:39:47 +00004964 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCallaeeb7012010-05-27 06:19:26 +00004965 return false;
4966}
4967
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004968//===----------------------------------------------------------------------===//
4969// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
4970// Currently subclassed only to implement custom OpenCL C function attribute
4971// handling.
4972//===----------------------------------------------------------------------===//
4973
4974namespace {
4975
4976class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4977public:
4978 TCETargetCodeGenInfo(CodeGenTypes &CGT)
4979 : DefaultTargetCodeGenInfo(CGT) {}
4980
4981 virtual void SetTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
4982 CodeGen::CodeGenModule &M) const;
4983};
4984
4985void TCETargetCodeGenInfo::SetTargetAttributes(const Decl *D,
4986 llvm::GlobalValue *GV,
4987 CodeGen::CodeGenModule &M) const {
4988 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4989 if (!FD) return;
4990
4991 llvm::Function *F = cast<llvm::Function>(GV);
4992
David Blaikie4e4d0842012-03-11 07:00:24 +00004993 if (M.getLangOpts().OpenCL) {
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004994 if (FD->hasAttr<OpenCLKernelAttr>()) {
4995 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling72390b32012-12-20 19:27:06 +00004996 F->addFnAttr(llvm::Attribute::NoInline);
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00004997
4998 if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
4999
5000 // Convert the reqd_work_group_size() attributes to metadata.
5001 llvm::LLVMContext &Context = F->getContext();
5002 llvm::NamedMDNode *OpenCLMetadata =
5003 M.getModule().getOrInsertNamedMetadata("opencl.kernel_wg_size_info");
5004
5005 SmallVector<llvm::Value*, 5> Operands;
5006 Operands.push_back(F);
5007
Chris Lattner8b418682012-02-07 00:39:47 +00005008 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5009 llvm::APInt(32,
5010 FD->getAttr<ReqdWorkGroupSizeAttr>()->getXDim())));
5011 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5012 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005013 FD->getAttr<ReqdWorkGroupSizeAttr>()->getYDim())));
Chris Lattner8b418682012-02-07 00:39:47 +00005014 Operands.push_back(llvm::Constant::getIntegerValue(M.Int32Ty,
5015 llvm::APInt(32,
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005016 FD->getAttr<ReqdWorkGroupSizeAttr>()->getZDim())));
5017
5018 // Add a boolean constant operand for "required" (true) or "hint" (false)
5019 // for implementing the work_group_size_hint attr later. Currently
5020 // always true as the hint is not yet implemented.
Chris Lattner8b418682012-02-07 00:39:47 +00005021 Operands.push_back(llvm::ConstantInt::getTrue(Context));
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005022 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
5023 }
5024 }
5025 }
5026}
5027
5028}
John McCallaeeb7012010-05-27 06:19:26 +00005029
Tony Linthicum96319392011-12-12 21:14:55 +00005030//===----------------------------------------------------------------------===//
5031// Hexagon ABI Implementation
5032//===----------------------------------------------------------------------===//
5033
5034namespace {
5035
5036class HexagonABIInfo : public ABIInfo {
5037
5038
5039public:
5040 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5041
5042private:
5043
5044 ABIArgInfo classifyReturnType(QualType RetTy) const;
5045 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5046
5047 virtual void computeInfo(CGFunctionInfo &FI) const;
5048
5049 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5050 CodeGenFunction &CGF) const;
5051};
5052
5053class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
5054public:
5055 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
5056 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
5057
5058 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const {
5059 return 29;
5060 }
5061};
5062
5063}
5064
5065void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
5066 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
5067 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5068 it != ie; ++it)
5069 it->info = classifyArgumentType(it->type);
5070}
5071
5072ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
5073 if (!isAggregateTypeForABI(Ty)) {
5074 // Treat an enum type as its underlying type.
5075 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5076 Ty = EnumTy->getDecl()->getIntegerType();
5077
5078 return (Ty->isPromotableIntegerType() ?
5079 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5080 }
5081
5082 // Ignore empty records.
5083 if (isEmptyRecord(getContext(), Ty, true))
5084 return ABIArgInfo::getIgnore();
5085
Mark Lacey23630722013-10-06 01:33:34 +00005086 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
Timur Iskhodzhanoved23bdf2013-04-17 12:54:10 +00005087 return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum96319392011-12-12 21:14:55 +00005088
5089 uint64_t Size = getContext().getTypeSize(Ty);
5090 if (Size > 64)
5091 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5092 // Pass in the smallest viable integer type.
5093 else if (Size > 32)
5094 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5095 else if (Size > 16)
5096 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5097 else if (Size > 8)
5098 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5099 else
5100 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5101}
5102
5103ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
5104 if (RetTy->isVoidType())
5105 return ABIArgInfo::getIgnore();
5106
5107 // Large vector types should be returned via memory.
5108 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
5109 return ABIArgInfo::getIndirect(0);
5110
5111 if (!isAggregateTypeForABI(RetTy)) {
5112 // Treat an enum type as its underlying type.
5113 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5114 RetTy = EnumTy->getDecl()->getIntegerType();
5115
5116 return (RetTy->isPromotableIntegerType() ?
5117 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5118 }
5119
5120 // Structures with either a non-trivial destructor or a non-trivial
5121 // copy constructor are always indirect.
Mark Lacey23630722013-10-06 01:33:34 +00005122 if (isRecordReturnIndirect(RetTy, getCXXABI()))
Tony Linthicum96319392011-12-12 21:14:55 +00005123 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5124
5125 if (isEmptyRecord(getContext(), RetTy, true))
5126 return ABIArgInfo::getIgnore();
5127
5128 // Aggregates <= 8 bytes are returned in r0; other aggregates
5129 // are returned indirectly.
5130 uint64_t Size = getContext().getTypeSize(RetTy);
5131 if (Size <= 64) {
5132 // Return in the smallest viable integer type.
5133 if (Size <= 8)
5134 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5135 if (Size <= 16)
5136 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5137 if (Size <= 32)
5138 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5139 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
5140 }
5141
5142 return ABIArgInfo::getIndirect(0, /*ByVal=*/true);
5143}
5144
5145llvm::Value *HexagonABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
Chris Lattner8b418682012-02-07 00:39:47 +00005146 CodeGenFunction &CGF) const {
Tony Linthicum96319392011-12-12 21:14:55 +00005147 // FIXME: Need to handle alignment
Chris Lattner8b418682012-02-07 00:39:47 +00005148 llvm::Type *BPP = CGF.Int8PtrPtrTy;
Tony Linthicum96319392011-12-12 21:14:55 +00005149
5150 CGBuilderTy &Builder = CGF.Builder;
5151 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
5152 "ap");
5153 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5154 llvm::Type *PTy =
5155 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
5156 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
5157
5158 uint64_t Offset =
5159 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
5160 llvm::Value *NextAddr =
5161 Builder.CreateGEP(Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset),
5162 "ap.next");
5163 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
5164
5165 return AddrTyped;
5166}
5167
5168
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005169//===----------------------------------------------------------------------===//
5170// SPARC v9 ABI Implementation.
5171// Based on the SPARC Compliance Definition version 2.4.1.
5172//
5173// Function arguments a mapped to a nominal "parameter array" and promoted to
5174// registers depending on their type. Each argument occupies 8 or 16 bytes in
5175// the array, structs larger than 16 bytes are passed indirectly.
5176//
5177// One case requires special care:
5178//
5179// struct mixed {
5180// int i;
5181// float f;
5182// };
5183//
5184// When a struct mixed is passed by value, it only occupies 8 bytes in the
5185// parameter array, but the int is passed in an integer register, and the float
5186// is passed in a floating point register. This is represented as two arguments
5187// with the LLVM IR inreg attribute:
5188//
5189// declare void f(i32 inreg %i, float inreg %f)
5190//
5191// The code generator will only allocate 4 bytes from the parameter array for
5192// the inreg arguments. All other arguments are allocated a multiple of 8
5193// bytes.
5194//
5195namespace {
5196class SparcV9ABIInfo : public ABIInfo {
5197public:
5198 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
5199
5200private:
5201 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
5202 virtual void computeInfo(CGFunctionInfo &FI) const;
5203 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5204 CodeGenFunction &CGF) const;
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005205
5206 // Coercion type builder for structs passed in registers. The coercion type
5207 // serves two purposes:
5208 //
5209 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
5210 // in registers.
5211 // 2. Expose aligned floating point elements as first-level elements, so the
5212 // code generator knows to pass them in floating point registers.
5213 //
5214 // We also compute the InReg flag which indicates that the struct contains
5215 // aligned 32-bit floats.
5216 //
5217 struct CoerceBuilder {
5218 llvm::LLVMContext &Context;
5219 const llvm::DataLayout &DL;
5220 SmallVector<llvm::Type*, 8> Elems;
5221 uint64_t Size;
5222 bool InReg;
5223
5224 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
5225 : Context(c), DL(dl), Size(0), InReg(false) {}
5226
5227 // Pad Elems with integers until Size is ToSize.
5228 void pad(uint64_t ToSize) {
5229 assert(ToSize >= Size && "Cannot remove elements");
5230 if (ToSize == Size)
5231 return;
5232
5233 // Finish the current 64-bit word.
5234 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
5235 if (Aligned > Size && Aligned <= ToSize) {
5236 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
5237 Size = Aligned;
5238 }
5239
5240 // Add whole 64-bit words.
5241 while (Size + 64 <= ToSize) {
5242 Elems.push_back(llvm::Type::getInt64Ty(Context));
5243 Size += 64;
5244 }
5245
5246 // Final in-word padding.
5247 if (Size < ToSize) {
5248 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
5249 Size = ToSize;
5250 }
5251 }
5252
5253 // Add a floating point element at Offset.
5254 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
5255 // Unaligned floats are treated as integers.
5256 if (Offset % Bits)
5257 return;
5258 // The InReg flag is only required if there are any floats < 64 bits.
5259 if (Bits < 64)
5260 InReg = true;
5261 pad(Offset);
5262 Elems.push_back(Ty);
5263 Size = Offset + Bits;
5264 }
5265
5266 // Add a struct type to the coercion type, starting at Offset (in bits).
5267 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
5268 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
5269 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
5270 llvm::Type *ElemTy = StrTy->getElementType(i);
5271 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
5272 switch (ElemTy->getTypeID()) {
5273 case llvm::Type::StructTyID:
5274 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
5275 break;
5276 case llvm::Type::FloatTyID:
5277 addFloat(ElemOffset, ElemTy, 32);
5278 break;
5279 case llvm::Type::DoubleTyID:
5280 addFloat(ElemOffset, ElemTy, 64);
5281 break;
5282 case llvm::Type::FP128TyID:
5283 addFloat(ElemOffset, ElemTy, 128);
5284 break;
5285 case llvm::Type::PointerTyID:
5286 if (ElemOffset % 64 == 0) {
5287 pad(ElemOffset);
5288 Elems.push_back(ElemTy);
5289 Size += 64;
5290 }
5291 break;
5292 default:
5293 break;
5294 }
5295 }
5296 }
5297
5298 // Check if Ty is a usable substitute for the coercion type.
5299 bool isUsableType(llvm::StructType *Ty) const {
5300 if (Ty->getNumElements() != Elems.size())
5301 return false;
5302 for (unsigned i = 0, e = Elems.size(); i != e; ++i)
5303 if (Elems[i] != Ty->getElementType(i))
5304 return false;
5305 return true;
5306 }
5307
5308 // Get the coercion type as a literal struct type.
5309 llvm::Type *getType() const {
5310 if (Elems.size() == 1)
5311 return Elems.front();
5312 else
5313 return llvm::StructType::get(Context, Elems);
5314 }
5315 };
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005316};
5317} // end anonymous namespace
5318
5319ABIArgInfo
5320SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
5321 if (Ty->isVoidType())
5322 return ABIArgInfo::getIgnore();
5323
5324 uint64_t Size = getContext().getTypeSize(Ty);
5325
5326 // Anything too big to fit in registers is passed with an explicit indirect
5327 // pointer / sret pointer.
5328 if (Size > SizeLimit)
5329 return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
5330
5331 // Treat an enum type as its underlying type.
5332 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5333 Ty = EnumTy->getDecl()->getIntegerType();
5334
5335 // Integer types smaller than a register are extended.
5336 if (Size < 64 && Ty->isIntegerType())
5337 return ABIArgInfo::getExtend();
5338
5339 // Other non-aggregates go in registers.
5340 if (!isAggregateTypeForABI(Ty))
5341 return ABIArgInfo::getDirect();
5342
5343 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesenfc782fb2013-05-28 04:57:37 +00005344 // Build a coercion type from the LLVM struct type.
5345 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
5346 if (!StrTy)
5347 return ABIArgInfo::getDirect();
5348
5349 CoerceBuilder CB(getVMContext(), getDataLayout());
5350 CB.addStruct(0, StrTy);
5351 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
5352
5353 // Try to use the original type for coercion.
5354 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
5355
5356 if (CB.InReg)
5357 return ABIArgInfo::getDirectInReg(CoerceTy);
5358 else
5359 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005360}
5361
5362llvm::Value *SparcV9ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5363 CodeGenFunction &CGF) const {
Jakob Stoklund Olesena4b56d32013-06-05 03:00:18 +00005364 ABIArgInfo AI = classifyType(Ty, 16 * 8);
5365 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5366 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5367 AI.setCoerceToType(ArgTy);
5368
5369 llvm::Type *BPP = CGF.Int8PtrPtrTy;
5370 CGBuilderTy &Builder = CGF.Builder;
5371 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap");
5372 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
5373 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
5374 llvm::Value *ArgAddr;
5375 unsigned Stride;
5376
5377 switch (AI.getKind()) {
5378 case ABIArgInfo::Expand:
5379 llvm_unreachable("Unsupported ABI kind for va_arg");
5380
5381 case ABIArgInfo::Extend:
5382 Stride = 8;
5383 ArgAddr = Builder
5384 .CreateConstGEP1_32(Addr, 8 - getDataLayout().getTypeAllocSize(ArgTy),
5385 "extend");
5386 break;
5387
5388 case ABIArgInfo::Direct:
5389 Stride = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5390 ArgAddr = Addr;
5391 break;
5392
5393 case ABIArgInfo::Indirect:
5394 Stride = 8;
5395 ArgAddr = Builder.CreateBitCast(Addr,
5396 llvm::PointerType::getUnqual(ArgPtrTy),
5397 "indirect");
5398 ArgAddr = Builder.CreateLoad(ArgAddr, "indirect.arg");
5399 break;
5400
5401 case ABIArgInfo::Ignore:
5402 return llvm::UndefValue::get(ArgPtrTy);
5403 }
5404
5405 // Update VAList.
5406 Addr = Builder.CreateConstGEP1_32(Addr, Stride, "ap.next");
5407 Builder.CreateStore(Addr, VAListAddrAsBPP);
5408
5409 return Builder.CreatePointerCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005410}
5411
5412void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
5413 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
5414 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
5415 it != ie; ++it)
5416 it->info = classifyType(it->type, 16 * 8);
5417}
5418
5419namespace {
5420class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
5421public:
5422 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
5423 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
5424};
5425} // end anonymous namespace
5426
5427
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005428//===----------------------------------------------------------------------===//
5429// Xcore ABI Implementation
5430//===----------------------------------------------------------------------===//
5431namespace {
Robert Lytton276c2892013-08-19 09:46:39 +00005432class XCoreABIInfo : public DefaultABIInfo {
5433public:
5434 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
5435 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5436 CodeGenFunction &CGF) const;
5437};
5438
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005439class XcoreTargetCodeGenInfo : public TargetCodeGenInfo {
5440public:
5441 XcoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton276c2892013-08-19 09:46:39 +00005442 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005443};
Robert Lytton645e6fd2013-10-11 10:29:34 +00005444} // End anonymous namespace.
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005445
Robert Lytton276c2892013-08-19 09:46:39 +00005446llvm::Value *XCoreABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
5447 CodeGenFunction &CGF) const {
Robert Lytton276c2892013-08-19 09:46:39 +00005448 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton276c2892013-08-19 09:46:39 +00005449
Robert Lytton645e6fd2013-10-11 10:29:34 +00005450 // Get the VAList.
Robert Lytton276c2892013-08-19 09:46:39 +00005451 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr,
5452 CGF.Int8PtrPtrTy);
5453 llvm::Value *AP = Builder.CreateLoad(VAListAddrAsBPP);
Robert Lytton276c2892013-08-19 09:46:39 +00005454
Robert Lytton645e6fd2013-10-11 10:29:34 +00005455 // Handle the argument.
5456 ABIArgInfo AI = classifyArgumentType(Ty);
5457 llvm::Type *ArgTy = CGT.ConvertType(Ty);
5458 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
5459 AI.setCoerceToType(ArgTy);
Robert Lytton276c2892013-08-19 09:46:39 +00005460 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
Robert Lytton645e6fd2013-10-11 10:29:34 +00005461 llvm::Value *Val;
Andy Gibbsed9967e2013-10-14 07:02:04 +00005462 uint64_t ArgSize = 0;
Robert Lytton276c2892013-08-19 09:46:39 +00005463 switch (AI.getKind()) {
Robert Lytton276c2892013-08-19 09:46:39 +00005464 case ABIArgInfo::Expand:
5465 llvm_unreachable("Unsupported ABI kind for va_arg");
5466 case ABIArgInfo::Ignore:
Robert Lytton645e6fd2013-10-11 10:29:34 +00005467 Val = llvm::UndefValue::get(ArgPtrTy);
5468 ArgSize = 0;
5469 break;
Robert Lytton276c2892013-08-19 09:46:39 +00005470 case ABIArgInfo::Extend:
5471 case ABIArgInfo::Direct:
Robert Lytton645e6fd2013-10-11 10:29:34 +00005472 Val = Builder.CreatePointerCast(AP, ArgPtrTy);
5473 ArgSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
5474 if (ArgSize < 4)
5475 ArgSize = 4;
5476 break;
Robert Lytton276c2892013-08-19 09:46:39 +00005477 case ABIArgInfo::Indirect:
5478 llvm::Value *ArgAddr;
5479 ArgAddr = Builder.CreateBitCast(AP, llvm::PointerType::getUnqual(ArgPtrTy));
5480 ArgAddr = Builder.CreateLoad(ArgAddr);
Robert Lytton645e6fd2013-10-11 10:29:34 +00005481 Val = Builder.CreatePointerCast(ArgAddr, ArgPtrTy);
5482 ArgSize = 4;
5483 break;
Robert Lytton276c2892013-08-19 09:46:39 +00005484 }
Robert Lytton645e6fd2013-10-11 10:29:34 +00005485
5486 // Increment the VAList.
5487 if (ArgSize) {
5488 llvm::Value *APN = Builder.CreateConstGEP1_32(AP, ArgSize);
5489 Builder.CreateStore(APN, VAListAddrAsBPP);
5490 }
5491 return Val;
Robert Lytton276c2892013-08-19 09:46:39 +00005492}
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005493
5494//===----------------------------------------------------------------------===//
5495// Driver code
5496//===----------------------------------------------------------------------===//
5497
Chris Lattnerea044322010-07-29 02:01:43 +00005498const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005499 if (TheTargetCodeGenInfo)
5500 return *TheTargetCodeGenInfo;
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005501
John McCall64aa4b32013-04-16 22:48:15 +00005502 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar1752ee42009-08-24 09:10:05 +00005503 switch (Triple.getArch()) {
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005504 default:
Chris Lattnerea044322010-07-29 02:01:43 +00005505 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005506
Derek Schuff9ed63f82012-09-06 17:37:28 +00005507 case llvm::Triple::le32:
5508 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCallaeeb7012010-05-27 06:19:26 +00005509 case llvm::Triple::mips:
5510 case llvm::Triple::mipsel:
Akira Hatanaka550ed202013-10-29 19:00:35 +00005511 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true,
5512 getTarget()));
Akira Hatanaka8c6dfbe2011-09-20 18:30:57 +00005513 case llvm::Triple::mips64:
5514 case llvm::Triple::mips64el:
Akira Hatanaka550ed202013-10-29 19:00:35 +00005515 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false,
5516 getTarget()));
Tim Northoverc264e162013-01-31 12:13:10 +00005517 case llvm::Triple::aarch64:
5518 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types));
5519
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005520 case llvm::Triple::arm:
5521 case llvm::Triple::thumb:
Sandeep Patel34c1af82011-04-05 00:23:47 +00005522 {
5523 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
John McCall64aa4b32013-04-16 22:48:15 +00005524 if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Sandeep Patel34c1af82011-04-05 00:23:47 +00005525 Kind = ARMABIInfo::APCS;
David Tweedb16abb12012-10-25 13:33:01 +00005526 else if (CodeGenOpts.FloatABI == "hard" ||
John McCall64aa4b32013-04-16 22:48:15 +00005527 (CodeGenOpts.FloatABI != "soft" &&
5528 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel34c1af82011-04-05 00:23:47 +00005529 Kind = ARMABIInfo::AAPCS_VFP;
5530
Derek Schuff263366f2012-10-16 22:30:41 +00005531 switch (Triple.getOS()) {
Eli Bendersky441d9f72012-12-04 18:38:10 +00005532 case llvm::Triple::NaCl:
Derek Schuff263366f2012-10-16 22:30:41 +00005533 return *(TheTargetCodeGenInfo =
5534 new NaClARMTargetCodeGenInfo(Types, Kind));
5535 default:
5536 return *(TheTargetCodeGenInfo =
5537 new ARMTargetCodeGenInfo(Types, Kind));
5538 }
Sandeep Patel34c1af82011-04-05 00:23:47 +00005539 }
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005540
John McCallec853ba2010-03-11 00:10:12 +00005541 case llvm::Triple::ppc:
Chris Lattnerea044322010-07-29 02:01:43 +00005542 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divacky0fbc4b92012-05-09 18:22:46 +00005543 case llvm::Triple::ppc64:
Bill Schmidt2fc107f2012-10-03 19:18:57 +00005544 if (Triple.isOSBinFormatELF())
5545 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
5546 else
5547 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Bill Schmidtea7fb0c2013-07-26 01:36:11 +00005548 case llvm::Triple::ppc64le:
5549 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
5550 return *(TheTargetCodeGenInfo = new PPC64_SVR4_TargetCodeGenInfo(Types));
John McCallec853ba2010-03-11 00:10:12 +00005551
Peter Collingbourneedb66f32012-05-20 23:28:41 +00005552 case llvm::Triple::nvptx:
5553 case llvm::Triple::nvptx64:
Justin Holewinski2c585b92012-05-24 17:43:12 +00005554 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinski0259c3a2011-04-22 11:10:38 +00005555
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005556 case llvm::Triple::msp430:
Chris Lattnerea044322010-07-29 02:01:43 +00005557 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbar34d91fd2009-09-12 00:59:49 +00005558
Ulrich Weigandb8409212013-05-06 16:26:41 +00005559 case llvm::Triple::systemz:
5560 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
5561
Peter Collingbourne2f7aa992011-10-13 16:24:41 +00005562 case llvm::Triple::tce:
5563 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
5564
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005565 case llvm::Triple::x86: {
John McCallb8b52972013-06-18 02:46:29 +00005566 bool IsDarwinVectorABI = Triple.isOSDarwin();
5567 bool IsSmallStructInRegABI =
5568 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
5569 bool IsWin32FloatStructABI = (Triple.getOS() == llvm::Triple::Win32);
Daniel Dunbardb57a4c2011-04-19 21:43:27 +00005570
John McCallb8b52972013-06-18 02:46:29 +00005571 if (Triple.getOS() == llvm::Triple::Win32) {
Eli Friedman55fc7e22012-01-25 22:46:34 +00005572 return *(TheTargetCodeGenInfo =
Reid Kleckner3190ca92013-05-08 13:44:39 +00005573 new WinX86_32TargetCodeGenInfo(Types,
John McCallb8b52972013-06-18 02:46:29 +00005574 IsDarwinVectorABI, IsSmallStructInRegABI,
5575 IsWin32FloatStructABI,
Reid Kleckner3190ca92013-05-08 13:44:39 +00005576 CodeGenOpts.NumRegisterParameters));
John McCallb8b52972013-06-18 02:46:29 +00005577 } else {
Anton Korobeynikov82d0a412010-01-10 12:58:08 +00005578 return *(TheTargetCodeGenInfo =
John McCallb8b52972013-06-18 02:46:29 +00005579 new X86_32TargetCodeGenInfo(Types,
5580 IsDarwinVectorABI, IsSmallStructInRegABI,
5581 IsWin32FloatStructABI,
Rafael Espindolab48280b2012-07-31 02:44:24 +00005582 CodeGenOpts.NumRegisterParameters));
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005583 }
Eli Friedmanc3e0fb42011-07-08 23:31:17 +00005584 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005585
Eli Friedmanee1ad992011-12-02 00:11:43 +00005586 case llvm::Triple::x86_64: {
John McCall64aa4b32013-04-16 22:48:15 +00005587 bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
Eli Friedmanee1ad992011-12-02 00:11:43 +00005588
Chris Lattnerf13721d2010-08-31 16:44:54 +00005589 switch (Triple.getOS()) {
5590 case llvm::Triple::Win32:
NAKAMURA Takumi0aa20572011-02-17 08:51:38 +00005591 case llvm::Triple::MinGW32:
Chris Lattnerf13721d2010-08-31 16:44:54 +00005592 case llvm::Triple::Cygwin:
5593 return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
Eli Bendersky441d9f72012-12-04 18:38:10 +00005594 case llvm::Triple::NaCl:
John McCall64aa4b32013-04-16 22:48:15 +00005595 return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
5596 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005597 default:
Eli Friedmanee1ad992011-12-02 00:11:43 +00005598 return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
5599 HasAVX));
Chris Lattnerf13721d2010-08-31 16:44:54 +00005600 }
Daniel Dunbar2c0843f2009-08-24 08:52:16 +00005601 }
Tony Linthicum96319392011-12-12 21:14:55 +00005602 case llvm::Triple::hexagon:
5603 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Jakob Stoklund Olesen107196c2013-05-27 21:48:25 +00005604 case llvm::Triple::sparcv9:
5605 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton5f15f4d2013-08-13 09:43:10 +00005606 case llvm::Triple::xcore:
5607 return *(TheTargetCodeGenInfo = new XcoreTargetCodeGenInfo(Types));
5608
Eli Friedmanee1ad992011-12-02 00:11:43 +00005609 }
Anton Korobeynikovc4a59eb2009-06-05 22:08:42 +00005610}