blob: 0d7d9a7de4473a4e7febc6b85d02ee98413d67c2 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000022#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000023#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000024#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000025#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000028#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000030
Anton Korobeynikov244360d2009-06-05 22:08:42 +000031using namespace clang;
32using namespace CodeGen;
33
John McCall943fae92010-05-27 06:19:26 +000034static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
35 llvm::Value *Array,
36 llvm::Value *Value,
37 unsigned FirstIndex,
38 unsigned LastIndex) {
39 // Alternatively, we could emit this as a loop in the source.
40 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000041 llvm::Value *Cell =
42 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000043 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000044 }
45}
46
John McCalla1dee5302010-08-22 10:59:02 +000047static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000048 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000049 T->isMemberFunctionPointerType();
50}
51
John McCall7f416cc2015-09-08 08:05:57 +000052ABIArgInfo
53ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
54 llvm::Type *Padding) const {
55 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
56 ByRef, Realign, Padding);
57}
58
59ABIArgInfo
60ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
61 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
62 /*ByRef*/ false, Realign);
63}
64
Charles Davisc7d5c942015-09-17 20:55:33 +000065Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
66 QualType Ty) const {
67 return Address::invalid();
68}
69
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000070ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000071
John McCall12f23522016-04-04 18:33:08 +000072/// Does the given lowering require more than the given number of
73/// registers when expanded?
74///
75/// This is intended to be the basis of a reasonable basic implementation
76/// of should{Pass,Return}IndirectlyForSwift.
77///
78/// For most targets, a limit of four total registers is reasonable; this
79/// limits the amount of code required in order to move around the value
80/// in case it wasn't produced immediately prior to the call by the caller
81/// (or wasn't produced in exactly the right registers) or isn't used
82/// immediately within the callee. But some targets may need to further
83/// limit the register count due to an inability to support that many
84/// return registers.
85static bool occupiesMoreThan(CodeGenTypes &cgt,
86 ArrayRef<llvm::Type*> scalarTypes,
87 unsigned maxAllRegisters) {
88 unsigned intCount = 0, fpCount = 0;
89 for (llvm::Type *type : scalarTypes) {
90 if (type->isPointerTy()) {
91 intCount++;
92 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
93 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
94 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
95 } else {
96 assert(type->isVectorTy() || type->isFloatingPointTy());
97 fpCount++;
98 }
99 }
100
101 return (intCount + fpCount > maxAllRegisters);
102}
103
104bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
105 llvm::Type *eltTy,
106 unsigned numElts) const {
107 // The default implementation of this assumes that the target guarantees
108 // 128-bit SIMD support but nothing more.
109 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
110}
111
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000112static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000113 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000114 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
115 if (!RD)
116 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000117 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000118}
119
120static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000121 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000122 const RecordType *RT = T->getAs<RecordType>();
123 if (!RT)
124 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000125 return getRecordArgABI(RT, CXXABI);
126}
127
Reid Klecknerb1be6832014-11-15 01:41:41 +0000128/// Pass transparent unions as if they were the type of the first element. Sema
129/// should ensure that all elements of the union have the same "machine type".
130static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
131 if (const RecordType *UT = Ty->getAsUnionType()) {
132 const RecordDecl *UD = UT->getDecl();
133 if (UD->hasAttr<TransparentUnionAttr>()) {
134 assert(!UD->field_empty() && "sema created an empty transparent union");
135 return UD->field_begin()->getType();
136 }
137 }
138 return Ty;
139}
140
Mark Lacey3825e832013-10-06 01:33:34 +0000141CGCXXABI &ABIInfo::getCXXABI() const {
142 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000143}
144
Chris Lattner2b037972010-07-29 02:01:43 +0000145ASTContext &ABIInfo::getContext() const {
146 return CGT.getContext();
147}
148
149llvm::LLVMContext &ABIInfo::getVMContext() const {
150 return CGT.getLLVMContext();
151}
152
Micah Villmowdd31ca12012-10-08 16:25:52 +0000153const llvm::DataLayout &ABIInfo::getDataLayout() const {
154 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000155}
156
John McCallc8e01702013-04-16 22:48:15 +0000157const TargetInfo &ABIInfo::getTarget() const {
158 return CGT.getTarget();
159}
Chris Lattner2b037972010-07-29 02:01:43 +0000160
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000161bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
162
Reid Klecknere9f6a712014-10-31 17:10:41 +0000163bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
164 return false;
165}
166
167bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
168 uint64_t Members) const {
169 return false;
170}
171
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000172bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
173 return false;
174}
175
Yaron Kerencdae9412016-01-29 19:38:18 +0000176LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000177 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000178 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000179 switch (TheKind) {
180 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000181 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000182 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000183 Ty->print(OS);
184 else
185 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000186 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000187 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000188 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000189 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000190 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000191 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000192 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000193 case InAlloca:
194 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
195 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000196 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000197 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000198 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000199 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000200 break;
201 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000202 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000203 break;
John McCallf26e73d2016-03-11 04:30:43 +0000204 case CoerceAndExpand:
205 OS << "CoerceAndExpand Type=";
206 getCoerceAndExpandType()->print(OS);
207 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000208 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000209 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000210}
211
Petar Jovanovic402257b2015-12-04 00:26:47 +0000212// Dynamically round a pointer up to a multiple of the given alignment.
213static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
214 llvm::Value *Ptr,
215 CharUnits Align) {
216 llvm::Value *PtrAsInt = Ptr;
217 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
218 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
219 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
220 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
221 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
222 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
223 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
224 Ptr->getType(),
225 Ptr->getName() + ".aligned");
226 return PtrAsInt;
227}
228
John McCall7f416cc2015-09-08 08:05:57 +0000229/// Emit va_arg for a platform using the common void* representation,
230/// where arguments are simply emitted in an array of slots on the stack.
231///
232/// This version implements the core direct-value passing rules.
233///
234/// \param SlotSize - The size and alignment of a stack slot.
235/// Each argument will be allocated to a multiple of this number of
236/// slots, and all the slots will be aligned to this value.
237/// \param AllowHigherAlign - The slot alignment is not a cap;
238/// an argument type with an alignment greater than the slot size
239/// will be emitted on a higher-alignment address, potentially
240/// leaving one or more empty slots behind as padding. If this
241/// is false, the returned address might be less-aligned than
242/// DirectAlign.
243static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
244 Address VAListAddr,
245 llvm::Type *DirectTy,
246 CharUnits DirectSize,
247 CharUnits DirectAlign,
248 CharUnits SlotSize,
249 bool AllowHigherAlign) {
250 // Cast the element type to i8* if necessary. Some platforms define
251 // va_list as a struct containing an i8* instead of just an i8*.
252 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
253 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
254
255 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
256
257 // If the CC aligns values higher than the slot size, do so if needed.
258 Address Addr = Address::invalid();
259 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000260 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
261 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000262 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000263 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000264 }
265
266 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000267 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000268 llvm::Value *NextPtr =
269 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
270 "argp.next");
271 CGF.Builder.CreateStore(NextPtr, VAListAddr);
272
273 // If the argument is smaller than a slot, and this is a big-endian
274 // target, the argument will be right-adjusted in its slot.
275 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
276 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
277 }
278
279 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
280 return Addr;
281}
282
283/// Emit va_arg for a platform using the common void* representation,
284/// where arguments are simply emitted in an array of slots on the stack.
285///
286/// \param IsIndirect - Values of this type are passed indirectly.
287/// \param ValueInfo - The size and alignment of this type, generally
288/// computed with getContext().getTypeInfoInChars(ValueTy).
289/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
290/// Each argument will be allocated to a multiple of this number of
291/// slots, and all the slots will be aligned to this value.
292/// \param AllowHigherAlign - The slot alignment is not a cap;
293/// an argument type with an alignment greater than the slot size
294/// will be emitted on a higher-alignment address, potentially
295/// leaving one or more empty slots behind as padding.
296static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
297 QualType ValueTy, bool IsIndirect,
298 std::pair<CharUnits, CharUnits> ValueInfo,
299 CharUnits SlotSizeAndAlign,
300 bool AllowHigherAlign) {
301 // The size and alignment of the value that was passed directly.
302 CharUnits DirectSize, DirectAlign;
303 if (IsIndirect) {
304 DirectSize = CGF.getPointerSize();
305 DirectAlign = CGF.getPointerAlign();
306 } else {
307 DirectSize = ValueInfo.first;
308 DirectAlign = ValueInfo.second;
309 }
310
311 // Cast the address we've calculated to the right type.
312 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
313 if (IsIndirect)
314 DirectTy = DirectTy->getPointerTo(0);
315
316 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
317 DirectSize, DirectAlign,
318 SlotSizeAndAlign,
319 AllowHigherAlign);
320
321 if (IsIndirect) {
322 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
323 }
324
325 return Addr;
326
327}
328
329static Address emitMergePHI(CodeGenFunction &CGF,
330 Address Addr1, llvm::BasicBlock *Block1,
331 Address Addr2, llvm::BasicBlock *Block2,
332 const llvm::Twine &Name = "") {
333 assert(Addr1.getType() == Addr2.getType());
334 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
335 PHI->addIncoming(Addr1.getPointer(), Block1);
336 PHI->addIncoming(Addr2.getPointer(), Block2);
337 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
338 return Address(PHI, Align);
339}
340
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000341TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
342
John McCall3480ef22011-08-30 01:42:09 +0000343// If someone can figure out a general rule for this, that would be great.
344// It's probably just doomed to be platform-dependent, though.
345unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
346 // Verified for:
347 // x86-64 FreeBSD, Linux, Darwin
348 // x86-32 FreeBSD, Linux, Darwin
349 // PowerPC Linux, Darwin
350 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000351 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000352 return 32;
353}
354
John McCalla729c622012-02-17 03:33:10 +0000355bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
356 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000357 // The following conventions are known to require this to be false:
358 // x86_stdcall
359 // MIPS
360 // For everything else, we just prefer false unless we opt out.
361 return false;
362}
363
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000364void
365TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
366 llvm::SmallString<24> &Opt) const {
367 // This assumes the user is passing a library name like "rt" instead of a
368 // filename like "librt.a/so", and that they don't care whether it's static or
369 // dynamic.
370 Opt = "-l";
371 Opt += Lib;
372}
373
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000374static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000375
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000376/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000377/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000378static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
379 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000380 if (FD->isUnnamedBitfield())
381 return true;
382
383 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000384
Eli Friedman0b3f2012011-11-18 03:47:20 +0000385 // Constant arrays of empty records count as empty, strip them off.
386 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000387 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000388 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
389 if (AT->getSize() == 0)
390 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000391 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000392 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000393
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000394 const RecordType *RT = FT->getAs<RecordType>();
395 if (!RT)
396 return false;
397
398 // C++ record fields are never empty, at least in the Itanium ABI.
399 //
400 // FIXME: We should use a predicate for whether this behavior is true in the
401 // current ABI.
402 if (isa<CXXRecordDecl>(RT->getDecl()))
403 return false;
404
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000405 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000406}
407
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000408/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000409/// fields. Note that a structure with a flexible array member is not
410/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000411static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000412 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000413 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000414 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000415 const RecordDecl *RD = RT->getDecl();
416 if (RD->hasFlexibleArrayMember())
417 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000418
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000419 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000420 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000421 for (const auto &I : CXXRD->bases())
422 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000423 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000424
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000425 for (const auto *I : RD->fields())
426 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000427 return false;
428 return true;
429}
430
431/// isSingleElementStruct - Determine if a structure is a "single
432/// element struct", i.e. it has exactly one non-empty field or
433/// exactly one field which is itself a single element
434/// struct. Structures with flexible array members are never
435/// considered single element structs.
436///
437/// \return The field declaration for the single non-empty field, if
438/// it exists.
439static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000440 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000441 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000442 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000443
444 const RecordDecl *RD = RT->getDecl();
445 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000446 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000447
Craig Topper8a13c412014-05-21 05:09:00 +0000448 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000449
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000450 // If this is a C++ record, check the bases first.
451 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000452 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000453 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000454 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000455 continue;
456
457 // If we already found an element then this isn't a single-element struct.
458 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000459 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000460
461 // If this is non-empty and not a single element struct, the composite
462 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000463 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000464 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000465 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000466 }
467 }
468
469 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000470 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471 QualType FT = FD->getType();
472
473 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000474 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000475 continue;
476
477 // If we already found an element then this isn't a single-element
478 // struct.
479 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000480 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000481
482 // Treat single element arrays as the element.
483 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
484 if (AT->getSize().getZExtValue() != 1)
485 break;
486 FT = AT->getElementType();
487 }
488
John McCalla1dee5302010-08-22 10:59:02 +0000489 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000490 Found = FT.getTypePtr();
491 } else {
492 Found = isSingleElementStruct(FT, Context);
493 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000494 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000495 }
496 }
497
Eli Friedmanee945342011-11-18 01:25:50 +0000498 // We don't consider a struct a single-element struct if it has
499 // padding beyond the element type.
500 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000501 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000502
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000503 return Found;
504}
505
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000506namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000507Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
508 const ABIArgInfo &AI) {
509 // This default implementation defers to the llvm backend's va_arg
510 // instruction. It can handle only passing arguments directly
511 // (typically only handled in the backend for primitive types), or
512 // aggregates passed indirectly by pointer (NOTE: if the "byval"
513 // flag has ABI impact in the callee, this implementation cannot
514 // work.)
515
516 // Only a few cases are covered here at the moment -- those needed
517 // by the default abi.
518 llvm::Value *Val;
519
520 if (AI.isIndirect()) {
521 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000522 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000523 assert(
524 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000525 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000526
527 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
528 CharUnits TyAlignForABI = TyInfo.second;
529
530 llvm::Type *BaseTy =
531 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
532 llvm::Value *Addr =
533 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
534 return Address(Addr, TyAlignForABI);
535 } else {
536 assert((AI.isDirect() || AI.isExtend()) &&
537 "Unexpected ArgInfo Kind in generic VAArg emitter!");
538
539 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000540 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000541 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000542 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000543 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000544 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000545 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000546 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000547
548 Address Temp = CGF.CreateMemTemp(Ty, "varet");
549 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
550 CGF.Builder.CreateStore(Val, Temp);
551 return Temp;
552 }
553}
554
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000555/// DefaultABIInfo - The default implementation for ABI specific
556/// details. This implementation provides information which results in
557/// self-consistent and sensible LLVM IR generation, but does not
558/// conform to any particular ABI.
559class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000560public:
561 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000562
Chris Lattner458b2aa2010-07-29 02:16:43 +0000563 ABIArgInfo classifyReturnType(QualType RetTy) const;
564 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000565
Craig Topper4f12f102014-03-12 06:41:41 +0000566 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000567 if (!getCXXABI().classifyReturnType(FI))
568 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000569 for (auto &I : FI.arguments())
570 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000571 }
572
John McCall7f416cc2015-09-08 08:05:57 +0000573 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000574 QualType Ty) const override {
575 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
576 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000577};
578
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000579class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
580public:
Chris Lattner2b037972010-07-29 02:01:43 +0000581 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
582 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000583};
584
Chris Lattner458b2aa2010-07-29 02:16:43 +0000585ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000586 Ty = useFirstFieldIfTransparentUnion(Ty);
587
588 if (isAggregateTypeForABI(Ty)) {
589 // Records with non-trivial destructors/copy-constructors should not be
590 // passed by value.
591 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000592 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000593
John McCall7f416cc2015-09-08 08:05:57 +0000594 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000595 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000596
Chris Lattner9723d6c2010-03-11 18:19:55 +0000597 // Treat an enum type as its underlying type.
598 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
599 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000600
Chris Lattner9723d6c2010-03-11 18:19:55 +0000601 return (Ty->isPromotableIntegerType() ?
602 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000603}
604
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000605ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
606 if (RetTy->isVoidType())
607 return ABIArgInfo::getIgnore();
608
609 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000610 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000611
612 // Treat an enum type as its underlying type.
613 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
614 RetTy = EnumTy->getDecl()->getIntegerType();
615
616 return (RetTy->isPromotableIntegerType() ?
617 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
618}
619
Derek Schuff09338a22012-09-06 17:37:28 +0000620//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000621// WebAssembly ABI Implementation
622//
623// This is a very simple ABI that relies a lot on DefaultABIInfo.
624//===----------------------------------------------------------------------===//
625
626class WebAssemblyABIInfo final : public DefaultABIInfo {
627public:
628 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
629 : DefaultABIInfo(CGT) {}
630
631private:
632 ABIArgInfo classifyReturnType(QualType RetTy) const;
633 ABIArgInfo classifyArgumentType(QualType Ty) const;
634
635 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000636 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000637 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000638 void computeInfo(CGFunctionInfo &FI) const override {
639 if (!getCXXABI().classifyReturnType(FI))
640 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
641 for (auto &Arg : FI.arguments())
642 Arg.info = classifyArgumentType(Arg.type);
643 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000644
645 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
646 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000647};
648
649class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
650public:
651 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
652 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
653};
654
655/// \brief Classify argument of given type \p Ty.
656ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
657 Ty = useFirstFieldIfTransparentUnion(Ty);
658
659 if (isAggregateTypeForABI(Ty)) {
660 // Records with non-trivial destructors/copy-constructors should not be
661 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000662 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000663 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000664 // Ignore empty structs/unions.
665 if (isEmptyRecord(getContext(), Ty, true))
666 return ABIArgInfo::getIgnore();
667 // Lower single-element structs to just pass a regular value. TODO: We
668 // could do reasonable-size multiple-element structs too, using getExpand(),
669 // though watch out for things like bitfields.
670 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
671 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000672 }
673
674 // Otherwise just do the default thing.
675 return DefaultABIInfo::classifyArgumentType(Ty);
676}
677
678ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
679 if (isAggregateTypeForABI(RetTy)) {
680 // Records with non-trivial destructors/copy-constructors should not be
681 // returned by value.
682 if (!getRecordArgABI(RetTy, getCXXABI())) {
683 // Ignore empty structs/unions.
684 if (isEmptyRecord(getContext(), RetTy, true))
685 return ABIArgInfo::getIgnore();
686 // Lower single-element structs to just return a regular value. TODO: We
687 // could do reasonable-size multiple-element structs too, using
688 // ABIArgInfo::getDirect().
689 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
690 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
691 }
692 }
693
694 // Otherwise just do the default thing.
695 return DefaultABIInfo::classifyReturnType(RetTy);
696}
697
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000698Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
699 QualType Ty) const {
700 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
701 getContext().getTypeInfoInChars(Ty),
702 CharUnits::fromQuantity(4),
703 /*AllowHigherAlign=*/ true);
704}
705
Dan Gohmanc2853072015-09-03 22:51:53 +0000706//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000707// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000708//
709// This is a simplified version of the x86_32 ABI. Arguments and return values
710// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000711//===----------------------------------------------------------------------===//
712
713class PNaClABIInfo : public ABIInfo {
714 public:
715 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
716
717 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000718 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000719
Craig Topper4f12f102014-03-12 06:41:41 +0000720 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000721 Address EmitVAArg(CodeGenFunction &CGF,
722 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000723};
724
725class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
726 public:
727 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
728 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
729};
730
731void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000732 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000733 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
734
Reid Kleckner40ca9132014-05-13 22:05:45 +0000735 for (auto &I : FI.arguments())
736 I.info = classifyArgumentType(I.type);
737}
Derek Schuff09338a22012-09-06 17:37:28 +0000738
John McCall7f416cc2015-09-08 08:05:57 +0000739Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
740 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000741 // The PNaCL ABI is a bit odd, in that varargs don't use normal
742 // function classification. Structs get passed directly for varargs
743 // functions, through a rewriting transform in
744 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
745 // this target to actually support a va_arg instructions with an
746 // aggregate type, unlike other targets.
747 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000748}
749
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000750/// \brief Classify argument of given type \p Ty.
751ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000752 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000753 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000754 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
755 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000756 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
757 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000758 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000759 } else if (Ty->isFloatingType()) {
760 // Floating-point types don't go inreg.
761 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000762 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000763
764 return (Ty->isPromotableIntegerType() ?
765 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000766}
767
768ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
769 if (RetTy->isVoidType())
770 return ABIArgInfo::getIgnore();
771
Eli Benderskye20dad62013-04-04 22:49:35 +0000772 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000773 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000774 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000775
776 // Treat an enum type as its underlying type.
777 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
778 RetTy = EnumTy->getDecl()->getIntegerType();
779
780 return (RetTy->isPromotableIntegerType() ?
781 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
782}
783
Chad Rosier651c1832013-03-25 21:00:27 +0000784/// IsX86_MMXType - Return true if this is an MMX type.
785bool IsX86_MMXType(llvm::Type *IRType) {
786 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000787 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
788 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
789 IRType->getScalarSizeInBits() != 64;
790}
791
Jay Foad7c57be32011-07-11 09:56:20 +0000792static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000793 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000794 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000795 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
796 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
797 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000798 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000799 }
800
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000801 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000802 }
803
804 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000805 return Ty;
806}
807
Reid Kleckner80944df2014-10-31 22:00:51 +0000808/// Returns true if this type can be passed in SSE registers with the
809/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
810static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
811 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
812 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
813 return true;
814 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
815 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
816 // registers specially.
817 unsigned VecSize = Context.getTypeSize(VT);
818 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
819 return true;
820 }
821 return false;
822}
823
824/// Returns true if this aggregate is small enough to be passed in SSE registers
825/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
826static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
827 return NumMembers <= 4;
828}
829
Chris Lattner0cf24192010-06-28 20:05:43 +0000830//===----------------------------------------------------------------------===//
831// X86-32 ABI Implementation
832//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000833
Reid Kleckner661f35b2014-01-18 01:12:41 +0000834/// \brief Similar to llvm::CCState, but for Clang.
835struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000836 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000837
838 unsigned CC;
839 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000840 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000841};
842
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000843/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000844class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000845 enum Class {
846 Integer,
847 Float
848 };
849
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000850 static const unsigned MinABIStackAlignInBytes = 4;
851
David Chisnallde3a0692009-08-17 23:08:21 +0000852 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000853 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000854 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000855 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000856 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000857 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000858
859 static bool isRegisterSize(unsigned Size) {
860 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
861 }
862
Reid Kleckner80944df2014-10-31 22:00:51 +0000863 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
864 // FIXME: Assumes vectorcall is in use.
865 return isX86VectorTypeForVectorCall(getContext(), Ty);
866 }
867
868 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
869 uint64_t NumMembers) const override {
870 // FIXME: Assumes vectorcall is in use.
871 return isX86VectorCallAggregateSmallEnough(NumMembers);
872 }
873
Reid Kleckner40ca9132014-05-13 22:05:45 +0000874 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000875
Daniel Dunbar557893d2010-04-21 19:10:51 +0000876 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
877 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000878 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
879
John McCall7f416cc2015-09-08 08:05:57 +0000880 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000881
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000882 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000883 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000884
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000885 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000886 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000887 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000888 /// \brief Updates the number of available free registers, returns
889 /// true if any registers were allocated.
890 bool updateFreeRegs(QualType Ty, CCState &State) const;
891
892 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
893 bool &NeedsPadding) const;
894 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000895
Reid Kleckner04046052016-05-02 17:41:07 +0000896 bool canExpandIndirectArgument(QualType Ty) const;
897
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000898 /// \brief Rewrite the function info so that all memory arguments use
899 /// inalloca.
900 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
901
902 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000903 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000904 QualType Type) const;
905
Rafael Espindola75419dc2012-07-23 23:30:29 +0000906public:
907
Craig Topper4f12f102014-03-12 06:41:41 +0000908 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000909 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
910 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000911
Michael Kupersteindc745202015-10-19 07:52:25 +0000912 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
913 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000914 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000915 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000916 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
917 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000918 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000919 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000920 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000921
922 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
923 ArrayRef<llvm::Type*> scalars,
924 bool asReturnValue) const override {
925 // LLVM's x86-32 lowering currently only assigns up to three
926 // integer registers and three fp registers. Oddly, it'll use up to
927 // four vector registers for vectors, but those can overlap with the
928 // scalar registers.
929 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
930 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000931};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000932
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000933class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
934public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000935 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
936 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000937 unsigned NumRegisterParameters, bool SoftFloatABI)
938 : TargetCodeGenInfo(new X86_32ABIInfo(
939 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
940 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000941
John McCall1fe2a8c2013-06-18 02:46:29 +0000942 static bool isStructReturnInRegABI(
943 const llvm::Triple &Triple, const CodeGenOptions &Opts);
944
Eric Christopher162c91c2015-06-05 22:03:00 +0000945 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000946 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000947
Craig Topper4f12f102014-03-12 06:41:41 +0000948 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000949 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000950 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000951 return 4;
952 }
953
954 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000955 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000956
Jay Foad7c57be32011-07-11 09:56:20 +0000957 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000958 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000959 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000960 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
961 }
962
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000963 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
964 std::string &Constraints,
965 std::vector<llvm::Type *> &ResultRegTypes,
966 std::vector<llvm::Type *> &ResultTruncRegTypes,
967 std::vector<LValue> &ResultRegDests,
968 std::string &AsmString,
969 unsigned NumOutputs) const override;
970
Craig Topper4f12f102014-03-12 06:41:41 +0000971 llvm::Constant *
972 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000973 unsigned Sig = (0xeb << 0) | // jmp rel8
974 (0x06 << 8) | // .+0x08
975 ('F' << 16) |
976 ('T' << 24);
977 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
978 }
John McCall01391782016-02-05 21:37:38 +0000979
980 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
981 return "movl\t%ebp, %ebp"
982 "\t\t## marker for objc_retainAutoreleaseReturnValue";
983 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000984};
985
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000986}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000987
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000988/// Rewrite input constraint references after adding some output constraints.
989/// In the case where there is one output and one input and we add one output,
990/// we need to replace all operand references greater than or equal to 1:
991/// mov $0, $1
992/// mov eax, $1
993/// The result will be:
994/// mov $0, $2
995/// mov eax, $2
996static void rewriteInputConstraintReferences(unsigned FirstIn,
997 unsigned NumNewOuts,
998 std::string &AsmString) {
999 std::string Buf;
1000 llvm::raw_string_ostream OS(Buf);
1001 size_t Pos = 0;
1002 while (Pos < AsmString.size()) {
1003 size_t DollarStart = AsmString.find('$', Pos);
1004 if (DollarStart == std::string::npos)
1005 DollarStart = AsmString.size();
1006 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1007 if (DollarEnd == std::string::npos)
1008 DollarEnd = AsmString.size();
1009 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1010 Pos = DollarEnd;
1011 size_t NumDollars = DollarEnd - DollarStart;
1012 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1013 // We have an operand reference.
1014 size_t DigitStart = Pos;
1015 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1016 if (DigitEnd == std::string::npos)
1017 DigitEnd = AsmString.size();
1018 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1019 unsigned OperandIndex;
1020 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1021 if (OperandIndex >= FirstIn)
1022 OperandIndex += NumNewOuts;
1023 OS << OperandIndex;
1024 } else {
1025 OS << OperandStr;
1026 }
1027 Pos = DigitEnd;
1028 }
1029 }
1030 AsmString = std::move(OS.str());
1031}
1032
1033/// Add output constraints for EAX:EDX because they are return registers.
1034void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1035 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1036 std::vector<llvm::Type *> &ResultRegTypes,
1037 std::vector<llvm::Type *> &ResultTruncRegTypes,
1038 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1039 unsigned NumOutputs) const {
1040 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1041
1042 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1043 // larger.
1044 if (!Constraints.empty())
1045 Constraints += ',';
1046 if (RetWidth <= 32) {
1047 Constraints += "={eax}";
1048 ResultRegTypes.push_back(CGF.Int32Ty);
1049 } else {
1050 // Use the 'A' constraint for EAX:EDX.
1051 Constraints += "=A";
1052 ResultRegTypes.push_back(CGF.Int64Ty);
1053 }
1054
1055 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1056 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1057 ResultTruncRegTypes.push_back(CoerceTy);
1058
1059 // Coerce the integer by bitcasting the return slot pointer.
1060 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1061 CoerceTy->getPointerTo()));
1062 ResultRegDests.push_back(ReturnSlot);
1063
1064 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1065}
1066
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001067/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001068/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001069bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1070 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001071 uint64_t Size = Context.getTypeSize(Ty);
1072
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001073 // For i386, type must be register sized.
1074 // For the MCU ABI, it only needs to be <= 8-byte
1075 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1076 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001077
1078 if (Ty->isVectorType()) {
1079 // 64- and 128- bit vectors inside structures are not returned in
1080 // registers.
1081 if (Size == 64 || Size == 128)
1082 return false;
1083
1084 return true;
1085 }
1086
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001087 // If this is a builtin, pointer, enum, complex type, member pointer, or
1088 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001089 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001090 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001091 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001092 return true;
1093
1094 // Arrays are treated like records.
1095 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001096 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001097
1098 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001099 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001100 if (!RT) return false;
1101
Anders Carlsson40446e82010-01-27 03:25:19 +00001102 // FIXME: Traverse bases here too.
1103
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001104 // Structure types are passed in register if all fields would be
1105 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001106 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001107 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001108 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001109 continue;
1110
1111 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001112 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001113 return false;
1114 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001115 return true;
1116}
1117
Reid Kleckner04046052016-05-02 17:41:07 +00001118static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1119 // Treat complex types as the element type.
1120 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1121 Ty = CTy->getElementType();
1122
1123 // Check for a type which we know has a simple scalar argument-passing
1124 // convention without any padding. (We're specifically looking for 32
1125 // and 64-bit integer and integer-equivalents, float, and double.)
1126 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1127 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1128 return false;
1129
1130 uint64_t Size = Context.getTypeSize(Ty);
1131 return Size == 32 || Size == 64;
1132}
1133
1134/// Test whether an argument type which is to be passed indirectly (on the
1135/// stack) would have the equivalent layout if it was expanded into separate
1136/// arguments. If so, we prefer to do the latter to avoid inhibiting
1137/// optimizations.
1138bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1139 // We can only expand structure types.
1140 const RecordType *RT = Ty->getAs<RecordType>();
1141 if (!RT)
1142 return false;
1143 const RecordDecl *RD = RT->getDecl();
1144 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1145 if (!IsWin32StructABI ) {
1146 // On non-Windows, we have to conservatively match our old bitcode
1147 // prototypes in order to be ABI-compatible at the bitcode level.
1148 if (!CXXRD->isCLike())
1149 return false;
1150 } else {
1151 // Don't do this for dynamic classes.
1152 if (CXXRD->isDynamicClass())
1153 return false;
1154 // Don't do this if there are any non-empty bases.
1155 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1156 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1157 return false;
1158 }
1159 }
1160 }
1161
1162 uint64_t Size = 0;
1163
1164 for (const auto *FD : RD->fields()) {
1165 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1166 // argument is smaller than 32-bits, expanding the struct will create
1167 // alignment padding.
1168 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1169 return false;
1170
1171 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1172 // how to expand them yet, and the predicate for telling if a bitfield still
1173 // counts as "basic" is more complicated than what we were doing previously.
1174 if (FD->isBitField())
1175 return false;
1176
1177 Size += getContext().getTypeSize(FD->getType());
1178 }
1179
1180 // We can do this if there was no alignment padding.
1181 return Size == getContext().getTypeSize(Ty);
1182}
1183
John McCall7f416cc2015-09-08 08:05:57 +00001184ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001185 // If the return value is indirect, then the hidden argument is consuming one
1186 // integer register.
1187 if (State.FreeRegs) {
1188 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001189 if (!IsMCUABI)
1190 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001191 }
John McCall7f416cc2015-09-08 08:05:57 +00001192 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001193}
1194
Eric Christopher7565e0d2015-05-29 23:09:49 +00001195ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1196 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001197 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001198 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001199
Reid Kleckner80944df2014-10-31 22:00:51 +00001200 const Type *Base = nullptr;
1201 uint64_t NumElts = 0;
1202 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1203 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1204 // The LLVM struct type for such an aggregate should lower properly.
1205 return ABIArgInfo::getDirect();
1206 }
1207
Chris Lattner458b2aa2010-07-29 02:16:43 +00001208 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001209 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001210 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001211 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001212
1213 // 128-bit vectors are a special case; they are returned in
1214 // registers and we need to make sure to pick a type the LLVM
1215 // backend will like.
1216 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001217 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001218 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001219
1220 // Always return in register if it fits in a general purpose
1221 // register, or if it is 64 bits and has a single element.
1222 if ((Size == 8 || Size == 16 || Size == 32) ||
1223 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001224 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001225 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001226
John McCall7f416cc2015-09-08 08:05:57 +00001227 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001228 }
1229
1230 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001231 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001232
John McCalla1dee5302010-08-22 10:59:02 +00001233 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001234 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001235 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001236 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001237 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001238 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001239
David Chisnallde3a0692009-08-17 23:08:21 +00001240 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001241 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001242 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001243
Denis Zobnin380b2242016-02-11 11:26:03 +00001244 // Ignore empty structs/unions.
1245 if (isEmptyRecord(getContext(), RetTy, true))
1246 return ABIArgInfo::getIgnore();
1247
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001248 // Small structures which are register sized are generally returned
1249 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001250 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001251 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001252
1253 // As a special-case, if the struct is a "single-element" struct, and
1254 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001255 // floating-point register. (MSVC does not apply this special case.)
1256 // We apply a similar transformation for pointer types to improve the
1257 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001258 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001259 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001260 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001261 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1262
1263 // FIXME: We should be able to narrow this integer in cases with dead
1264 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001265 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001266 }
1267
John McCall7f416cc2015-09-08 08:05:57 +00001268 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001269 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001270
Chris Lattner458b2aa2010-07-29 02:16:43 +00001271 // Treat an enum type as its underlying type.
1272 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1273 RetTy = EnumTy->getDecl()->getIntegerType();
1274
1275 return (RetTy->isPromotableIntegerType() ?
1276 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001277}
1278
Eli Friedman7919bea2012-06-05 19:40:46 +00001279static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1280 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1281}
1282
Daniel Dunbared23de32010-09-16 20:42:00 +00001283static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1284 const RecordType *RT = Ty->getAs<RecordType>();
1285 if (!RT)
1286 return 0;
1287 const RecordDecl *RD = RT->getDecl();
1288
1289 // If this is a C++ record, check the bases first.
1290 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001291 for (const auto &I : CXXRD->bases())
1292 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001293 return false;
1294
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001295 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001296 QualType FT = i->getType();
1297
Eli Friedman7919bea2012-06-05 19:40:46 +00001298 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001299 return true;
1300
1301 if (isRecordWithSSEVectorType(Context, FT))
1302 return true;
1303 }
1304
1305 return false;
1306}
1307
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001308unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1309 unsigned Align) const {
1310 // Otherwise, if the alignment is less than or equal to the minimum ABI
1311 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001312 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001313 return 0; // Use default alignment.
1314
1315 // On non-Darwin, the stack type alignment is always 4.
1316 if (!IsDarwinVectorABI) {
1317 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001318 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001319 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001320
Daniel Dunbared23de32010-09-16 20:42:00 +00001321 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001322 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1323 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001324 return 16;
1325
1326 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001327}
1328
Rafael Espindola703c47f2012-10-19 05:04:37 +00001329ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001330 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001331 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001332 if (State.FreeRegs) {
1333 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001334 if (!IsMCUABI)
1335 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001336 }
John McCall7f416cc2015-09-08 08:05:57 +00001337 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001338 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001339
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001340 // Compute the byval alignment.
1341 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1342 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1343 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001344 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001345
1346 // If the stack alignment is less than the type alignment, realign the
1347 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001348 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001349 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1350 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001351}
1352
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001353X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1354 const Type *T = isSingleElementStruct(Ty, getContext());
1355 if (!T)
1356 T = Ty.getTypePtr();
1357
1358 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1359 BuiltinType::Kind K = BT->getKind();
1360 if (K == BuiltinType::Float || K == BuiltinType::Double)
1361 return Float;
1362 }
1363 return Integer;
1364}
1365
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001366bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001367 if (!IsSoftFloatABI) {
1368 Class C = classify(Ty);
1369 if (C == Float)
1370 return false;
1371 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001372
Rafael Espindola077dd592012-10-24 01:58:58 +00001373 unsigned Size = getContext().getTypeSize(Ty);
1374 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001375
1376 if (SizeInRegs == 0)
1377 return false;
1378
Michael Kuperstein68901882015-10-25 08:18:20 +00001379 if (!IsMCUABI) {
1380 if (SizeInRegs > State.FreeRegs) {
1381 State.FreeRegs = 0;
1382 return false;
1383 }
1384 } else {
1385 // The MCU psABI allows passing parameters in-reg even if there are
1386 // earlier parameters that are passed on the stack. Also,
1387 // it does not allow passing >8-byte structs in-register,
1388 // even if there are 3 free registers available.
1389 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1390 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001391 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001392
Reid Kleckner661f35b2014-01-18 01:12:41 +00001393 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001394 return true;
1395}
1396
1397bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1398 bool &InReg,
1399 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001400 // On Windows, aggregates other than HFAs are never passed in registers, and
1401 // they do not consume register slots. Homogenous floating-point aggregates
1402 // (HFAs) have already been dealt with at this point.
1403 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1404 return false;
1405
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001406 NeedsPadding = false;
1407 InReg = !IsMCUABI;
1408
1409 if (!updateFreeRegs(Ty, State))
1410 return false;
1411
1412 if (IsMCUABI)
1413 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001414
Reid Kleckner80944df2014-10-31 22:00:51 +00001415 if (State.CC == llvm::CallingConv::X86_FastCall ||
1416 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001417 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001418 NeedsPadding = true;
1419
Rafael Espindola077dd592012-10-24 01:58:58 +00001420 return false;
1421 }
1422
Rafael Espindola703c47f2012-10-19 05:04:37 +00001423 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001424}
1425
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001426bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1427 if (!updateFreeRegs(Ty, State))
1428 return false;
1429
1430 if (IsMCUABI)
1431 return false;
1432
1433 if (State.CC == llvm::CallingConv::X86_FastCall ||
1434 State.CC == llvm::CallingConv::X86_VectorCall) {
1435 if (getContext().getTypeSize(Ty) > 32)
1436 return false;
1437
1438 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1439 Ty->isReferenceType());
1440 }
1441
1442 return true;
1443}
1444
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001445ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1446 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001447 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001448
Reid Klecknerb1be6832014-11-15 01:41:41 +00001449 Ty = useFirstFieldIfTransparentUnion(Ty);
1450
Reid Kleckner80944df2014-10-31 22:00:51 +00001451 // Check with the C++ ABI first.
1452 const RecordType *RT = Ty->getAs<RecordType>();
1453 if (RT) {
1454 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1455 if (RAA == CGCXXABI::RAA_Indirect) {
1456 return getIndirectResult(Ty, false, State);
1457 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1458 // The field index doesn't matter, we'll fix it up later.
1459 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1460 }
1461 }
1462
1463 // vectorcall adds the concept of a homogenous vector aggregate, similar
1464 // to other targets.
1465 const Type *Base = nullptr;
1466 uint64_t NumElts = 0;
1467 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1468 isHomogeneousAggregate(Ty, Base, NumElts)) {
1469 if (State.FreeSSERegs >= NumElts) {
1470 State.FreeSSERegs -= NumElts;
1471 if (Ty->isBuiltinType() || Ty->isVectorType())
1472 return ABIArgInfo::getDirect();
1473 return ABIArgInfo::getExpand();
1474 }
1475 return getIndirectResult(Ty, /*ByVal=*/false, State);
1476 }
1477
1478 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001479 // Structures with flexible arrays are always indirect.
1480 // FIXME: This should not be byval!
1481 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1482 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001483
Reid Kleckner04046052016-05-02 17:41:07 +00001484 // Ignore empty structs/unions on non-Windows.
1485 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001486 return ABIArgInfo::getIgnore();
1487
Rafael Espindolafad28de2012-10-24 01:59:00 +00001488 llvm::LLVMContext &LLVMContext = getVMContext();
1489 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001490 bool NeedsPadding = false;
1491 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001492 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001493 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001494 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001495 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001496 if (InReg)
1497 return ABIArgInfo::getDirectInReg(Result);
1498 else
1499 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001500 }
Craig Topper8a13c412014-05-21 05:09:00 +00001501 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001502
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001503 // Expand small (<= 128-bit) record types when we know that the stack layout
1504 // of those arguments will match the struct. This is important because the
1505 // LLVM backend isn't smart enough to remove byval, which inhibits many
1506 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001507 // Don't do this for the MCU if there are still free integer registers
1508 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001509 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1510 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001511 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001512 State.CC == llvm::CallingConv::X86_FastCall ||
1513 State.CC == llvm::CallingConv::X86_VectorCall,
1514 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001515
Reid Kleckner661f35b2014-01-18 01:12:41 +00001516 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001517 }
1518
Chris Lattnerd774ae92010-08-26 20:05:13 +00001519 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001520 // On Darwin, some vectors are passed in memory, we handle this by passing
1521 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001522 if (IsDarwinVectorABI) {
1523 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001524 if ((Size == 8 || Size == 16 || Size == 32) ||
1525 (Size == 64 && VT->getNumElements() == 1))
1526 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1527 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001528 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001529
Chad Rosier651c1832013-03-25 21:00:27 +00001530 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1531 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001532
Chris Lattnerd774ae92010-08-26 20:05:13 +00001533 return ABIArgInfo::getDirect();
1534 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001535
1536
Chris Lattner458b2aa2010-07-29 02:16:43 +00001537 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1538 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001539
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001540 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001541
1542 if (Ty->isPromotableIntegerType()) {
1543 if (InReg)
1544 return ABIArgInfo::getExtendInReg();
1545 return ABIArgInfo::getExtend();
1546 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001547
Rafael Espindola703c47f2012-10-19 05:04:37 +00001548 if (InReg)
1549 return ABIArgInfo::getDirectInReg();
1550 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001551}
1552
Rafael Espindolaa6472962012-07-24 00:01:07 +00001553void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001554 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001555 if (IsMCUABI)
1556 State.FreeRegs = 3;
1557 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001558 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001559 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1560 State.FreeRegs = 2;
1561 State.FreeSSERegs = 6;
1562 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001563 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001564 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001565 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001566
Reid Kleckner677539d2014-07-10 01:58:55 +00001567 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001568 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001569 } else if (FI.getReturnInfo().isIndirect()) {
1570 // The C++ ABI is not aware of register usage, so we have to check if the
1571 // return value was sret and put it in a register ourselves if appropriate.
1572 if (State.FreeRegs) {
1573 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001574 if (!IsMCUABI)
1575 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001576 }
1577 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001578
Peter Collingbournef7706832014-12-12 23:41:25 +00001579 // The chain argument effectively gives us another free register.
1580 if (FI.isChainCall())
1581 ++State.FreeRegs;
1582
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001583 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001584 for (auto &I : FI.arguments()) {
1585 I.info = classifyArgumentType(I.type, State);
1586 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001587 }
1588
1589 // If we needed to use inalloca for any argument, do a second pass and rewrite
1590 // all the memory arguments to use inalloca.
1591 if (UsedInAlloca)
1592 rewriteWithInAlloca(FI);
1593}
1594
1595void
1596X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001597 CharUnits &StackOffset, ABIArgInfo &Info,
1598 QualType Type) const {
1599 // Arguments are always 4-byte-aligned.
1600 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1601
1602 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001603 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1604 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001605 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001606
John McCall7f416cc2015-09-08 08:05:57 +00001607 // Insert padding bytes to respect alignment.
1608 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001609 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001610 if (StackOffset != FieldEnd) {
1611 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001612 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001613 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001614 FrameFields.push_back(Ty);
1615 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001616}
1617
Reid Kleckner852361d2014-07-26 00:12:26 +00001618static bool isArgInAlloca(const ABIArgInfo &Info) {
1619 // Leave ignored and inreg arguments alone.
1620 switch (Info.getKind()) {
1621 case ABIArgInfo::InAlloca:
1622 return true;
1623 case ABIArgInfo::Indirect:
1624 assert(Info.getIndirectByVal());
1625 return true;
1626 case ABIArgInfo::Ignore:
1627 return false;
1628 case ABIArgInfo::Direct:
1629 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001630 if (Info.getInReg())
1631 return false;
1632 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001633 case ABIArgInfo::Expand:
1634 case ABIArgInfo::CoerceAndExpand:
1635 // These are aggregate types which are never passed in registers when
1636 // inalloca is involved.
1637 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001638 }
1639 llvm_unreachable("invalid enum");
1640}
1641
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001642void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1643 assert(IsWin32StructABI && "inalloca only supported on win32");
1644
1645 // Build a packed struct type for all of the arguments in memory.
1646 SmallVector<llvm::Type *, 6> FrameFields;
1647
John McCall7f416cc2015-09-08 08:05:57 +00001648 // The stack alignment is always 4.
1649 CharUnits StackAlign = CharUnits::fromQuantity(4);
1650
1651 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001652 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1653
1654 // Put 'this' into the struct before 'sret', if necessary.
1655 bool IsThisCall =
1656 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1657 ABIArgInfo &Ret = FI.getReturnInfo();
1658 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1659 isArgInAlloca(I->info)) {
1660 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1661 ++I;
1662 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001663
1664 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001665 if (Ret.isIndirect() && !Ret.getInReg()) {
1666 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1667 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001668 // On Windows, the hidden sret parameter is always returned in eax.
1669 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001670 }
1671
1672 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001673 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001674 ++I;
1675
1676 // Put arguments passed in memory into the struct.
1677 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001678 if (isArgInAlloca(I->info))
1679 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001680 }
1681
1682 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001683 /*isPacked=*/true),
1684 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001685}
1686
John McCall7f416cc2015-09-08 08:05:57 +00001687Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1688 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001689
John McCall7f416cc2015-09-08 08:05:57 +00001690 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001691
John McCall7f416cc2015-09-08 08:05:57 +00001692 // x86-32 changes the alignment of certain arguments on the stack.
1693 //
1694 // Just messing with TypeInfo like this works because we never pass
1695 // anything indirectly.
1696 TypeInfo.second = CharUnits::fromQuantity(
1697 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001698
John McCall7f416cc2015-09-08 08:05:57 +00001699 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1700 TypeInfo, CharUnits::fromQuantity(4),
1701 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001702}
1703
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001704bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1705 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1706 assert(Triple.getArch() == llvm::Triple::x86);
1707
1708 switch (Opts.getStructReturnConvention()) {
1709 case CodeGenOptions::SRCK_Default:
1710 break;
1711 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1712 return false;
1713 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1714 return true;
1715 }
1716
Michael Kupersteind749f232015-10-27 07:46:22 +00001717 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001718 return true;
1719
1720 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001721 case llvm::Triple::DragonFly:
1722 case llvm::Triple::FreeBSD:
1723 case llvm::Triple::OpenBSD:
1724 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001725 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001726 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001727 default:
1728 return false;
1729 }
1730}
1731
Eric Christopher162c91c2015-06-05 22:03:00 +00001732void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001733 llvm::GlobalValue *GV,
1734 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001735 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001736 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1737 // Get the LLVM function.
1738 llvm::Function *Fn = cast<llvm::Function>(GV);
1739
1740 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001741 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001742 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001743 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1744 llvm::AttributeSet::get(CGM.getLLVMContext(),
1745 llvm::AttributeSet::FunctionIndex,
1746 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001747 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001748 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1749 llvm::Function *Fn = cast<llvm::Function>(GV);
1750 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1751 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001752 }
1753}
1754
John McCallbeec5a02010-03-06 00:35:14 +00001755bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1756 CodeGen::CodeGenFunction &CGF,
1757 llvm::Value *Address) const {
1758 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001759
Chris Lattnerece04092012-02-07 00:39:47 +00001760 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001761
John McCallbeec5a02010-03-06 00:35:14 +00001762 // 0-7 are the eight integer registers; the order is different
1763 // on Darwin (for EH), but the range is the same.
1764 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001765 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001766
John McCallc8e01702013-04-16 22:48:15 +00001767 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001768 // 12-16 are st(0..4). Not sure why we stop at 4.
1769 // These have size 16, which is sizeof(long double) on
1770 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001771 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001772 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001773
John McCallbeec5a02010-03-06 00:35:14 +00001774 } else {
1775 // 9 is %eflags, which doesn't get a size on Darwin for some
1776 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001777 Builder.CreateAlignedStore(
1778 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1779 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001780
1781 // 11-16 are st(0..5). Not sure why we stop at 5.
1782 // These have size 12, which is sizeof(long double) on
1783 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001784 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001785 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1786 }
John McCallbeec5a02010-03-06 00:35:14 +00001787
1788 return false;
1789}
1790
Chris Lattner0cf24192010-06-28 20:05:43 +00001791//===----------------------------------------------------------------------===//
1792// X86-64 ABI Implementation
1793//===----------------------------------------------------------------------===//
1794
1795
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001796namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001797/// The AVX ABI level for X86 targets.
1798enum class X86AVXABILevel {
1799 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001800 AVX,
1801 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001802};
1803
1804/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1805static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1806 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001807 case X86AVXABILevel::AVX512:
1808 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001809 case X86AVXABILevel::AVX:
1810 return 256;
1811 case X86AVXABILevel::None:
1812 return 128;
1813 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001814 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001815}
1816
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001817/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001818class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001819 enum Class {
1820 Integer = 0,
1821 SSE,
1822 SSEUp,
1823 X87,
1824 X87Up,
1825 ComplexX87,
1826 NoClass,
1827 Memory
1828 };
1829
1830 /// merge - Implement the X86_64 ABI merging algorithm.
1831 ///
1832 /// Merge an accumulating classification \arg Accum with a field
1833 /// classification \arg Field.
1834 ///
1835 /// \param Accum - The accumulating classification. This should
1836 /// always be either NoClass or the result of a previous merge
1837 /// call. In addition, this should never be Memory (the caller
1838 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001839 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001840
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001841 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1842 ///
1843 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1844 /// final MEMORY or SSE classes when necessary.
1845 ///
1846 /// \param AggregateSize - The size of the current aggregate in
1847 /// the classification process.
1848 ///
1849 /// \param Lo - The classification for the parts of the type
1850 /// residing in the low word of the containing object.
1851 ///
1852 /// \param Hi - The classification for the parts of the type
1853 /// residing in the higher words of the containing object.
1854 ///
1855 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1856
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001857 /// classify - Determine the x86_64 register classes in which the
1858 /// given type T should be passed.
1859 ///
1860 /// \param Lo - The classification for the parts of the type
1861 /// residing in the low word of the containing object.
1862 ///
1863 /// \param Hi - The classification for the parts of the type
1864 /// residing in the high word of the containing object.
1865 ///
1866 /// \param OffsetBase - The bit offset of this type in the
1867 /// containing object. Some parameters are classified different
1868 /// depending on whether they straddle an eightbyte boundary.
1869 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001870 /// \param isNamedArg - Whether the argument in question is a "named"
1871 /// argument, as used in AMD64-ABI 3.5.7.
1872 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001873 /// If a word is unused its result will be NoClass; if a type should
1874 /// be passed in Memory then at least the classification of \arg Lo
1875 /// will be Memory.
1876 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001877 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001878 ///
1879 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1880 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001881 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1882 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001883
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001884 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001885 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1886 unsigned IROffset, QualType SourceTy,
1887 unsigned SourceOffset) const;
1888 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1889 unsigned IROffset, QualType SourceTy,
1890 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001891
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001892 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001893 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001894 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001895
1896 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001897 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001898 ///
1899 /// \param freeIntRegs - The number of free integer registers remaining
1900 /// available.
1901 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001902
Chris Lattner458b2aa2010-07-29 02:16:43 +00001903 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001904
Bill Wendling5cd41c42010-10-18 03:41:31 +00001905 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001906 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001907 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001908 unsigned &neededSSE,
1909 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001910
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001911 bool IsIllegalVectorType(QualType Ty) const;
1912
John McCalle0fda732011-04-21 01:20:55 +00001913 /// The 0.98 ABI revision clarified a lot of ambiguities,
1914 /// unfortunately in ways that were not always consistent with
1915 /// certain previous compilers. In particular, platforms which
1916 /// required strict binary compatibility with older versions of GCC
1917 /// may need to exempt themselves.
1918 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001919 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001920 }
1921
David Majnemere2ae2282016-03-04 05:26:16 +00001922 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1923 // compilers require us to classify it as INTEGER.
1924 bool classifyIntegerMMXAsSSE() const {
1925 const llvm::Triple &Triple = getTarget().getTriple();
1926 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1927 return false;
1928 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1929 return false;
1930 return true;
1931 }
1932
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001933 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001934 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1935 // 64-bit hardware.
1936 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001937
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001938public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001939 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001940 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001941 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001942 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001943
John McCalla729c622012-02-17 03:33:10 +00001944 bool isPassedUsingAVXType(QualType type) const {
1945 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001946 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001947 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1948 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001949 if (info.isDirect()) {
1950 llvm::Type *ty = info.getCoerceToType();
1951 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1952 return (vectorTy->getBitWidth() > 128);
1953 }
1954 return false;
1955 }
1956
Craig Topper4f12f102014-03-12 06:41:41 +00001957 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001958
John McCall7f416cc2015-09-08 08:05:57 +00001959 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1960 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001961 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1962 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001963
1964 bool has64BitPointers() const {
1965 return Has64BitPointers;
1966 }
John McCall12f23522016-04-04 18:33:08 +00001967
1968 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1969 ArrayRef<llvm::Type*> scalars,
1970 bool asReturnValue) const override {
1971 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
1972 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001973};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001974
Chris Lattner04dc9572010-08-31 16:44:54 +00001975/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001976class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001977public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001978 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1979 : ABIInfo(CGT),
1980 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001981
Craig Topper4f12f102014-03-12 06:41:41 +00001982 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001983
John McCall7f416cc2015-09-08 08:05:57 +00001984 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1985 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001986
1987 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1988 // FIXME: Assumes vectorcall is in use.
1989 return isX86VectorTypeForVectorCall(getContext(), Ty);
1990 }
1991
1992 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1993 uint64_t NumMembers) const override {
1994 // FIXME: Assumes vectorcall is in use.
1995 return isX86VectorCallAggregateSmallEnough(NumMembers);
1996 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001997
1998private:
1999 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2000 bool IsReturnType) const;
2001
2002 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002003};
2004
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002005class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2006public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002007 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002008 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002009
John McCalla729c622012-02-17 03:33:10 +00002010 const X86_64ABIInfo &getABIInfo() const {
2011 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2012 }
2013
Craig Topper4f12f102014-03-12 06:41:41 +00002014 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002015 return 7;
2016 }
2017
2018 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002019 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002020 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002021
John McCall943fae92010-05-27 06:19:26 +00002022 // 0-15 are the 16 integer registers.
2023 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002024 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002025 return false;
2026 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002027
Jay Foad7c57be32011-07-11 09:56:20 +00002028 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002029 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002030 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002031 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2032 }
2033
John McCalla729c622012-02-17 03:33:10 +00002034 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002035 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002036 // The default CC on x86-64 sets %al to the number of SSA
2037 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002038 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002039 // that when AVX types are involved: the ABI explicitly states it is
2040 // undefined, and it doesn't work in practice because of how the ABI
2041 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002042 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002043 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002044 for (CallArgList::const_iterator
2045 it = args.begin(), ie = args.end(); it != ie; ++it) {
2046 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2047 HasAVXType = true;
2048 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002049 }
2050 }
John McCalla729c622012-02-17 03:33:10 +00002051
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002052 if (!HasAVXType)
2053 return true;
2054 }
John McCallcbc038a2011-09-21 08:08:30 +00002055
John McCalla729c622012-02-17 03:33:10 +00002056 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002057 }
2058
Craig Topper4f12f102014-03-12 06:41:41 +00002059 llvm::Constant *
2060 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002061 unsigned Sig;
2062 if (getABIInfo().has64BitPointers())
2063 Sig = (0xeb << 0) | // jmp rel8
2064 (0x0a << 8) | // .+0x0c
2065 ('F' << 16) |
2066 ('T' << 24);
2067 else
2068 Sig = (0xeb << 0) | // jmp rel8
2069 (0x06 << 8) | // .+0x08
2070 ('F' << 16) |
2071 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002072 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2073 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002074
2075 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2076 CodeGen::CodeGenModule &CGM) const override {
2077 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2078 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2079 llvm::Function *Fn = cast<llvm::Function>(GV);
2080 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2081 }
2082 }
2083 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002084};
2085
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002086class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2087public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002088 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2089 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002090
2091 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002092 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002093 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002094 // If the argument contains a space, enclose it in quotes.
2095 if (Lib.find(" ") != StringRef::npos)
2096 Opt += "\"" + Lib.str() + "\"";
2097 else
2098 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002099 }
2100};
2101
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002102static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002103 // If the argument does not end in .lib, automatically add the suffix.
2104 // If the argument contains a space, enclose it in quotes.
2105 // This matches the behavior of MSVC.
2106 bool Quote = (Lib.find(" ") != StringRef::npos);
2107 std::string ArgStr = Quote ? "\"" : "";
2108 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002109 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002110 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002111 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002112 return ArgStr;
2113}
2114
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002115class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2116public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002117 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002118 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2119 unsigned NumRegisterParameters)
2120 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002121 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002122
Eric Christopher162c91c2015-06-05 22:03:00 +00002123 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002124 CodeGen::CodeGenModule &CGM) const override;
2125
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002126 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002127 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002128 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002129 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002130 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002131
2132 void getDetectMismatchOption(llvm::StringRef Name,
2133 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002134 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002135 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002136 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002137};
2138
Hans Wennborg77dc2362015-01-20 19:45:50 +00002139static void addStackProbeSizeTargetAttribute(const Decl *D,
2140 llvm::GlobalValue *GV,
2141 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002142 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002143 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2144 llvm::Function *Fn = cast<llvm::Function>(GV);
2145
Eric Christopher7565e0d2015-05-29 23:09:49 +00002146 Fn->addFnAttr("stack-probe-size",
2147 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002148 }
2149 }
2150}
2151
Eric Christopher162c91c2015-06-05 22:03:00 +00002152void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002153 llvm::GlobalValue *GV,
2154 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002155 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002156
2157 addStackProbeSizeTargetAttribute(D, GV, CGM);
2158}
2159
Chris Lattner04dc9572010-08-31 16:44:54 +00002160class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2161public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002162 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2163 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002164 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002165
Eric Christopher162c91c2015-06-05 22:03:00 +00002166 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002167 CodeGen::CodeGenModule &CGM) const override;
2168
Craig Topper4f12f102014-03-12 06:41:41 +00002169 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002170 return 7;
2171 }
2172
2173 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002174 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002175 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002176
Chris Lattner04dc9572010-08-31 16:44:54 +00002177 // 0-15 are the 16 integer registers.
2178 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002179 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002180 return false;
2181 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002182
2183 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002184 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002185 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002186 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002187 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002188
2189 void getDetectMismatchOption(llvm::StringRef Name,
2190 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002191 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002192 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002193 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002194};
2195
Eric Christopher162c91c2015-06-05 22:03:00 +00002196void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002197 llvm::GlobalValue *GV,
2198 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002199 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002200
Alexey Bataevd51e9932016-01-15 04:06:31 +00002201 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2202 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2203 llvm::Function *Fn = cast<llvm::Function>(GV);
2204 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2205 }
2206 }
2207
Hans Wennborg77dc2362015-01-20 19:45:50 +00002208 addStackProbeSizeTargetAttribute(D, GV, CGM);
2209}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002210}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002211
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002212void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2213 Class &Hi) const {
2214 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2215 //
2216 // (a) If one of the classes is Memory, the whole argument is passed in
2217 // memory.
2218 //
2219 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2220 // memory.
2221 //
2222 // (c) If the size of the aggregate exceeds two eightbytes and the first
2223 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2224 // argument is passed in memory. NOTE: This is necessary to keep the
2225 // ABI working for processors that don't support the __m256 type.
2226 //
2227 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2228 //
2229 // Some of these are enforced by the merging logic. Others can arise
2230 // only with unions; for example:
2231 // union { _Complex double; unsigned; }
2232 //
2233 // Note that clauses (b) and (c) were added in 0.98.
2234 //
2235 if (Hi == Memory)
2236 Lo = Memory;
2237 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2238 Lo = Memory;
2239 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2240 Lo = Memory;
2241 if (Hi == SSEUp && Lo != SSE)
2242 Hi = SSE;
2243}
2244
Chris Lattnerd776fb12010-06-28 21:43:59 +00002245X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002246 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2247 // classified recursively so that always two fields are
2248 // considered. The resulting class is calculated according to
2249 // the classes of the fields in the eightbyte:
2250 //
2251 // (a) If both classes are equal, this is the resulting class.
2252 //
2253 // (b) If one of the classes is NO_CLASS, the resulting class is
2254 // the other class.
2255 //
2256 // (c) If one of the classes is MEMORY, the result is the MEMORY
2257 // class.
2258 //
2259 // (d) If one of the classes is INTEGER, the result is the
2260 // INTEGER.
2261 //
2262 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2263 // MEMORY is used as class.
2264 //
2265 // (f) Otherwise class SSE is used.
2266
2267 // Accum should never be memory (we should have returned) or
2268 // ComplexX87 (because this cannot be passed in a structure).
2269 assert((Accum != Memory && Accum != ComplexX87) &&
2270 "Invalid accumulated classification during merge.");
2271 if (Accum == Field || Field == NoClass)
2272 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002273 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002274 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002275 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002276 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002277 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002278 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002279 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2280 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002281 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002282 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002283}
2284
Chris Lattner5c740f12010-06-30 19:14:05 +00002285void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002286 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002287 // FIXME: This code can be simplified by introducing a simple value class for
2288 // Class pairs with appropriate constructor methods for the various
2289 // situations.
2290
2291 // FIXME: Some of the split computations are wrong; unaligned vectors
2292 // shouldn't be passed in registers for example, so there is no chance they
2293 // can straddle an eightbyte. Verify & simplify.
2294
2295 Lo = Hi = NoClass;
2296
2297 Class &Current = OffsetBase < 64 ? Lo : Hi;
2298 Current = Memory;
2299
John McCall9dd450b2009-09-21 23:43:11 +00002300 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002301 BuiltinType::Kind k = BT->getKind();
2302
2303 if (k == BuiltinType::Void) {
2304 Current = NoClass;
2305 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2306 Lo = Integer;
2307 Hi = Integer;
2308 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2309 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002310 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002311 Current = SSE;
2312 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002313 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2314 if (LDF == &llvm::APFloat::IEEEquad) {
2315 Lo = SSE;
2316 Hi = SSEUp;
2317 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2318 Lo = X87;
2319 Hi = X87Up;
2320 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2321 Current = SSE;
2322 } else
2323 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002324 }
2325 // FIXME: _Decimal32 and _Decimal64 are SSE.
2326 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002327 return;
2328 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002329
Chris Lattnerd776fb12010-06-28 21:43:59 +00002330 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002331 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002332 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002333 return;
2334 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002335
Chris Lattnerd776fb12010-06-28 21:43:59 +00002336 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002337 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002338 return;
2339 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002340
Chris Lattnerd776fb12010-06-28 21:43:59 +00002341 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002342 if (Ty->isMemberFunctionPointerType()) {
2343 if (Has64BitPointers) {
2344 // If Has64BitPointers, this is an {i64, i64}, so classify both
2345 // Lo and Hi now.
2346 Lo = Hi = Integer;
2347 } else {
2348 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2349 // straddles an eightbyte boundary, Hi should be classified as well.
2350 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2351 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2352 if (EB_FuncPtr != EB_ThisAdj) {
2353 Lo = Hi = Integer;
2354 } else {
2355 Current = Integer;
2356 }
2357 }
2358 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002359 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002360 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002361 return;
2362 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002363
Chris Lattnerd776fb12010-06-28 21:43:59 +00002364 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002365 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002366 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2367 // gcc passes the following as integer:
2368 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2369 // 2 bytes - <2 x char>, <1 x short>
2370 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002371 Current = Integer;
2372
2373 // If this type crosses an eightbyte boundary, it should be
2374 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002375 uint64_t EB_Lo = (OffsetBase) / 64;
2376 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2377 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002378 Hi = Lo;
2379 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002380 QualType ElementType = VT->getElementType();
2381
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002382 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002383 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002384 return;
2385
David Majnemere2ae2282016-03-04 05:26:16 +00002386 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2387 // pass them as integer. For platforms where clang is the de facto
2388 // platform compiler, we must continue to use integer.
2389 if (!classifyIntegerMMXAsSSE() &&
2390 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2391 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2392 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2393 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002394 Current = Integer;
2395 else
2396 Current = SSE;
2397
2398 // If this type crosses an eightbyte boundary, it should be
2399 // split.
2400 if (OffsetBase && OffsetBase != 64)
2401 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002402 } else if (Size == 128 ||
2403 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002404 // Arguments of 256-bits are split into four eightbyte chunks. The
2405 // least significant one belongs to class SSE and all the others to class
2406 // SSEUP. The original Lo and Hi design considers that types can't be
2407 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2408 // This design isn't correct for 256-bits, but since there're no cases
2409 // where the upper parts would need to be inspected, avoid adding
2410 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002411 //
2412 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2413 // registers if they are "named", i.e. not part of the "..." of a
2414 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002415 //
2416 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2417 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002418 Lo = SSE;
2419 Hi = SSEUp;
2420 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002421 return;
2422 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002423
Chris Lattnerd776fb12010-06-28 21:43:59 +00002424 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002425 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002426
Chris Lattner2b037972010-07-29 02:01:43 +00002427 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002428 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002429 if (Size <= 64)
2430 Current = Integer;
2431 else if (Size <= 128)
2432 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002433 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002434 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002435 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002436 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002437 } else if (ET == getContext().LongDoubleTy) {
2438 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2439 if (LDF == &llvm::APFloat::IEEEquad)
2440 Current = Memory;
2441 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2442 Current = ComplexX87;
2443 else if (LDF == &llvm::APFloat::IEEEdouble)
2444 Lo = Hi = SSE;
2445 else
2446 llvm_unreachable("unexpected long double representation!");
2447 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002448
2449 // If this complex type crosses an eightbyte boundary then it
2450 // should be split.
2451 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002452 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002453 if (Hi == NoClass && EB_Real != EB_Imag)
2454 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002455
Chris Lattnerd776fb12010-06-28 21:43:59 +00002456 return;
2457 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002458
Chris Lattner2b037972010-07-29 02:01:43 +00002459 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002460 // Arrays are treated like structures.
2461
Chris Lattner2b037972010-07-29 02:01:43 +00002462 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002463
2464 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002465 // than four eightbytes, ..., it has class MEMORY.
2466 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002467 return;
2468
2469 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2470 // fields, it has class MEMORY.
2471 //
2472 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002473 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002474 return;
2475
2476 // Otherwise implement simplified merge. We could be smarter about
2477 // this, but it isn't worth it and would be harder to verify.
2478 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002479 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002480 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002481
2482 // The only case a 256-bit wide vector could be used is when the array
2483 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2484 // to work for sizes wider than 128, early check and fallback to memory.
2485 if (Size > 128 && EltSize != 256)
2486 return;
2487
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002488 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2489 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002490 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002491 Lo = merge(Lo, FieldLo);
2492 Hi = merge(Hi, FieldHi);
2493 if (Lo == Memory || Hi == Memory)
2494 break;
2495 }
2496
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002497 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002498 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002499 return;
2500 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002501
Chris Lattnerd776fb12010-06-28 21:43:59 +00002502 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002503 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002504
2505 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002506 // than four eightbytes, ..., it has class MEMORY.
2507 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002508 return;
2509
Anders Carlsson20759ad2009-09-16 15:53:40 +00002510 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2511 // copy constructor or a non-trivial destructor, it is passed by invisible
2512 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002513 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002514 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002515
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002516 const RecordDecl *RD = RT->getDecl();
2517
2518 // Assume variable sized types are passed in memory.
2519 if (RD->hasFlexibleArrayMember())
2520 return;
2521
Chris Lattner2b037972010-07-29 02:01:43 +00002522 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523
2524 // Reset Lo class, this will be recomputed.
2525 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002526
2527 // If this is a C++ record, classify the bases first.
2528 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002529 for (const auto &I : CXXRD->bases()) {
2530 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002531 "Unexpected base class!");
2532 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002533 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002534
2535 // Classify this field.
2536 //
2537 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2538 // single eightbyte, each is classified separately. Each eightbyte gets
2539 // initialized to class NO_CLASS.
2540 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002541 uint64_t Offset =
2542 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002543 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002544 Lo = merge(Lo, FieldLo);
2545 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002546 if (Lo == Memory || Hi == Memory) {
2547 postMerge(Size, Lo, Hi);
2548 return;
2549 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002550 }
2551 }
2552
2553 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002554 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002555 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002556 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002557 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2558 bool BitField = i->isBitField();
2559
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002560 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2561 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002562 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002563 // The only case a 256-bit wide vector could be used is when the struct
2564 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2565 // to work for sizes wider than 128, early check and fallback to memory.
2566 //
2567 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2568 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002569 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002570 return;
2571 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002572 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002573 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002574 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002575 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002576 return;
2577 }
2578
2579 // Classify this field.
2580 //
2581 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2582 // exceeds a single eightbyte, each is classified
2583 // separately. Each eightbyte gets initialized to class
2584 // NO_CLASS.
2585 Class FieldLo, FieldHi;
2586
2587 // Bit-fields require special handling, they do not force the
2588 // structure to be passed in memory even if unaligned, and
2589 // therefore they can straddle an eightbyte.
2590 if (BitField) {
2591 // Ignore padding bit-fields.
2592 if (i->isUnnamedBitfield())
2593 continue;
2594
2595 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002596 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002597
2598 uint64_t EB_Lo = Offset / 64;
2599 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002600
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002601 if (EB_Lo) {
2602 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2603 FieldLo = NoClass;
2604 FieldHi = Integer;
2605 } else {
2606 FieldLo = Integer;
2607 FieldHi = EB_Hi ? Integer : NoClass;
2608 }
2609 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002610 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002611 Lo = merge(Lo, FieldLo);
2612 Hi = merge(Hi, FieldHi);
2613 if (Lo == Memory || Hi == Memory)
2614 break;
2615 }
2616
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002617 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 }
2619}
2620
Chris Lattner22a931e2010-06-29 06:01:59 +00002621ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002622 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2623 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002624 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002625 // Treat an enum type as its underlying type.
2626 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2627 Ty = EnumTy->getDecl()->getIntegerType();
2628
2629 return (Ty->isPromotableIntegerType() ?
2630 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2631 }
2632
John McCall7f416cc2015-09-08 08:05:57 +00002633 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002634}
2635
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002636bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2637 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2638 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002639 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002640 if (Size <= 64 || Size > LargestVector)
2641 return true;
2642 }
2643
2644 return false;
2645}
2646
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002647ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2648 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2650 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002651 //
2652 // This assumption is optimistic, as there could be free registers available
2653 // when we need to pass this argument in memory, and LLVM could try to pass
2654 // the argument in the free register. This does not seem to happen currently,
2655 // but this code would be much safer if we could mark the argument with
2656 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002657 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002658 // Treat an enum type as its underlying type.
2659 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2660 Ty = EnumTy->getDecl()->getIntegerType();
2661
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002662 return (Ty->isPromotableIntegerType() ?
2663 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002664 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002665
Mark Lacey3825e832013-10-06 01:33:34 +00002666 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002667 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002668
Chris Lattner44c2b902011-05-22 23:21:23 +00002669 // Compute the byval alignment. We specify the alignment of the byval in all
2670 // cases so that the mid-level optimizer knows the alignment of the byval.
2671 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002672
2673 // Attempt to avoid passing indirect results using byval when possible. This
2674 // is important for good codegen.
2675 //
2676 // We do this by coercing the value into a scalar type which the backend can
2677 // handle naturally (i.e., without using byval).
2678 //
2679 // For simplicity, we currently only do this when we have exhausted all of the
2680 // free integer registers. Doing this when there are free integer registers
2681 // would require more care, as we would have to ensure that the coerced value
2682 // did not claim the unused register. That would require either reording the
2683 // arguments to the function (so that any subsequent inreg values came first),
2684 // or only doing this optimization when there were no following arguments that
2685 // might be inreg.
2686 //
2687 // We currently expect it to be rare (particularly in well written code) for
2688 // arguments to be passed on the stack when there are still free integer
2689 // registers available (this would typically imply large structs being passed
2690 // by value), so this seems like a fair tradeoff for now.
2691 //
2692 // We can revisit this if the backend grows support for 'onstack' parameter
2693 // attributes. See PR12193.
2694 if (freeIntRegs == 0) {
2695 uint64_t Size = getContext().getTypeSize(Ty);
2696
2697 // If this type fits in an eightbyte, coerce it into the matching integral
2698 // type, which will end up on the stack (with alignment 8).
2699 if (Align == 8 && Size <= 64)
2700 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2701 Size));
2702 }
2703
John McCall7f416cc2015-09-08 08:05:57 +00002704 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002705}
2706
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002707/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2708/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002709llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002710 // Wrapper structs/arrays that only contain vectors are passed just like
2711 // vectors; strip them off if present.
2712 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2713 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002714
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002715 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002716 if (isa<llvm::VectorType>(IRType) ||
2717 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002718 return IRType;
2719
2720 // We couldn't find the preferred IR vector type for 'Ty'.
2721 uint64_t Size = getContext().getTypeSize(Ty);
2722 assert((Size == 128 || Size == 256) && "Invalid type found!");
2723
2724 // Return a LLVM IR vector type based on the size of 'Ty'.
2725 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2726 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002727}
2728
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002729/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2730/// is known to either be off the end of the specified type or being in
2731/// alignment padding. The user type specified is known to be at most 128 bits
2732/// in size, and have passed through X86_64ABIInfo::classify with a successful
2733/// classification that put one of the two halves in the INTEGER class.
2734///
2735/// It is conservatively correct to return false.
2736static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2737 unsigned EndBit, ASTContext &Context) {
2738 // If the bytes being queried are off the end of the type, there is no user
2739 // data hiding here. This handles analysis of builtins, vectors and other
2740 // types that don't contain interesting padding.
2741 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2742 if (TySize <= StartBit)
2743 return true;
2744
Chris Lattner98076a22010-07-29 07:43:55 +00002745 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2746 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2747 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2748
2749 // Check each element to see if the element overlaps with the queried range.
2750 for (unsigned i = 0; i != NumElts; ++i) {
2751 // If the element is after the span we care about, then we're done..
2752 unsigned EltOffset = i*EltSize;
2753 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002754
Chris Lattner98076a22010-07-29 07:43:55 +00002755 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2756 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2757 EndBit-EltOffset, Context))
2758 return false;
2759 }
2760 // If it overlaps no elements, then it is safe to process as padding.
2761 return true;
2762 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002763
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002764 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2765 const RecordDecl *RD = RT->getDecl();
2766 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002767
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002768 // If this is a C++ record, check the bases first.
2769 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002770 for (const auto &I : CXXRD->bases()) {
2771 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002772 "Unexpected base class!");
2773 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002774 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002775
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002776 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002777 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002778 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002779
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002780 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002781 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002782 EndBit-BaseOffset, Context))
2783 return false;
2784 }
2785 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002786
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002787 // Verify that no field has data that overlaps the region of interest. Yes
2788 // this could be sped up a lot by being smarter about queried fields,
2789 // however we're only looking at structs up to 16 bytes, so we don't care
2790 // much.
2791 unsigned idx = 0;
2792 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2793 i != e; ++i, ++idx) {
2794 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002795
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002796 // If we found a field after the region we care about, then we're done.
2797 if (FieldOffset >= EndBit) break;
2798
2799 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2800 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2801 Context))
2802 return false;
2803 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002804
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002805 // If nothing in this record overlapped the area of interest, then we're
2806 // clean.
2807 return true;
2808 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002809
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002810 return false;
2811}
2812
Chris Lattnere556a712010-07-29 18:39:32 +00002813/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2814/// float member at the specified offset. For example, {int,{float}} has a
2815/// float at offset 4. It is conservatively correct for this routine to return
2816/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002817static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002818 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002819 // Base case if we find a float.
2820 if (IROffset == 0 && IRType->isFloatTy())
2821 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002822
Chris Lattnere556a712010-07-29 18:39:32 +00002823 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002824 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002825 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2826 unsigned Elt = SL->getElementContainingOffset(IROffset);
2827 IROffset -= SL->getElementOffset(Elt);
2828 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2829 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002830
Chris Lattnere556a712010-07-29 18:39:32 +00002831 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002832 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2833 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002834 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2835 IROffset -= IROffset/EltSize*EltSize;
2836 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2837 }
2838
2839 return false;
2840}
2841
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002842
2843/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2844/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002845llvm::Type *X86_64ABIInfo::
2846GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002847 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002848 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002849 // pass as float if the last 4 bytes is just padding. This happens for
2850 // structs that contain 3 floats.
2851 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2852 SourceOffset*8+64, getContext()))
2853 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002854
Chris Lattnere556a712010-07-29 18:39:32 +00002855 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2856 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2857 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002858 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2859 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002860 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002861
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002862 return llvm::Type::getDoubleTy(getVMContext());
2863}
2864
2865
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002866/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2867/// an 8-byte GPR. This means that we either have a scalar or we are talking
2868/// about the high or low part of an up-to-16-byte struct. This routine picks
2869/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002870/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2871/// etc).
2872///
2873/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2874/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2875/// the 8-byte value references. PrefType may be null.
2876///
Alp Toker9907f082014-07-09 14:06:35 +00002877/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002878/// an offset into this that we're processing (which is always either 0 or 8).
2879///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002880llvm::Type *X86_64ABIInfo::
2881GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002882 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002883 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2884 // returning an 8-byte unit starting with it. See if we can safely use it.
2885 if (IROffset == 0) {
2886 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002887 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2888 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002889 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002890
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002891 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2892 // goodness in the source type is just tail padding. This is allowed to
2893 // kick in for struct {double,int} on the int, but not on
2894 // struct{double,int,int} because we wouldn't return the second int. We
2895 // have to do this analysis on the source type because we can't depend on
2896 // unions being lowered a specific way etc.
2897 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002898 IRType->isIntegerTy(32) ||
2899 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2900 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2901 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002902
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002903 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2904 SourceOffset*8+64, getContext()))
2905 return IRType;
2906 }
2907 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002908
Chris Lattner2192fe52011-07-18 04:24:23 +00002909 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002910 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002911 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002912 if (IROffset < SL->getSizeInBytes()) {
2913 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2914 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002915
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002916 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2917 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002918 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002919 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002920
Chris Lattner2192fe52011-07-18 04:24:23 +00002921 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002922 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002923 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002924 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002925 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2926 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002927 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002928
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002929 // Okay, we don't have any better idea of what to pass, so we pass this in an
2930 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002931 unsigned TySizeInBytes =
2932 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002933
Chris Lattner3f763422010-07-29 17:34:39 +00002934 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002935
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002936 // It is always safe to classify this as an integer type up to i64 that
2937 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002938 return llvm::IntegerType::get(getVMContext(),
2939 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002940}
2941
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002942
2943/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2944/// be used as elements of a two register pair to pass or return, return a
2945/// first class aggregate to represent them. For example, if the low part of
2946/// a by-value argument should be passed as i32* and the high part as float,
2947/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002948static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002949GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002950 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002951 // In order to correctly satisfy the ABI, we need to the high part to start
2952 // at offset 8. If the high and low parts we inferred are both 4-byte types
2953 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2954 // the second element at offset 8. Check for this:
2955 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2956 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002957 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002958 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002959
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002960 // To handle this, we have to increase the size of the low part so that the
2961 // second element will start at an 8 byte offset. We can't increase the size
2962 // of the second element because it might make us access off the end of the
2963 // struct.
2964 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002965 // There are usually two sorts of types the ABI generation code can produce
2966 // for the low part of a pair that aren't 8 bytes in size: float or
2967 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2968 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002969 // Promote these to a larger type.
2970 if (Lo->isFloatTy())
2971 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2972 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002973 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2974 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002975 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2976 }
2977 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002978
Reid Kleckneree7cf842014-12-01 22:02:27 +00002979 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002980
2981
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002982 // Verify that the second element is at an 8-byte offset.
2983 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2984 "Invalid x86-64 argument pair!");
2985 return Result;
2986}
2987
Chris Lattner31faff52010-07-28 23:06:14 +00002988ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002989classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002990 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2991 // classification algorithm.
2992 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002993 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002994
2995 // Check some invariants.
2996 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002997 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2998
Craig Topper8a13c412014-05-21 05:09:00 +00002999 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003000 switch (Lo) {
3001 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003002 if (Hi == NoClass)
3003 return ABIArgInfo::getIgnore();
3004 // If the low part is just padding, it takes no register, leave ResType
3005 // null.
3006 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3007 "Unknown missing lo part");
3008 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003009
3010 case SSEUp:
3011 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003012 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003013
3014 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3015 // hidden argument.
3016 case Memory:
3017 return getIndirectReturnResult(RetTy);
3018
3019 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3020 // available register of the sequence %rax, %rdx is used.
3021 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003022 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003023
Chris Lattner1f3a0632010-07-29 21:42:50 +00003024 // If we have a sign or zero extended integer, make sure to return Extend
3025 // so that the parameter gets the right LLVM IR attributes.
3026 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3027 // Treat an enum type as its underlying type.
3028 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3029 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003030
Chris Lattner1f3a0632010-07-29 21:42:50 +00003031 if (RetTy->isIntegralOrEnumerationType() &&
3032 RetTy->isPromotableIntegerType())
3033 return ABIArgInfo::getExtend();
3034 }
Chris Lattner31faff52010-07-28 23:06:14 +00003035 break;
3036
3037 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3038 // available SSE register of the sequence %xmm0, %xmm1 is used.
3039 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003040 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003041 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003042
3043 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3044 // returned on the X87 stack in %st0 as 80-bit x87 number.
3045 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003046 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003047 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003048
3049 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3050 // part of the value is returned in %st0 and the imaginary part in
3051 // %st1.
3052 case ComplexX87:
3053 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003054 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003055 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003056 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003057 break;
3058 }
3059
Craig Topper8a13c412014-05-21 05:09:00 +00003060 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003061 switch (Hi) {
3062 // Memory was handled previously and X87 should
3063 // never occur as a hi class.
3064 case Memory:
3065 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003066 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003067
3068 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003069 case NoClass:
3070 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003071
Chris Lattner52b3c132010-09-01 00:20:33 +00003072 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003073 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003074 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3075 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003076 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003077 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003078 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003079 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3080 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003081 break;
3082
3083 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003084 // is passed in the next available eightbyte chunk if the last used
3085 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003086 //
Chris Lattner57540c52011-04-15 05:22:18 +00003087 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003088 case SSEUp:
3089 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003090 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003091 break;
3092
3093 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3094 // returned together with the previous X87 value in %st0.
3095 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003096 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003097 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003098 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003099 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003100 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003101 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003102 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3103 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003104 }
Chris Lattner31faff52010-07-28 23:06:14 +00003105 break;
3106 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003107
Chris Lattner52b3c132010-09-01 00:20:33 +00003108 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003109 // known to pass in the high eightbyte of the result. We do this by forming a
3110 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003111 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003112 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003113
Chris Lattner1f3a0632010-07-29 21:42:50 +00003114 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003115}
3116
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003117ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003118 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3119 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003120 const
3121{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003122 Ty = useFirstFieldIfTransparentUnion(Ty);
3123
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003124 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003125 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003126
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003127 // Check some invariants.
3128 // FIXME: Enforce these by construction.
3129 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003130 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3131
3132 neededInt = 0;
3133 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003134 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003135 switch (Lo) {
3136 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003137 if (Hi == NoClass)
3138 return ABIArgInfo::getIgnore();
3139 // If the low part is just padding, it takes no register, leave ResType
3140 // null.
3141 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3142 "Unknown missing lo part");
3143 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003144
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003145 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3146 // on the stack.
3147 case Memory:
3148
3149 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3150 // COMPLEX_X87, it is passed in memory.
3151 case X87:
3152 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003153 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003154 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003155 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003156
3157 case SSEUp:
3158 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003159 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003160
3161 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3162 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3163 // and %r9 is used.
3164 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003165 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003166
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003167 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003168 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003169
3170 // If we have a sign or zero extended integer, make sure to return Extend
3171 // so that the parameter gets the right LLVM IR attributes.
3172 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3173 // Treat an enum type as its underlying type.
3174 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3175 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003176
Chris Lattner1f3a0632010-07-29 21:42:50 +00003177 if (Ty->isIntegralOrEnumerationType() &&
3178 Ty->isPromotableIntegerType())
3179 return ABIArgInfo::getExtend();
3180 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003181
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003182 break;
3183
3184 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3185 // available SSE register is used, the registers are taken in the
3186 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003187 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003188 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003189 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003190 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003191 break;
3192 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003193 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003194
Craig Topper8a13c412014-05-21 05:09:00 +00003195 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003196 switch (Hi) {
3197 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003198 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003199 // which is passed in memory.
3200 case Memory:
3201 case X87:
3202 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003203 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003204
3205 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003206
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003207 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003209 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003210 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003211
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003212 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3213 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003214 break;
3215
3216 // X87Up generally doesn't occur here (long double is passed in
3217 // memory), except in situations involving unions.
3218 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003219 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003220 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003221
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003222 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3223 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003224
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003225 ++neededSSE;
3226 break;
3227
3228 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3229 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003230 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003231 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003232 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003233 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003234 break;
3235 }
3236
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003237 // If a high part was specified, merge it together with the low part. It is
3238 // known to pass in the high eightbyte of the result. We do this by forming a
3239 // first class struct aggregate with the high and low part: {low, high}
3240 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003241 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003242
Chris Lattner1f3a0632010-07-29 21:42:50 +00003243 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003244}
3245
Chris Lattner22326a12010-07-29 02:31:05 +00003246void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003247
Reid Kleckner40ca9132014-05-13 22:05:45 +00003248 if (!getCXXABI().classifyReturnType(FI))
3249 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003250
3251 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003252 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003253
3254 // If the return value is indirect, then the hidden argument is consuming one
3255 // integer register.
3256 if (FI.getReturnInfo().isIndirect())
3257 --freeIntRegs;
3258
Peter Collingbournef7706832014-12-12 23:41:25 +00003259 // The chain argument effectively gives us another free register.
3260 if (FI.isChainCall())
3261 ++freeIntRegs;
3262
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003263 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003264 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3265 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003266 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003267 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003268 it != ie; ++it, ++ArgNo) {
3269 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003270
Bill Wendling9987c0e2010-10-18 23:51:38 +00003271 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003272 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003273 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003274
3275 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3276 // eightbyte of an argument, the whole argument is passed on the
3277 // stack. If registers have already been assigned for some
3278 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003279 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003280 freeIntRegs -= neededInt;
3281 freeSSERegs -= neededSSE;
3282 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003283 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003284 }
3285 }
3286}
3287
John McCall7f416cc2015-09-08 08:05:57 +00003288static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3289 Address VAListAddr, QualType Ty) {
3290 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3291 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003292 llvm::Value *overflow_arg_area =
3293 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3294
3295 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3296 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003297 // It isn't stated explicitly in the standard, but in practice we use
3298 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003299 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3300 if (Align > CharUnits::fromQuantity(8)) {
3301 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3302 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003303 }
3304
3305 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003306 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003307 llvm::Value *Res =
3308 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003309 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003310
3311 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3312 // l->overflow_arg_area + sizeof(type).
3313 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3314 // an 8 byte boundary.
3315
3316 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003317 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003318 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003319 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3320 "overflow_arg_area.next");
3321 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3322
3323 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003324 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003325}
3326
John McCall7f416cc2015-09-08 08:05:57 +00003327Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3328 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003329 // Assume that va_list type is correct; should be pointer to LLVM type:
3330 // struct {
3331 // i32 gp_offset;
3332 // i32 fp_offset;
3333 // i8* overflow_arg_area;
3334 // i8* reg_save_area;
3335 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003336 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003337
John McCall7f416cc2015-09-08 08:05:57 +00003338 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003339 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003340 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003341
3342 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3343 // in the registers. If not go to step 7.
3344 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003345 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003346
3347 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3348 // general purpose registers needed to pass type and num_fp to hold
3349 // the number of floating point registers needed.
3350
3351 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3352 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3353 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3354 //
3355 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3356 // register save space).
3357
Craig Topper8a13c412014-05-21 05:09:00 +00003358 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003359 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3360 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003361 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003362 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003363 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3364 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003365 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003366 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3367 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003368 }
3369
3370 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003371 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003372 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3373 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003374 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3375 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003376 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3377 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003378 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3379 }
3380
3381 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3382 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3383 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3384 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3385
3386 // Emit code to load the value if it was passed in registers.
3387
3388 CGF.EmitBlock(InRegBlock);
3389
3390 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3391 // an offset of l->gp_offset and/or l->fp_offset. This may require
3392 // copying to a temporary location in case the parameter is passed
3393 // in different register classes or requires an alignment greater
3394 // than 8 for general purpose registers and 16 for XMM registers.
3395 //
3396 // FIXME: This really results in shameful code when we end up needing to
3397 // collect arguments from different places; often what should result in a
3398 // simple assembling of a structure from scattered addresses has many more
3399 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003400 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003401 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3402 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3403 "reg_save_area");
3404
3405 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003406 if (neededInt && neededSSE) {
3407 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003408 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003409 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003410 Address Tmp = CGF.CreateMemTemp(Ty);
3411 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003412 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003413 llvm::Type *TyLo = ST->getElementType(0);
3414 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003415 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003416 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003417 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3418 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003419 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3420 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003421 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3422 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003423
John McCall7f416cc2015-09-08 08:05:57 +00003424 // Copy the first element.
3425 llvm::Value *V =
3426 CGF.Builder.CreateDefaultAlignedLoad(
3427 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3428 CGF.Builder.CreateStore(V,
3429 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3430
3431 // Copy the second element.
3432 V = CGF.Builder.CreateDefaultAlignedLoad(
3433 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3434 CharUnits Offset = CharUnits::fromQuantity(
3435 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3436 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3437
3438 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003439 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003440 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3441 CharUnits::fromQuantity(8));
3442 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003443
3444 // Copy to a temporary if necessary to ensure the appropriate alignment.
3445 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003446 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003447 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003448 CharUnits TyAlign = SizeAlign.second;
3449
3450 // Copy into a temporary if the type is more aligned than the
3451 // register save area.
3452 if (TyAlign.getQuantity() > 8) {
3453 Address Tmp = CGF.CreateMemTemp(Ty);
3454 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003455 RegAddr = Tmp;
3456 }
John McCall7f416cc2015-09-08 08:05:57 +00003457
Chris Lattner0cf24192010-06-28 20:05:43 +00003458 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003459 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3460 CharUnits::fromQuantity(16));
3461 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003462 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003463 assert(neededSSE == 2 && "Invalid number of needed registers!");
3464 // SSE registers are spaced 16 bytes apart in the register save
3465 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003466 // The ABI isn't explicit about this, but it seems reasonable
3467 // to assume that the slots are 16-byte aligned, since the stack is
3468 // naturally 16-byte aligned and the prologue is expected to store
3469 // all the SSE registers to the RSA.
3470 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3471 CharUnits::fromQuantity(16));
3472 Address RegAddrHi =
3473 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3474 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003475 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003476 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003477 llvm::Value *V;
3478 Address Tmp = CGF.CreateMemTemp(Ty);
3479 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3480 V = CGF.Builder.CreateLoad(
3481 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3482 CGF.Builder.CreateStore(V,
3483 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3484 V = CGF.Builder.CreateLoad(
3485 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3486 CGF.Builder.CreateStore(V,
3487 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3488
3489 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003490 }
3491
3492 // AMD64-ABI 3.5.7p5: Step 5. Set:
3493 // l->gp_offset = l->gp_offset + num_gp * 8
3494 // l->fp_offset = l->fp_offset + num_fp * 16.
3495 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003496 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003497 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3498 gp_offset_p);
3499 }
3500 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003501 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003502 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3503 fp_offset_p);
3504 }
3505 CGF.EmitBranch(ContBlock);
3506
3507 // Emit code to load the value if it was passed in memory.
3508
3509 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003510 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003511
3512 // Return the appropriate result.
3513
3514 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003515 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3516 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003517 return ResAddr;
3518}
3519
Charles Davisc7d5c942015-09-17 20:55:33 +00003520Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3521 QualType Ty) const {
3522 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3523 CGF.getContext().getTypeInfoInChars(Ty),
3524 CharUnits::fromQuantity(8),
3525 /*allowHigherAlign*/ false);
3526}
3527
Reid Kleckner80944df2014-10-31 22:00:51 +00003528ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3529 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003530
3531 if (Ty->isVoidType())
3532 return ABIArgInfo::getIgnore();
3533
3534 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3535 Ty = EnumTy->getDecl()->getIntegerType();
3536
Reid Kleckner80944df2014-10-31 22:00:51 +00003537 TypeInfo Info = getContext().getTypeInfo(Ty);
3538 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003539 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003540
Reid Kleckner9005f412014-05-02 00:51:20 +00003541 const RecordType *RT = Ty->getAs<RecordType>();
3542 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003543 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003544 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003545 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003546 }
3547
3548 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003549 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003550
Reid Kleckner9005f412014-05-02 00:51:20 +00003551 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003552
Reid Kleckner80944df2014-10-31 22:00:51 +00003553 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3554 // other targets.
3555 const Type *Base = nullptr;
3556 uint64_t NumElts = 0;
3557 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3558 if (FreeSSERegs >= NumElts) {
3559 FreeSSERegs -= NumElts;
3560 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3561 return ABIArgInfo::getDirect();
3562 return ABIArgInfo::getExpand();
3563 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003564 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003565 }
3566
3567
Reid Klecknerec87fec2014-05-02 01:17:12 +00003568 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003569 // If the member pointer is represented by an LLVM int or ptr, pass it
3570 // directly.
3571 llvm::Type *LLTy = CGT.ConvertType(Ty);
3572 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3573 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003574 }
3575
Michael Kuperstein4f818702015-02-24 09:35:58 +00003576 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003577 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3578 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003579 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003580 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003581
Reid Kleckner9005f412014-05-02 00:51:20 +00003582 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003583 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003584 }
3585
Julien Lerouge10dcff82014-08-27 00:36:55 +00003586 // Bool type is always extended to the ABI, other builtin types are not
3587 // extended.
3588 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3589 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003590 return ABIArgInfo::getExtend();
3591
Reid Kleckner11a17192015-10-28 22:29:52 +00003592 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3593 // passes them indirectly through memory.
3594 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3595 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3596 if (LDF == &llvm::APFloat::x87DoubleExtended)
3597 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3598 }
3599
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003600 return ABIArgInfo::getDirect();
3601}
3602
3603void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003604 bool IsVectorCall =
3605 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003606
Reid Kleckner80944df2014-10-31 22:00:51 +00003607 // We can use up to 4 SSE return registers with vectorcall.
3608 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3609 if (!getCXXABI().classifyReturnType(FI))
3610 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3611
3612 // We can use up to 6 SSE register parameters with vectorcall.
3613 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003614 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003615 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003616}
3617
John McCall7f416cc2015-09-08 08:05:57 +00003618Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3619 QualType Ty) const {
3620 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3621 CGF.getContext().getTypeInfoInChars(Ty),
3622 CharUnits::fromQuantity(8),
3623 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003624}
Chris Lattner0cf24192010-06-28 20:05:43 +00003625
John McCallea8d8bb2010-03-11 00:10:12 +00003626// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003627namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003628/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3629class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003630bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003631public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003632 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3633 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003634
John McCall7f416cc2015-09-08 08:05:57 +00003635 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3636 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003637};
3638
3639class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3640public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003641 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3642 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003643
Craig Topper4f12f102014-03-12 06:41:41 +00003644 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003645 // This is recovered from gcc output.
3646 return 1; // r1 is the dedicated stack pointer
3647 }
3648
3649 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003650 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003651};
3652
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003653}
John McCallea8d8bb2010-03-11 00:10:12 +00003654
James Y Knight29b5f082016-02-24 02:59:33 +00003655// TODO: this implementation is now likely redundant with
3656// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003657Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3658 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003659 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003660 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3661 // TODO: Implement this. For now ignore.
3662 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003663 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003664 }
3665
John McCall7f416cc2015-09-08 08:05:57 +00003666 // struct __va_list_tag {
3667 // unsigned char gpr;
3668 // unsigned char fpr;
3669 // unsigned short reserved;
3670 // void *overflow_arg_area;
3671 // void *reg_save_area;
3672 // };
3673
Roman Divacky8a12d842014-11-03 18:32:54 +00003674 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003675 bool isInt =
3676 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003677 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003678
3679 // All aggregates are passed indirectly? That doesn't seem consistent
3680 // with the argument-lowering code.
3681 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003682
3683 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003684
3685 // The calling convention either uses 1-2 GPRs or 1 FPR.
3686 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003687 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003688 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3689 } else {
3690 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003691 }
John McCall7f416cc2015-09-08 08:05:57 +00003692
3693 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3694
3695 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003696 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003697 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3698 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3699 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003700
Eric Christopher7565e0d2015-05-29 23:09:49 +00003701 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003702 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003703
3704 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3705 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3706 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3707
3708 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3709
John McCall7f416cc2015-09-08 08:05:57 +00003710 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3711 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003712
John McCall7f416cc2015-09-08 08:05:57 +00003713 // Case 1: consume registers.
3714 Address RegAddr = Address::invalid();
3715 {
3716 CGF.EmitBlock(UsingRegs);
3717
3718 Address RegSaveAreaPtr =
3719 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3720 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3721 CharUnits::fromQuantity(8));
3722 assert(RegAddr.getElementType() == CGF.Int8Ty);
3723
3724 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003725 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003726 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3727 CharUnits::fromQuantity(32));
3728 }
3729
3730 // Get the address of the saved value by scaling the number of
3731 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003732 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003733 llvm::Value *RegOffset =
3734 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3735 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3736 RegAddr.getPointer(), RegOffset),
3737 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3738 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3739
3740 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003741 NumRegs =
3742 Builder.CreateAdd(NumRegs,
3743 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003744 Builder.CreateStore(NumRegs, NumRegsAddr);
3745
3746 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003747 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003748
John McCall7f416cc2015-09-08 08:05:57 +00003749 // Case 2: consume space in the overflow area.
3750 Address MemAddr = Address::invalid();
3751 {
3752 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003753
Roman Divacky039b9702016-02-20 08:31:24 +00003754 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3755
John McCall7f416cc2015-09-08 08:05:57 +00003756 // Everything in the overflow area is rounded up to a size of at least 4.
3757 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3758
3759 CharUnits Size;
3760 if (!isIndirect) {
3761 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003762 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003763 } else {
3764 Size = CGF.getPointerSize();
3765 }
3766
3767 Address OverflowAreaAddr =
3768 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003769 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003770 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003771 // Round up address of argument to alignment
3772 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3773 if (Align > OverflowAreaAlign) {
3774 llvm::Value *Ptr = OverflowArea.getPointer();
3775 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3776 Align);
3777 }
3778
John McCall7f416cc2015-09-08 08:05:57 +00003779 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3780
3781 // Increase the overflow area.
3782 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3783 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3784 CGF.EmitBranch(Cont);
3785 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003786
3787 CGF.EmitBlock(Cont);
3788
John McCall7f416cc2015-09-08 08:05:57 +00003789 // Merge the cases with a phi.
3790 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3791 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003792
John McCall7f416cc2015-09-08 08:05:57 +00003793 // Load the pointer if the argument was passed indirectly.
3794 if (isIndirect) {
3795 Result = Address(Builder.CreateLoad(Result, "aggr"),
3796 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003797 }
3798
3799 return Result;
3800}
3801
John McCallea8d8bb2010-03-11 00:10:12 +00003802bool
3803PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3804 llvm::Value *Address) const {
3805 // This is calculated from the LLVM and GCC tables and verified
3806 // against gcc output. AFAIK all ABIs use the same encoding.
3807
3808 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003809
Chris Lattnerece04092012-02-07 00:39:47 +00003810 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003811 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3812 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3813 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3814
3815 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003816 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003817
3818 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003819 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003820
3821 // 64-76 are various 4-byte special-purpose registers:
3822 // 64: mq
3823 // 65: lr
3824 // 66: ctr
3825 // 67: ap
3826 // 68-75 cr0-7
3827 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003828 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003829
3830 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003831 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003832
3833 // 109: vrsave
3834 // 110: vscr
3835 // 111: spe_acc
3836 // 112: spefscr
3837 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003838 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003839
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003840 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003841}
3842
Roman Divackyd966e722012-05-09 18:22:46 +00003843// PowerPC-64
3844
3845namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003846/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003847class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003848public:
3849 enum ABIKind {
3850 ELFv1 = 0,
3851 ELFv2
3852 };
3853
3854private:
3855 static const unsigned GPRBits = 64;
3856 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003857 bool HasQPX;
3858
3859 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3860 // will be passed in a QPX register.
3861 bool IsQPXVectorTy(const Type *Ty) const {
3862 if (!HasQPX)
3863 return false;
3864
3865 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3866 unsigned NumElements = VT->getNumElements();
3867 if (NumElements == 1)
3868 return false;
3869
3870 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3871 if (getContext().getTypeSize(Ty) <= 256)
3872 return true;
3873 } else if (VT->getElementType()->
3874 isSpecificBuiltinType(BuiltinType::Float)) {
3875 if (getContext().getTypeSize(Ty) <= 128)
3876 return true;
3877 }
3878 }
3879
3880 return false;
3881 }
3882
3883 bool IsQPXVectorTy(QualType Ty) const {
3884 return IsQPXVectorTy(Ty.getTypePtr());
3885 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003886
3887public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003888 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
James Y Knight29b5f082016-02-24 02:59:33 +00003889 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003890
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003891 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003892 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003893
3894 ABIArgInfo classifyReturnType(QualType RetTy) const;
3895 ABIArgInfo classifyArgumentType(QualType Ty) const;
3896
Reid Klecknere9f6a712014-10-31 17:10:41 +00003897 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3898 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3899 uint64_t Members) const override;
3900
Bill Schmidt84d37792012-10-12 19:26:17 +00003901 // TODO: We can add more logic to computeInfo to improve performance.
3902 // Example: For aggregate arguments that fit in a register, we could
3903 // use getDirectInReg (as is done below for structs containing a single
3904 // floating-point value) to avoid pushing them to memory on function
3905 // entry. This would require changing the logic in PPCISelLowering
3906 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003907 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003908 if (!getCXXABI().classifyReturnType(FI))
3909 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003910 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003911 // We rely on the default argument classification for the most part.
3912 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003913 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003914 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003915 if (T) {
3916 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003917 if (IsQPXVectorTy(T) ||
3918 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003919 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003920 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003921 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003922 continue;
3923 }
3924 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003925 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003926 }
3927 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003928
John McCall7f416cc2015-09-08 08:05:57 +00003929 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3930 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003931};
3932
3933class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003934
Bill Schmidt25cb3492012-10-03 19:18:57 +00003935public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003936 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003937 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003938 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003939
Craig Topper4f12f102014-03-12 06:41:41 +00003940 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003941 // This is recovered from gcc output.
3942 return 1; // r1 is the dedicated stack pointer
3943 }
3944
3945 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003946 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003947};
3948
Roman Divackyd966e722012-05-09 18:22:46 +00003949class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3950public:
3951 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3952
Craig Topper4f12f102014-03-12 06:41:41 +00003953 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003954 // This is recovered from gcc output.
3955 return 1; // r1 is the dedicated stack pointer
3956 }
3957
3958 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003959 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003960};
3961
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003962}
Roman Divackyd966e722012-05-09 18:22:46 +00003963
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003964// Return true if the ABI requires Ty to be passed sign- or zero-
3965// extended to 64 bits.
3966bool
3967PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3968 // Treat an enum type as its underlying type.
3969 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3970 Ty = EnumTy->getDecl()->getIntegerType();
3971
3972 // Promotable integer types are required to be promoted by the ABI.
3973 if (Ty->isPromotableIntegerType())
3974 return true;
3975
3976 // In addition to the usual promotable integer types, we also need to
3977 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3978 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3979 switch (BT->getKind()) {
3980 case BuiltinType::Int:
3981 case BuiltinType::UInt:
3982 return true;
3983 default:
3984 break;
3985 }
3986
3987 return false;
3988}
3989
John McCall7f416cc2015-09-08 08:05:57 +00003990/// isAlignedParamType - Determine whether a type requires 16-byte or
3991/// higher alignment in the parameter area. Always returns at least 8.
3992CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003993 // Complex types are passed just like their elements.
3994 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3995 Ty = CTy->getElementType();
3996
3997 // Only vector types of size 16 bytes need alignment (larger types are
3998 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003999 if (IsQPXVectorTy(Ty)) {
4000 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004001 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004002
John McCall7f416cc2015-09-08 08:05:57 +00004003 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004004 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004005 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004006 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004007
4008 // For single-element float/vector structs, we consider the whole type
4009 // to have the same alignment requirements as its single element.
4010 const Type *AlignAsType = nullptr;
4011 const Type *EltType = isSingleElementStruct(Ty, getContext());
4012 if (EltType) {
4013 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004014 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004015 getContext().getTypeSize(EltType) == 128) ||
4016 (BT && BT->isFloatingPoint()))
4017 AlignAsType = EltType;
4018 }
4019
Ulrich Weigandb7122372014-07-21 00:48:09 +00004020 // Likewise for ELFv2 homogeneous aggregates.
4021 const Type *Base = nullptr;
4022 uint64_t Members = 0;
4023 if (!AlignAsType && Kind == ELFv2 &&
4024 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4025 AlignAsType = Base;
4026
Ulrich Weigand581badc2014-07-10 17:20:07 +00004027 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004028 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4029 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004030 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004031
John McCall7f416cc2015-09-08 08:05:57 +00004032 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004033 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004034 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004035 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004036
4037 // Otherwise, we only need alignment for any aggregate type that
4038 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004039 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4040 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004041 return CharUnits::fromQuantity(32);
4042 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004043 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004044
John McCall7f416cc2015-09-08 08:05:57 +00004045 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004046}
4047
Ulrich Weigandb7122372014-07-21 00:48:09 +00004048/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4049/// aggregate. Base is set to the base element type, and Members is set
4050/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004051bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4052 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004053 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4054 uint64_t NElements = AT->getSize().getZExtValue();
4055 if (NElements == 0)
4056 return false;
4057 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4058 return false;
4059 Members *= NElements;
4060 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4061 const RecordDecl *RD = RT->getDecl();
4062 if (RD->hasFlexibleArrayMember())
4063 return false;
4064
4065 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004066
4067 // If this is a C++ record, check the bases first.
4068 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4069 for (const auto &I : CXXRD->bases()) {
4070 // Ignore empty records.
4071 if (isEmptyRecord(getContext(), I.getType(), true))
4072 continue;
4073
4074 uint64_t FldMembers;
4075 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4076 return false;
4077
4078 Members += FldMembers;
4079 }
4080 }
4081
Ulrich Weigandb7122372014-07-21 00:48:09 +00004082 for (const auto *FD : RD->fields()) {
4083 // Ignore (non-zero arrays of) empty records.
4084 QualType FT = FD->getType();
4085 while (const ConstantArrayType *AT =
4086 getContext().getAsConstantArrayType(FT)) {
4087 if (AT->getSize().getZExtValue() == 0)
4088 return false;
4089 FT = AT->getElementType();
4090 }
4091 if (isEmptyRecord(getContext(), FT, true))
4092 continue;
4093
4094 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4095 if (getContext().getLangOpts().CPlusPlus &&
4096 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4097 continue;
4098
4099 uint64_t FldMembers;
4100 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4101 return false;
4102
4103 Members = (RD->isUnion() ?
4104 std::max(Members, FldMembers) : Members + FldMembers);
4105 }
4106
4107 if (!Base)
4108 return false;
4109
4110 // Ensure there is no padding.
4111 if (getContext().getTypeSize(Base) * Members !=
4112 getContext().getTypeSize(Ty))
4113 return false;
4114 } else {
4115 Members = 1;
4116 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4117 Members = 2;
4118 Ty = CT->getElementType();
4119 }
4120
Reid Klecknere9f6a712014-10-31 17:10:41 +00004121 // Most ABIs only support float, double, and some vector type widths.
4122 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004123 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004124
4125 // The base type must be the same for all members. Types that
4126 // agree in both total size and mode (float vs. vector) are
4127 // treated as being equivalent here.
4128 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004129 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004130 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004131 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4132 // so make sure to widen it explicitly.
4133 if (const VectorType *VT = Base->getAs<VectorType>()) {
4134 QualType EltTy = VT->getElementType();
4135 unsigned NumElements =
4136 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4137 Base = getContext()
4138 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4139 .getTypePtr();
4140 }
4141 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004142
4143 if (Base->isVectorType() != TyPtr->isVectorType() ||
4144 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4145 return false;
4146 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004147 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4148}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004149
Reid Klecknere9f6a712014-10-31 17:10:41 +00004150bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4151 // Homogeneous aggregates for ELFv2 must have base types of float,
4152 // double, long double, or 128-bit vectors.
4153 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4154 if (BT->getKind() == BuiltinType::Float ||
4155 BT->getKind() == BuiltinType::Double ||
4156 BT->getKind() == BuiltinType::LongDouble)
4157 return true;
4158 }
4159 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004160 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004161 return true;
4162 }
4163 return false;
4164}
4165
4166bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4167 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004168 // Vector types require one register, floating point types require one
4169 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004170 uint32_t NumRegs =
4171 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004172
4173 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004174 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004175}
4176
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004177ABIArgInfo
4178PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004179 Ty = useFirstFieldIfTransparentUnion(Ty);
4180
Bill Schmidt90b22c92012-11-27 02:46:43 +00004181 if (Ty->isAnyComplexType())
4182 return ABIArgInfo::getDirect();
4183
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004184 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4185 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004186 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004187 uint64_t Size = getContext().getTypeSize(Ty);
4188 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004189 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004190 else if (Size < 128) {
4191 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4192 return ABIArgInfo::getDirect(CoerceTy);
4193 }
4194 }
4195
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004196 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004197 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004198 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004199
John McCall7f416cc2015-09-08 08:05:57 +00004200 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4201 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004202
4203 // ELFv2 homogeneous aggregates are passed as array types.
4204 const Type *Base = nullptr;
4205 uint64_t Members = 0;
4206 if (Kind == ELFv2 &&
4207 isHomogeneousAggregate(Ty, Base, Members)) {
4208 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4209 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4210 return ABIArgInfo::getDirect(CoerceTy);
4211 }
4212
Ulrich Weigand601957f2014-07-21 00:56:36 +00004213 // If an aggregate may end up fully in registers, we do not
4214 // use the ByVal method, but pass the aggregate as array.
4215 // This is usually beneficial since we avoid forcing the
4216 // back-end to store the argument to memory.
4217 uint64_t Bits = getContext().getTypeSize(Ty);
4218 if (Bits > 0 && Bits <= 8 * GPRBits) {
4219 llvm::Type *CoerceTy;
4220
4221 // Types up to 8 bytes are passed as integer type (which will be
4222 // properly aligned in the argument save area doubleword).
4223 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004224 CoerceTy =
4225 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004226 // Larger types are passed as arrays, with the base type selected
4227 // according to the required alignment in the save area.
4228 else {
4229 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004230 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004231 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4232 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4233 }
4234
4235 return ABIArgInfo::getDirect(CoerceTy);
4236 }
4237
Ulrich Weigandb7122372014-07-21 00:48:09 +00004238 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004239 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4240 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004241 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004242 }
4243
4244 return (isPromotableTypeForABI(Ty) ?
4245 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4246}
4247
4248ABIArgInfo
4249PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4250 if (RetTy->isVoidType())
4251 return ABIArgInfo::getIgnore();
4252
Bill Schmidta3d121c2012-12-17 04:20:17 +00004253 if (RetTy->isAnyComplexType())
4254 return ABIArgInfo::getDirect();
4255
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004256 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4257 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004258 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004259 uint64_t Size = getContext().getTypeSize(RetTy);
4260 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004261 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004262 else if (Size < 128) {
4263 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4264 return ABIArgInfo::getDirect(CoerceTy);
4265 }
4266 }
4267
Ulrich Weigandb7122372014-07-21 00:48:09 +00004268 if (isAggregateTypeForABI(RetTy)) {
4269 // ELFv2 homogeneous aggregates are returned as array types.
4270 const Type *Base = nullptr;
4271 uint64_t Members = 0;
4272 if (Kind == ELFv2 &&
4273 isHomogeneousAggregate(RetTy, Base, Members)) {
4274 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4275 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4276 return ABIArgInfo::getDirect(CoerceTy);
4277 }
4278
4279 // ELFv2 small aggregates are returned in up to two registers.
4280 uint64_t Bits = getContext().getTypeSize(RetTy);
4281 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4282 if (Bits == 0)
4283 return ABIArgInfo::getIgnore();
4284
4285 llvm::Type *CoerceTy;
4286 if (Bits > GPRBits) {
4287 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004288 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004289 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004290 CoerceTy =
4291 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004292 return ABIArgInfo::getDirect(CoerceTy);
4293 }
4294
4295 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004296 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004297 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004298
4299 return (isPromotableTypeForABI(RetTy) ?
4300 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4301}
4302
Bill Schmidt25cb3492012-10-03 19:18:57 +00004303// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004304Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4305 QualType Ty) const {
4306 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4307 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004308
John McCall7f416cc2015-09-08 08:05:57 +00004309 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004310
Bill Schmidt924c4782013-01-14 17:45:36 +00004311 // If we have a complex type and the base type is smaller than 8 bytes,
4312 // the ABI calls for the real and imaginary parts to be right-adjusted
4313 // in separate doublewords. However, Clang expects us to produce a
4314 // pointer to a structure with the two parts packed tightly. So generate
4315 // loads of the real and imaginary parts relative to the va_list pointer,
4316 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004317 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4318 CharUnits EltSize = TypeInfo.first / 2;
4319 if (EltSize < SlotSize) {
4320 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4321 SlotSize * 2, SlotSize,
4322 SlotSize, /*AllowHigher*/ true);
4323
4324 Address RealAddr = Addr;
4325 Address ImagAddr = RealAddr;
4326 if (CGF.CGM.getDataLayout().isBigEndian()) {
4327 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4328 SlotSize - EltSize);
4329 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4330 2 * SlotSize - EltSize);
4331 } else {
4332 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4333 }
4334
4335 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4336 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4337 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4338 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4339 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4340
4341 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4342 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4343 /*init*/ true);
4344 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004345 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004346 }
4347
John McCall7f416cc2015-09-08 08:05:57 +00004348 // Otherwise, just use the general rule.
4349 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4350 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004351}
4352
4353static bool
4354PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4355 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004356 // This is calculated from the LLVM and GCC tables and verified
4357 // against gcc output. AFAIK all ABIs use the same encoding.
4358
4359 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4360
4361 llvm::IntegerType *i8 = CGF.Int8Ty;
4362 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4363 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4364 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4365
4366 // 0-31: r0-31, the 8-byte general-purpose registers
4367 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4368
4369 // 32-63: fp0-31, the 8-byte floating-point registers
4370 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4371
4372 // 64-76 are various 4-byte special-purpose registers:
4373 // 64: mq
4374 // 65: lr
4375 // 66: ctr
4376 // 67: ap
4377 // 68-75 cr0-7
4378 // 76: xer
4379 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4380
4381 // 77-108: v0-31, the 16-byte vector registers
4382 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4383
4384 // 109: vrsave
4385 // 110: vscr
4386 // 111: spe_acc
4387 // 112: spefscr
4388 // 113: sfp
4389 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4390
4391 return false;
4392}
John McCallea8d8bb2010-03-11 00:10:12 +00004393
Bill Schmidt25cb3492012-10-03 19:18:57 +00004394bool
4395PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4396 CodeGen::CodeGenFunction &CGF,
4397 llvm::Value *Address) const {
4398
4399 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4400}
4401
4402bool
4403PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4404 llvm::Value *Address) const {
4405
4406 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4407}
4408
Chris Lattner0cf24192010-06-28 20:05:43 +00004409//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004410// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004411//===----------------------------------------------------------------------===//
4412
4413namespace {
4414
John McCall12f23522016-04-04 18:33:08 +00004415class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004416public:
4417 enum ABIKind {
4418 AAPCS = 0,
4419 DarwinPCS
4420 };
4421
4422private:
4423 ABIKind Kind;
4424
4425public:
John McCall12f23522016-04-04 18:33:08 +00004426 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4427 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004428
4429private:
4430 ABIKind getABIKind() const { return Kind; }
4431 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4432
4433 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004434 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004435 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4436 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4437 uint64_t Members) const override;
4438
Tim Northovera2ee4332014-03-29 15:09:45 +00004439 bool isIllegalVectorType(QualType Ty) const;
4440
David Blaikie1cbb9712014-11-14 19:09:44 +00004441 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004442 if (!getCXXABI().classifyReturnType(FI))
4443 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004444
Tim Northoverb047bfa2014-11-27 21:02:49 +00004445 for (auto &it : FI.arguments())
4446 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004447 }
4448
John McCall7f416cc2015-09-08 08:05:57 +00004449 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4450 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004451
John McCall7f416cc2015-09-08 08:05:57 +00004452 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4453 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004454
John McCall7f416cc2015-09-08 08:05:57 +00004455 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4456 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004457 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4458 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4459 }
John McCall12f23522016-04-04 18:33:08 +00004460
4461 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4462 ArrayRef<llvm::Type*> scalars,
4463 bool asReturnValue) const override {
4464 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4465 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004466};
4467
Tim Northover573cbee2014-05-24 12:52:07 +00004468class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004469public:
Tim Northover573cbee2014-05-24 12:52:07 +00004470 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4471 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004472
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004473 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004474 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4475 }
4476
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004477 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4478 return 31;
4479 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004480
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004481 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004482};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004483}
Tim Northovera2ee4332014-03-29 15:09:45 +00004484
Tim Northoverb047bfa2014-11-27 21:02:49 +00004485ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004486 Ty = useFirstFieldIfTransparentUnion(Ty);
4487
Tim Northovera2ee4332014-03-29 15:09:45 +00004488 // Handle illegal vector types here.
4489 if (isIllegalVectorType(Ty)) {
4490 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004491 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004492 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004493 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4494 return ABIArgInfo::getDirect(ResType);
4495 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004496 if (Size <= 32) {
4497 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004498 return ABIArgInfo::getDirect(ResType);
4499 }
4500 if (Size == 64) {
4501 llvm::Type *ResType =
4502 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004503 return ABIArgInfo::getDirect(ResType);
4504 }
4505 if (Size == 128) {
4506 llvm::Type *ResType =
4507 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004508 return ABIArgInfo::getDirect(ResType);
4509 }
John McCall7f416cc2015-09-08 08:05:57 +00004510 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004511 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004512
4513 if (!isAggregateTypeForABI(Ty)) {
4514 // Treat an enum type as its underlying type.
4515 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4516 Ty = EnumTy->getDecl()->getIntegerType();
4517
Tim Northovera2ee4332014-03-29 15:09:45 +00004518 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4519 ? ABIArgInfo::getExtend()
4520 : ABIArgInfo::getDirect());
4521 }
4522
4523 // Structures with either a non-trivial destructor or a non-trivial
4524 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004525 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004526 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4527 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004528 }
4529
4530 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4531 // elsewhere for GNU compatibility.
4532 if (isEmptyRecord(getContext(), Ty, true)) {
4533 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4534 return ABIArgInfo::getIgnore();
4535
Tim Northovera2ee4332014-03-29 15:09:45 +00004536 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4537 }
4538
4539 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004540 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004541 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004542 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004543 return ABIArgInfo::getDirect(
4544 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004545 }
4546
4547 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4548 uint64_t Size = getContext().getTypeSize(Ty);
4549 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004550 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004551 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004552
Tim Northovera2ee4332014-03-29 15:09:45 +00004553 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4554 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004555 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004556 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4557 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4558 }
4559 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4560 }
4561
John McCall7f416cc2015-09-08 08:05:57 +00004562 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004563}
4564
Tim Northover573cbee2014-05-24 12:52:07 +00004565ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004566 if (RetTy->isVoidType())
4567 return ABIArgInfo::getIgnore();
4568
4569 // Large vector types should be returned via memory.
4570 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004571 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004572
4573 if (!isAggregateTypeForABI(RetTy)) {
4574 // Treat an enum type as its underlying type.
4575 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4576 RetTy = EnumTy->getDecl()->getIntegerType();
4577
Tim Northover4dab6982014-04-18 13:46:08 +00004578 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4579 ? ABIArgInfo::getExtend()
4580 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004581 }
4582
Tim Northovera2ee4332014-03-29 15:09:45 +00004583 if (isEmptyRecord(getContext(), RetTy, true))
4584 return ABIArgInfo::getIgnore();
4585
Craig Topper8a13c412014-05-21 05:09:00 +00004586 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004587 uint64_t Members = 0;
4588 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004589 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4590 return ABIArgInfo::getDirect();
4591
4592 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4593 uint64_t Size = getContext().getTypeSize(RetTy);
4594 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004595 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004596 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004597
4598 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4599 // For aggregates with 16-byte alignment, we use i128.
4600 if (Alignment < 128 && Size == 128) {
4601 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4602 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4603 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004604 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4605 }
4606
John McCall7f416cc2015-09-08 08:05:57 +00004607 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004608}
4609
Tim Northover573cbee2014-05-24 12:52:07 +00004610/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4611bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004612 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4613 // Check whether VT is legal.
4614 unsigned NumElements = VT->getNumElements();
4615 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004616 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004617 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004618 return true;
4619 return Size != 64 && (Size != 128 || NumElements == 1);
4620 }
4621 return false;
4622}
4623
Reid Klecknere9f6a712014-10-31 17:10:41 +00004624bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4625 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4626 // point type or a short-vector type. This is the same as the 32-bit ABI,
4627 // but with the difference that any floating-point type is allowed,
4628 // including __fp16.
4629 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4630 if (BT->isFloatingPoint())
4631 return true;
4632 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4633 unsigned VecSize = getContext().getTypeSize(VT);
4634 if (VecSize == 64 || VecSize == 128)
4635 return true;
4636 }
4637 return false;
4638}
4639
4640bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4641 uint64_t Members) const {
4642 return Members <= 4;
4643}
4644
John McCall7f416cc2015-09-08 08:05:57 +00004645Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004646 QualType Ty,
4647 CodeGenFunction &CGF) const {
4648 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004649 bool IsIndirect = AI.isIndirect();
4650
Tim Northoverb047bfa2014-11-27 21:02:49 +00004651 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4652 if (IsIndirect)
4653 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4654 else if (AI.getCoerceToType())
4655 BaseTy = AI.getCoerceToType();
4656
4657 unsigned NumRegs = 1;
4658 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4659 BaseTy = ArrTy->getElementType();
4660 NumRegs = ArrTy->getNumElements();
4661 }
4662 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4663
Tim Northovera2ee4332014-03-29 15:09:45 +00004664 // The AArch64 va_list type and handling is specified in the Procedure Call
4665 // Standard, section B.4:
4666 //
4667 // struct {
4668 // void *__stack;
4669 // void *__gr_top;
4670 // void *__vr_top;
4671 // int __gr_offs;
4672 // int __vr_offs;
4673 // };
4674
4675 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4676 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4677 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4678 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004679
John McCall7f416cc2015-09-08 08:05:57 +00004680 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4681 CharUnits TyAlign = TyInfo.second;
4682
4683 Address reg_offs_p = Address::invalid();
4684 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004685 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004686 CharUnits reg_top_offset;
4687 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004688 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004689 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004690 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004691 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4692 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004693 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4694 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004695 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004696 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004697 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004699 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004700 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4701 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004702 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4703 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004704 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004705 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004706 }
4707
4708 //=======================================
4709 // Find out where argument was passed
4710 //=======================================
4711
4712 // If reg_offs >= 0 we're already using the stack for this type of
4713 // argument. We don't want to keep updating reg_offs (in case it overflows,
4714 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4715 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004716 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004717 UsingStack = CGF.Builder.CreateICmpSGE(
4718 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4719
4720 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4721
4722 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004723 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004724 CGF.EmitBlock(MaybeRegBlock);
4725
4726 // Integer arguments may need to correct register alignment (for example a
4727 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4728 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004729 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4730 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004731
4732 reg_offs = CGF.Builder.CreateAdd(
4733 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4734 "align_regoffs");
4735 reg_offs = CGF.Builder.CreateAnd(
4736 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4737 "aligned_regoffs");
4738 }
4739
4740 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004741 // The fact that this is done unconditionally reflects the fact that
4742 // allocating an argument to the stack also uses up all the remaining
4743 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004744 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004745 NewOffset = CGF.Builder.CreateAdd(
4746 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4747 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4748
4749 // Now we're in a position to decide whether this argument really was in
4750 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004751 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004752 InRegs = CGF.Builder.CreateICmpSLE(
4753 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4754
4755 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4756
4757 //=======================================
4758 // Argument was in registers
4759 //=======================================
4760
4761 // Now we emit the code for if the argument was originally passed in
4762 // registers. First start the appropriate block:
4763 CGF.EmitBlock(InRegBlock);
4764
John McCall7f416cc2015-09-08 08:05:57 +00004765 llvm::Value *reg_top = nullptr;
4766 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4767 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004768 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004769 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4770 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4771 Address RegAddr = Address::invalid();
4772 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004773
4774 if (IsIndirect) {
4775 // If it's been passed indirectly (actually a struct), whatever we find from
4776 // stored registers or on the stack will actually be a struct **.
4777 MemTy = llvm::PointerType::getUnqual(MemTy);
4778 }
4779
Craig Topper8a13c412014-05-21 05:09:00 +00004780 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004781 uint64_t NumMembers = 0;
4782 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004783 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004784 // Homogeneous aggregates passed in registers will have their elements split
4785 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4786 // qN+1, ...). We reload and store into a temporary local variable
4787 // contiguously.
4788 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004789 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004790 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4791 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004792 Address Tmp = CGF.CreateTempAlloca(HFATy,
4793 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004794
John McCall7f416cc2015-09-08 08:05:57 +00004795 // On big-endian platforms, the value will be right-aligned in its slot.
4796 int Offset = 0;
4797 if (CGF.CGM.getDataLayout().isBigEndian() &&
4798 BaseTyInfo.first.getQuantity() < 16)
4799 Offset = 16 - BaseTyInfo.first.getQuantity();
4800
Tim Northovera2ee4332014-03-29 15:09:45 +00004801 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004802 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4803 Address LoadAddr =
4804 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4805 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4806
4807 Address StoreAddr =
4808 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004809
4810 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4811 CGF.Builder.CreateStore(Elem, StoreAddr);
4812 }
4813
John McCall7f416cc2015-09-08 08:05:57 +00004814 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004815 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004816 // Otherwise the object is contiguous in memory.
4817
4818 // It might be right-aligned in its slot.
4819 CharUnits SlotSize = BaseAddr.getAlignment();
4820 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004821 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004822 TyInfo.first < SlotSize) {
4823 CharUnits Offset = SlotSize - TyInfo.first;
4824 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004825 }
4826
John McCall7f416cc2015-09-08 08:05:57 +00004827 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004828 }
4829
4830 CGF.EmitBranch(ContBlock);
4831
4832 //=======================================
4833 // Argument was on the stack
4834 //=======================================
4835 CGF.EmitBlock(OnStackBlock);
4836
John McCall7f416cc2015-09-08 08:05:57 +00004837 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4838 CharUnits::Zero(), "stack_p");
4839 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004840
John McCall7f416cc2015-09-08 08:05:57 +00004841 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004842 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004843 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4844 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004845
John McCall7f416cc2015-09-08 08:05:57 +00004846 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004847
John McCall7f416cc2015-09-08 08:05:57 +00004848 OnStackPtr = CGF.Builder.CreateAdd(
4849 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004850 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004851 OnStackPtr = CGF.Builder.CreateAnd(
4852 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004853 "align_stack");
4854
John McCall7f416cc2015-09-08 08:05:57 +00004855 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004856 }
John McCall7f416cc2015-09-08 08:05:57 +00004857 Address OnStackAddr(OnStackPtr,
4858 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004859
John McCall7f416cc2015-09-08 08:05:57 +00004860 // All stack slots are multiples of 8 bytes.
4861 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4862 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004863 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004864 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004865 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004866 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004867
John McCall7f416cc2015-09-08 08:05:57 +00004868 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004869 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004870 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004871
4872 // Write the new value of __stack for the next call to va_arg
4873 CGF.Builder.CreateStore(NewStack, stack_p);
4874
4875 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004876 TyInfo.first < StackSlotSize) {
4877 CharUnits Offset = StackSlotSize - TyInfo.first;
4878 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004879 }
4880
John McCall7f416cc2015-09-08 08:05:57 +00004881 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004882
4883 CGF.EmitBranch(ContBlock);
4884
4885 //=======================================
4886 // Tidy up
4887 //=======================================
4888 CGF.EmitBlock(ContBlock);
4889
John McCall7f416cc2015-09-08 08:05:57 +00004890 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4891 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004892
4893 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004894 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4895 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004896
4897 return ResAddr;
4898}
4899
John McCall7f416cc2015-09-08 08:05:57 +00004900Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4901 CodeGenFunction &CGF) const {
4902 // The backend's lowering doesn't support va_arg for aggregates or
4903 // illegal vector types. Lower VAArg here for these cases and use
4904 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004905 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004906 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004907
John McCall7f416cc2015-09-08 08:05:57 +00004908 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004909
John McCall7f416cc2015-09-08 08:05:57 +00004910 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004911 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004912 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4913 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4914 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004915 }
4916
John McCall7f416cc2015-09-08 08:05:57 +00004917 // The size of the actual thing passed, which might end up just
4918 // being a pointer for indirect types.
4919 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4920
4921 // Arguments bigger than 16 bytes which aren't homogeneous
4922 // aggregates should be passed indirectly.
4923 bool IsIndirect = false;
4924 if (TyInfo.first.getQuantity() > 16) {
4925 const Type *Base = nullptr;
4926 uint64_t Members = 0;
4927 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004928 }
4929
John McCall7f416cc2015-09-08 08:05:57 +00004930 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4931 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004932}
4933
4934//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004935// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004936//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004937
4938namespace {
4939
John McCall12f23522016-04-04 18:33:08 +00004940class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004941public:
4942 enum ABIKind {
4943 APCS = 0,
4944 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004945 AAPCS_VFP = 2,
4946 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004947 };
4948
4949private:
4950 ABIKind Kind;
4951
4952public:
John McCall12f23522016-04-04 18:33:08 +00004953 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
4954 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004955 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004956 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004957
John McCall3480ef22011-08-30 01:42:09 +00004958 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004959 switch (getTarget().getTriple().getEnvironment()) {
4960 case llvm::Triple::Android:
4961 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004962 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004963 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004964 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004965 return true;
4966 default:
4967 return false;
4968 }
John McCall3480ef22011-08-30 01:42:09 +00004969 }
4970
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004971 bool isEABIHF() const {
4972 switch (getTarget().getTriple().getEnvironment()) {
4973 case llvm::Triple::EABIHF:
4974 case llvm::Triple::GNUEABIHF:
4975 return true;
4976 default:
4977 return false;
4978 }
4979 }
4980
Daniel Dunbar020daa92009-09-12 01:00:39 +00004981 ABIKind getABIKind() const { return Kind; }
4982
Tim Northovera484bc02013-10-01 14:34:25 +00004983private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004984 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004985 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004986 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004987
Reid Klecknere9f6a712014-10-31 17:10:41 +00004988 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4989 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4990 uint64_t Members) const override;
4991
Craig Topper4f12f102014-03-12 06:41:41 +00004992 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004993
John McCall7f416cc2015-09-08 08:05:57 +00004994 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4995 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004996
4997 llvm::CallingConv::ID getLLVMDefaultCC() const;
4998 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004999 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005000
5001 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5002 ArrayRef<llvm::Type*> scalars,
5003 bool asReturnValue) const override {
5004 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5005 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005006};
5007
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005008class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5009public:
Chris Lattner2b037972010-07-29 02:01:43 +00005010 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5011 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005012
John McCall3480ef22011-08-30 01:42:09 +00005013 const ARMABIInfo &getABIInfo() const {
5014 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5015 }
5016
Craig Topper4f12f102014-03-12 06:41:41 +00005017 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005018 return 13;
5019 }
Roman Divackyc1617352011-05-18 19:36:54 +00005020
Craig Topper4f12f102014-03-12 06:41:41 +00005021 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005022 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5023 }
5024
Roman Divackyc1617352011-05-18 19:36:54 +00005025 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005026 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005027 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005028
5029 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005030 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005031 return false;
5032 }
John McCall3480ef22011-08-30 01:42:09 +00005033
Craig Topper4f12f102014-03-12 06:41:41 +00005034 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005035 if (getABIInfo().isEABI()) return 88;
5036 return TargetCodeGenInfo::getSizeOfUnwindException();
5037 }
Tim Northovera484bc02013-10-01 14:34:25 +00005038
Eric Christopher162c91c2015-06-05 22:03:00 +00005039 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005040 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005041 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005042 if (!FD)
5043 return;
5044
5045 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5046 if (!Attr)
5047 return;
5048
5049 const char *Kind;
5050 switch (Attr->getInterrupt()) {
5051 case ARMInterruptAttr::Generic: Kind = ""; break;
5052 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5053 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5054 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5055 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5056 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5057 }
5058
5059 llvm::Function *Fn = cast<llvm::Function>(GV);
5060
5061 Fn->addFnAttr("interrupt", Kind);
5062
Tim Northover5627d392015-10-30 16:30:45 +00005063 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5064 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005065 return;
5066
5067 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5068 // however this is not necessarily true on taking any interrupt. Instruct
5069 // the backend to perform a realignment as part of the function prologue.
5070 llvm::AttrBuilder B;
5071 B.addStackAlignmentAttr(8);
5072 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5073 llvm::AttributeSet::get(CGM.getLLVMContext(),
5074 llvm::AttributeSet::FunctionIndex,
5075 B));
5076 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005077};
5078
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005079class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005080public:
5081 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5082 : ARMTargetCodeGenInfo(CGT, K) {}
5083
Eric Christopher162c91c2015-06-05 22:03:00 +00005084 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005085 CodeGen::CodeGenModule &CGM) const override;
5086};
5087
Eric Christopher162c91c2015-06-05 22:03:00 +00005088void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005089 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005090 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005091 addStackProbeSizeTargetAttribute(D, GV, CGM);
5092}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005093}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005094
Chris Lattner22326a12010-07-29 02:31:05 +00005095void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005096 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005097 FI.getReturnInfo() =
5098 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005099
Tim Northoverbc784d12015-02-24 17:22:40 +00005100 for (auto &I : FI.arguments())
5101 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005102
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005103 // Always honor user-specified calling convention.
5104 if (FI.getCallingConvention() != llvm::CallingConv::C)
5105 return;
5106
John McCall882987f2013-02-28 19:01:20 +00005107 llvm::CallingConv::ID cc = getRuntimeCC();
5108 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005109 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005110}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005111
John McCall882987f2013-02-28 19:01:20 +00005112/// Return the default calling convention that LLVM will use.
5113llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5114 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005115 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005116 return llvm::CallingConv::ARM_AAPCS_VFP;
5117 else if (isEABI())
5118 return llvm::CallingConv::ARM_AAPCS;
5119 else
5120 return llvm::CallingConv::ARM_APCS;
5121}
5122
5123/// Return the calling convention that our ABI would like us to use
5124/// as the C calling convention.
5125llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005126 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005127 case APCS: return llvm::CallingConv::ARM_APCS;
5128 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5129 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005130 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005131 }
John McCall882987f2013-02-28 19:01:20 +00005132 llvm_unreachable("bad ABI kind");
5133}
5134
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005135void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005136 assert(getRuntimeCC() == llvm::CallingConv::C);
5137
5138 // Don't muddy up the IR with a ton of explicit annotations if
5139 // they'd just match what LLVM will infer from the triple.
5140 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5141 if (abiCC != getLLVMDefaultCC())
5142 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005143
Tim Northover5627d392015-10-30 16:30:45 +00005144 // AAPCS apparently requires runtime support functions to be soft-float, but
5145 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5146 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5147 switch (getABIKind()) {
5148 case APCS:
5149 case AAPCS16_VFP:
5150 if (abiCC != getLLVMDefaultCC())
5151 BuiltinCC = abiCC;
5152 break;
5153 case AAPCS:
5154 case AAPCS_VFP:
5155 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5156 break;
5157 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005158}
5159
Tim Northoverbc784d12015-02-24 17:22:40 +00005160ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5161 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005162 // 6.1.2.1 The following argument types are VFP CPRCs:
5163 // A single-precision floating-point type (including promoted
5164 // half-precision types); A double-precision floating-point type;
5165 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5166 // with a Base Type of a single- or double-precision floating-point type,
5167 // 64-bit containerized vectors or 128-bit containerized vectors with one
5168 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005169 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005170
Reid Klecknerb1be6832014-11-15 01:41:41 +00005171 Ty = useFirstFieldIfTransparentUnion(Ty);
5172
Manman Renfef9e312012-10-16 19:18:39 +00005173 // Handle illegal vector types here.
5174 if (isIllegalVectorType(Ty)) {
5175 uint64_t Size = getContext().getTypeSize(Ty);
5176 if (Size <= 32) {
5177 llvm::Type *ResType =
5178 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005179 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005180 }
5181 if (Size == 64) {
5182 llvm::Type *ResType = llvm::VectorType::get(
5183 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005184 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005185 }
5186 if (Size == 128) {
5187 llvm::Type *ResType = llvm::VectorType::get(
5188 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005189 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005190 }
John McCall7f416cc2015-09-08 08:05:57 +00005191 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005192 }
5193
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005194 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5195 // unspecified. This is not done for OpenCL as it handles the half type
5196 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005197 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005198 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5199 llvm::Type::getFloatTy(getVMContext()) :
5200 llvm::Type::getInt32Ty(getVMContext());
5201 return ABIArgInfo::getDirect(ResType);
5202 }
5203
John McCalla1dee5302010-08-22 10:59:02 +00005204 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005205 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005206 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005207 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005208 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005209
Tim Northover5a1558e2014-11-07 22:30:50 +00005210 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5211 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005212 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005213
Oliver Stannard405bded2014-02-11 09:25:50 +00005214 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005215 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005216 }
Tim Northover1060eae2013-06-21 22:49:34 +00005217
Daniel Dunbar09d33622009-09-14 21:54:03 +00005218 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005219 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005220 return ABIArgInfo::getIgnore();
5221
Tim Northover5a1558e2014-11-07 22:30:50 +00005222 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005223 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5224 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005225 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005226 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005227 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005228 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005229 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005230 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005231 }
Tim Northover5627d392015-10-30 16:30:45 +00005232 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5233 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5234 // this convention even for a variadic function: the backend will use GPRs
5235 // if needed.
5236 const Type *Base = nullptr;
5237 uint64_t Members = 0;
5238 if (isHomogeneousAggregate(Ty, Base, Members)) {
5239 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5240 llvm::Type *Ty =
5241 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5242 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5243 }
5244 }
5245
5246 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5247 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5248 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5249 // bigger than 128-bits, they get placed in space allocated by the caller,
5250 // and a pointer is passed.
5251 return ABIArgInfo::getIndirect(
5252 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005253 }
5254
Manman Ren6c30e132012-08-13 21:23:55 +00005255 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005256 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5257 // most 8-byte. We realign the indirect argument if type alignment is bigger
5258 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005259 uint64_t ABIAlign = 4;
5260 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5261 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005262 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005263 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005264
Manman Ren8cd99812012-11-06 04:58:01 +00005265 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005266 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005267 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5268 /*ByVal=*/true,
5269 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005270 }
5271
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005272 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005273 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005274 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005275 // FIXME: Try to match the types of the arguments more accurately where
5276 // we can.
5277 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005278 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5279 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005280 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005281 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5282 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005283 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005284
Tim Northover5a1558e2014-11-07 22:30:50 +00005285 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005286}
5287
Chris Lattner458b2aa2010-07-29 02:16:43 +00005288static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005289 llvm::LLVMContext &VMContext) {
5290 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5291 // is called integer-like if its size is less than or equal to one word, and
5292 // the offset of each of its addressable sub-fields is zero.
5293
5294 uint64_t Size = Context.getTypeSize(Ty);
5295
5296 // Check that the type fits in a word.
5297 if (Size > 32)
5298 return false;
5299
5300 // FIXME: Handle vector types!
5301 if (Ty->isVectorType())
5302 return false;
5303
Daniel Dunbard53bac72009-09-14 02:20:34 +00005304 // Float types are never treated as "integer like".
5305 if (Ty->isRealFloatingType())
5306 return false;
5307
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005308 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005309 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005310 return true;
5311
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005312 // Small complex integer types are "integer like".
5313 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5314 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005315
5316 // Single element and zero sized arrays should be allowed, by the definition
5317 // above, but they are not.
5318
5319 // Otherwise, it must be a record type.
5320 const RecordType *RT = Ty->getAs<RecordType>();
5321 if (!RT) return false;
5322
5323 // Ignore records with flexible arrays.
5324 const RecordDecl *RD = RT->getDecl();
5325 if (RD->hasFlexibleArrayMember())
5326 return false;
5327
5328 // Check that all sub-fields are at offset 0, and are themselves "integer
5329 // like".
5330 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5331
5332 bool HadField = false;
5333 unsigned idx = 0;
5334 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5335 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005336 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005337
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005338 // Bit-fields are not addressable, we only need to verify they are "integer
5339 // like". We still have to disallow a subsequent non-bitfield, for example:
5340 // struct { int : 0; int x }
5341 // is non-integer like according to gcc.
5342 if (FD->isBitField()) {
5343 if (!RD->isUnion())
5344 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005345
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005346 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5347 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005348
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005349 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005350 }
5351
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005352 // Check if this field is at offset 0.
5353 if (Layout.getFieldOffset(idx) != 0)
5354 return false;
5355
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005356 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5357 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005358
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005359 // Only allow at most one field in a structure. This doesn't match the
5360 // wording above, but follows gcc in situations with a field following an
5361 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005362 if (!RD->isUnion()) {
5363 if (HadField)
5364 return false;
5365
5366 HadField = true;
5367 }
5368 }
5369
5370 return true;
5371}
5372
Oliver Stannard405bded2014-02-11 09:25:50 +00005373ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5374 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005375 bool IsEffectivelyAAPCS_VFP =
5376 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005377
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005378 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005379 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005380
Daniel Dunbar19964db2010-09-23 01:54:32 +00005381 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005382 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005383 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005384 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005385
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005386 // __fp16 gets returned as if it were an int or float, but with the top 16
5387 // bits unspecified. This is not done for OpenCL as it handles the half type
5388 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005389 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005390 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5391 llvm::Type::getFloatTy(getVMContext()) :
5392 llvm::Type::getInt32Ty(getVMContext());
5393 return ABIArgInfo::getDirect(ResType);
5394 }
5395
John McCalla1dee5302010-08-22 10:59:02 +00005396 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005397 // Treat an enum type as its underlying type.
5398 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5399 RetTy = EnumTy->getDecl()->getIntegerType();
5400
Tim Northover5a1558e2014-11-07 22:30:50 +00005401 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5402 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005403 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005404
5405 // Are we following APCS?
5406 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005407 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005408 return ABIArgInfo::getIgnore();
5409
Daniel Dunbareedf1512010-02-01 23:31:19 +00005410 // Complex types are all returned as packed integers.
5411 //
5412 // FIXME: Consider using 2 x vector types if the back end handles them
5413 // correctly.
5414 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005415 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5416 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005417
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005418 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005419 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005420 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005421 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005422 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005423 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005424 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005425 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5426 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005427 }
5428
5429 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005430 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005431 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005432
5433 // Otherwise this is an AAPCS variant.
5434
Chris Lattner458b2aa2010-07-29 02:16:43 +00005435 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005436 return ABIArgInfo::getIgnore();
5437
Bob Wilson1d9269a2011-11-02 04:51:36 +00005438 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005439 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005440 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005441 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005442 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005443 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005444 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005445 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005446 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005447 }
5448
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005449 // Aggregates <= 4 bytes are returned in r0; other aggregates
5450 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005451 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005452 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005453 if (getDataLayout().isBigEndian())
5454 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005455 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005456
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005457 // Return in the smallest viable integer type.
5458 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005459 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005460 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005461 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5462 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005463 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5464 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5465 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005466 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005467 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005468 }
5469
John McCall7f416cc2015-09-08 08:05:57 +00005470 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005471}
5472
Manman Renfef9e312012-10-16 19:18:39 +00005473/// isIllegalVector - check whether Ty is an illegal vector type.
5474bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005475 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5476 if (isAndroid()) {
5477 // Android shipped using Clang 3.1, which supported a slightly different
5478 // vector ABI. The primary differences were that 3-element vector types
5479 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5480 // accepts that legacy behavior for Android only.
5481 // Check whether VT is legal.
5482 unsigned NumElements = VT->getNumElements();
5483 // NumElements should be power of 2 or equal to 3.
5484 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5485 return true;
5486 } else {
5487 // Check whether VT is legal.
5488 unsigned NumElements = VT->getNumElements();
5489 uint64_t Size = getContext().getTypeSize(VT);
5490 // NumElements should be power of 2.
5491 if (!llvm::isPowerOf2_32(NumElements))
5492 return true;
5493 // Size should be greater than 32 bits.
5494 return Size <= 32;
5495 }
Manman Renfef9e312012-10-16 19:18:39 +00005496 }
5497 return false;
5498}
5499
Reid Klecknere9f6a712014-10-31 17:10:41 +00005500bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5501 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5502 // double, or 64-bit or 128-bit vectors.
5503 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5504 if (BT->getKind() == BuiltinType::Float ||
5505 BT->getKind() == BuiltinType::Double ||
5506 BT->getKind() == BuiltinType::LongDouble)
5507 return true;
5508 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5509 unsigned VecSize = getContext().getTypeSize(VT);
5510 if (VecSize == 64 || VecSize == 128)
5511 return true;
5512 }
5513 return false;
5514}
5515
5516bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5517 uint64_t Members) const {
5518 return Members <= 4;
5519}
5520
John McCall7f416cc2015-09-08 08:05:57 +00005521Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5522 QualType Ty) const {
5523 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005524
John McCall7f416cc2015-09-08 08:05:57 +00005525 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005526 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005527 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5528 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5529 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005530 }
5531
John McCall7f416cc2015-09-08 08:05:57 +00005532 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5533 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005534
John McCall7f416cc2015-09-08 08:05:57 +00005535 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5536 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005537 const Type *Base = nullptr;
5538 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005539 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5540 IsIndirect = true;
5541
Tim Northover5627d392015-10-30 16:30:45 +00005542 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5543 // allocated by the caller.
5544 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5545 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5546 !isHomogeneousAggregate(Ty, Base, Members)) {
5547 IsIndirect = true;
5548
John McCall7f416cc2015-09-08 08:05:57 +00005549 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005550 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5551 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005552 // Our callers should be prepared to handle an under-aligned address.
5553 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5554 getABIKind() == ARMABIInfo::AAPCS) {
5555 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5556 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005557 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5558 // ARMv7k allows type alignment up to 16 bytes.
5559 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5560 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005561 } else {
5562 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005563 }
John McCall7f416cc2015-09-08 08:05:57 +00005564 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005565
John McCall7f416cc2015-09-08 08:05:57 +00005566 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5567 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005568}
5569
Chris Lattner0cf24192010-06-28 20:05:43 +00005570//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005571// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005572//===----------------------------------------------------------------------===//
5573
5574namespace {
5575
Justin Holewinski83e96682012-05-24 17:43:12 +00005576class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005577public:
Justin Holewinski36837432013-03-30 14:38:24 +00005578 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005579
5580 ABIArgInfo classifyReturnType(QualType RetTy) const;
5581 ABIArgInfo classifyArgumentType(QualType Ty) const;
5582
Craig Topper4f12f102014-03-12 06:41:41 +00005583 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005584 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5585 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005586};
5587
Justin Holewinski83e96682012-05-24 17:43:12 +00005588class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005589public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005590 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5591 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005592
Eric Christopher162c91c2015-06-05 22:03:00 +00005593 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005594 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005595private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005596 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5597 // resulting MDNode to the nvvm.annotations MDNode.
5598 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005599};
5600
Justin Holewinski83e96682012-05-24 17:43:12 +00005601ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005602 if (RetTy->isVoidType())
5603 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005604
5605 // note: this is different from default ABI
5606 if (!RetTy->isScalarType())
5607 return ABIArgInfo::getDirect();
5608
5609 // Treat an enum type as its underlying type.
5610 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5611 RetTy = EnumTy->getDecl()->getIntegerType();
5612
5613 return (RetTy->isPromotableIntegerType() ?
5614 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005615}
5616
Justin Holewinski83e96682012-05-24 17:43:12 +00005617ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005618 // Treat an enum type as its underlying type.
5619 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5620 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005621
Eli Bendersky95338a02014-10-29 13:43:21 +00005622 // Return aggregates type as indirect by value
5623 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005624 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005625
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005626 return (Ty->isPromotableIntegerType() ?
5627 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005628}
5629
Justin Holewinski83e96682012-05-24 17:43:12 +00005630void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005631 if (!getCXXABI().classifyReturnType(FI))
5632 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005633 for (auto &I : FI.arguments())
5634 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005635
5636 // Always honor user-specified calling convention.
5637 if (FI.getCallingConvention() != llvm::CallingConv::C)
5638 return;
5639
John McCall882987f2013-02-28 19:01:20 +00005640 FI.setEffectiveCallingConvention(getRuntimeCC());
5641}
5642
John McCall7f416cc2015-09-08 08:05:57 +00005643Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5644 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005645 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005646}
5647
Justin Holewinski83e96682012-05-24 17:43:12 +00005648void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005649setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005650 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005651 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005652 if (!FD) return;
5653
5654 llvm::Function *F = cast<llvm::Function>(GV);
5655
5656 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005657 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005658 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005659 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005660 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005661 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005662 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5663 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005664 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005665 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005666 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005667 }
Justin Holewinski38031972011-10-05 17:58:44 +00005668
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005669 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005670 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005671 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005672 // __global__ functions cannot be called from the device, we do not
5673 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005674 if (FD->hasAttr<CUDAGlobalAttr>()) {
5675 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5676 addNVVMMetadata(F, "kernel", 1);
5677 }
Artem Belevich7093e402015-04-21 22:55:54 +00005678 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005679 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005680 llvm::APSInt MaxThreads(32);
5681 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5682 if (MaxThreads > 0)
5683 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5684
5685 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5686 // not specified in __launch_bounds__ or if the user specified a 0 value,
5687 // we don't have to add a PTX directive.
5688 if (Attr->getMinBlocks()) {
5689 llvm::APSInt MinBlocks(32);
5690 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5691 if (MinBlocks > 0)
5692 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5693 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005694 }
5695 }
Justin Holewinski38031972011-10-05 17:58:44 +00005696 }
5697}
5698
Eli Benderskye06a2c42014-04-15 16:57:05 +00005699void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5700 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005701 llvm::Module *M = F->getParent();
5702 llvm::LLVMContext &Ctx = M->getContext();
5703
5704 // Get "nvvm.annotations" metadata node
5705 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5706
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005707 llvm::Metadata *MDVals[] = {
5708 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5709 llvm::ConstantAsMetadata::get(
5710 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005711 // Append metadata to nvvm.annotations
5712 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5713}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005714}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005715
5716//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005717// SystemZ ABI Implementation
5718//===----------------------------------------------------------------------===//
5719
5720namespace {
5721
Bryan Chane3f1ed52016-04-28 13:56:43 +00005722class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005723 bool HasVector;
5724
Ulrich Weigand47445072013-05-06 16:26:41 +00005725public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005726 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005727 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005728
5729 bool isPromotableIntegerType(QualType Ty) const;
5730 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005731 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005732 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005733 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005734
5735 ABIArgInfo classifyReturnType(QualType RetTy) const;
5736 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5737
Craig Topper4f12f102014-03-12 06:41:41 +00005738 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005739 if (!getCXXABI().classifyReturnType(FI))
5740 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005741 for (auto &I : FI.arguments())
5742 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005743 }
5744
John McCall7f416cc2015-09-08 08:05:57 +00005745 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5746 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005747
5748 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5749 ArrayRef<llvm::Type*> scalars,
5750 bool asReturnValue) const override {
5751 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5752 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005753};
5754
5755class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5756public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005757 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5758 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005759};
5760
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005761}
Ulrich Weigand47445072013-05-06 16:26:41 +00005762
5763bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5764 // Treat an enum type as its underlying type.
5765 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5766 Ty = EnumTy->getDecl()->getIntegerType();
5767
5768 // Promotable integer types are required to be promoted by the ABI.
5769 if (Ty->isPromotableIntegerType())
5770 return true;
5771
5772 // 32-bit values must also be promoted.
5773 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5774 switch (BT->getKind()) {
5775 case BuiltinType::Int:
5776 case BuiltinType::UInt:
5777 return true;
5778 default:
5779 return false;
5780 }
5781 return false;
5782}
5783
5784bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005785 return (Ty->isAnyComplexType() ||
5786 Ty->isVectorType() ||
5787 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005788}
5789
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005790bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5791 return (HasVector &&
5792 Ty->isVectorType() &&
5793 getContext().getTypeSize(Ty) <= 128);
5794}
5795
Ulrich Weigand47445072013-05-06 16:26:41 +00005796bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5797 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5798 switch (BT->getKind()) {
5799 case BuiltinType::Float:
5800 case BuiltinType::Double:
5801 return true;
5802 default:
5803 return false;
5804 }
5805
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005806 return false;
5807}
5808
5809QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005810 if (const RecordType *RT = Ty->getAsStructureType()) {
5811 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005812 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005813
5814 // If this is a C++ record, check the bases first.
5815 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005816 for (const auto &I : CXXRD->bases()) {
5817 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005818
5819 // Empty bases don't affect things either way.
5820 if (isEmptyRecord(getContext(), Base, true))
5821 continue;
5822
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005823 if (!Found.isNull())
5824 return Ty;
5825 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005826 }
5827
5828 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005829 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005830 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005831 // Unlike isSingleElementStruct(), empty structure and array fields
5832 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005833 if (getContext().getLangOpts().CPlusPlus &&
5834 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5835 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005836
5837 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005838 // Nested structures still do though.
5839 if (!Found.isNull())
5840 return Ty;
5841 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005842 }
5843
5844 // Unlike isSingleElementStruct(), trailing padding is allowed.
5845 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005846 if (!Found.isNull())
5847 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005848 }
5849
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005850 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005851}
5852
John McCall7f416cc2015-09-08 08:05:57 +00005853Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5854 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005855 // Assume that va_list type is correct; should be pointer to LLVM type:
5856 // struct {
5857 // i64 __gpr;
5858 // i64 __fpr;
5859 // i8 *__overflow_arg_area;
5860 // i8 *__reg_save_area;
5861 // };
5862
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005863 // Every non-vector argument occupies 8 bytes and is passed by preference
5864 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5865 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005866 Ty = getContext().getCanonicalType(Ty);
5867 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005868 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005869 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005870 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005871 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005872 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005873 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005874 CharUnits UnpaddedSize;
5875 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005876 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005877 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5878 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005879 } else {
5880 if (AI.getCoerceToType())
5881 ArgTy = AI.getCoerceToType();
5882 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005883 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005884 UnpaddedSize = TyInfo.first;
5885 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005886 }
John McCall7f416cc2015-09-08 08:05:57 +00005887 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5888 if (IsVector && UnpaddedSize > PaddedSize)
5889 PaddedSize = CharUnits::fromQuantity(16);
5890 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005891
John McCall7f416cc2015-09-08 08:05:57 +00005892 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005893
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005894 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005895 llvm::Value *PaddedSizeV =
5896 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005897
5898 if (IsVector) {
5899 // Work out the address of a vector argument on the stack.
5900 // Vector arguments are always passed in the high bits of a
5901 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005902 Address OverflowArgAreaPtr =
5903 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005904 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005905 Address OverflowArgArea =
5906 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5907 TyInfo.second);
5908 Address MemAddr =
5909 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005910
5911 // Update overflow_arg_area_ptr pointer
5912 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005913 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5914 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005915 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5916
5917 return MemAddr;
5918 }
5919
John McCall7f416cc2015-09-08 08:05:57 +00005920 assert(PaddedSize.getQuantity() == 8);
5921
5922 unsigned MaxRegs, RegCountField, RegSaveIndex;
5923 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005924 if (InFPRs) {
5925 MaxRegs = 4; // Maximum of 4 FPR arguments
5926 RegCountField = 1; // __fpr
5927 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005928 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005929 } else {
5930 MaxRegs = 5; // Maximum of 5 GPR arguments
5931 RegCountField = 0; // __gpr
5932 RegSaveIndex = 2; // save offset for r2
5933 RegPadding = Padding; // values are passed in the low bits of a GPR
5934 }
5935
John McCall7f416cc2015-09-08 08:05:57 +00005936 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5937 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5938 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005939 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005940 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5941 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005942 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005943
5944 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5945 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5946 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5947 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5948
5949 // Emit code to load the value if it was passed in registers.
5950 CGF.EmitBlock(InRegBlock);
5951
5952 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005953 llvm::Value *ScaledRegCount =
5954 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5955 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005956 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5957 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005958 llvm::Value *RegOffset =
5959 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005960 Address RegSaveAreaPtr =
5961 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5962 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005963 llvm::Value *RegSaveArea =
5964 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005965 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5966 "raw_reg_addr"),
5967 PaddedSize);
5968 Address RegAddr =
5969 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005970
5971 // Update the register count
5972 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5973 llvm::Value *NewRegCount =
5974 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5975 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5976 CGF.EmitBranch(ContBlock);
5977
5978 // Emit code to load the value if it was passed in memory.
5979 CGF.EmitBlock(InMemBlock);
5980
5981 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005982 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5983 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5984 Address OverflowArgArea =
5985 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5986 PaddedSize);
5987 Address RawMemAddr =
5988 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5989 Address MemAddr =
5990 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005991
5992 // Update overflow_arg_area_ptr pointer
5993 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005994 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5995 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005996 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5997 CGF.EmitBranch(ContBlock);
5998
5999 // Return the appropriate result.
6000 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006001 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6002 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006003
6004 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006005 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6006 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006007
6008 return ResAddr;
6009}
6010
Ulrich Weigand47445072013-05-06 16:26:41 +00006011ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6012 if (RetTy->isVoidType())
6013 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006014 if (isVectorArgumentType(RetTy))
6015 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006016 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006017 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006018 return (isPromotableIntegerType(RetTy) ?
6019 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6020}
6021
6022ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6023 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006024 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006025 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006026
6027 // Integers and enums are extended to full register width.
6028 if (isPromotableIntegerType(Ty))
6029 return ABIArgInfo::getExtend();
6030
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006031 // Handle vector types and vector-like structure types. Note that
6032 // as opposed to float-like structure types, we do not allow any
6033 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006034 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006035 QualType SingleElementTy = GetSingleElementType(Ty);
6036 if (isVectorArgumentType(SingleElementTy) &&
6037 getContext().getTypeSize(SingleElementTy) == Size)
6038 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6039
6040 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006041 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006042 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006043
6044 // Handle small structures.
6045 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6046 // Structures with flexible arrays have variable length, so really
6047 // fail the size test above.
6048 const RecordDecl *RD = RT->getDecl();
6049 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006050 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006051
6052 // The structure is passed as an unextended integer, a float, or a double.
6053 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006054 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006055 assert(Size == 32 || Size == 64);
6056 if (Size == 32)
6057 PassTy = llvm::Type::getFloatTy(getVMContext());
6058 else
6059 PassTy = llvm::Type::getDoubleTy(getVMContext());
6060 } else
6061 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6062 return ABIArgInfo::getDirect(PassTy);
6063 }
6064
6065 // Non-structure compounds are passed indirectly.
6066 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006067 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006068
Craig Topper8a13c412014-05-21 05:09:00 +00006069 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006070}
6071
6072//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006073// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006074//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006075
6076namespace {
6077
6078class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6079public:
Chris Lattner2b037972010-07-29 02:01:43 +00006080 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6081 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006082 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006083 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006084};
6085
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006086}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006087
Eric Christopher162c91c2015-06-05 22:03:00 +00006088void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006089 llvm::GlobalValue *GV,
6090 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006091 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006092 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6093 // Handle 'interrupt' attribute:
6094 llvm::Function *F = cast<llvm::Function>(GV);
6095
6096 // Step 1: Set ISR calling convention.
6097 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6098
6099 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006100 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006101
6102 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006103 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006104 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6105 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006106 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006107 }
6108}
6109
Chris Lattner0cf24192010-06-28 20:05:43 +00006110//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006111// MIPS ABI Implementation. This works for both little-endian and
6112// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006113//===----------------------------------------------------------------------===//
6114
John McCall943fae92010-05-27 06:19:26 +00006115namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006116class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006117 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006118 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6119 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006120 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006121 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006122 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006123 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006124public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006125 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006126 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006127 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006128
6129 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006130 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006131 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006132 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6133 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006134 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006135};
6136
John McCall943fae92010-05-27 06:19:26 +00006137class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006138 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006139public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006140 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6141 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006142 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006143
Craig Topper4f12f102014-03-12 06:41:41 +00006144 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006145 return 29;
6146 }
6147
Eric Christopher162c91c2015-06-05 22:03:00 +00006148 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006149 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006150 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006151 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006152 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006153 if (FD->hasAttr<Mips16Attr>()) {
6154 Fn->addFnAttr("mips16");
6155 }
6156 else if (FD->hasAttr<NoMips16Attr>()) {
6157 Fn->addFnAttr("nomips16");
6158 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006159
6160 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6161 if (!Attr)
6162 return;
6163
6164 const char *Kind;
6165 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006166 case MipsInterruptAttr::eic: Kind = "eic"; break;
6167 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6168 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6169 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6170 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6171 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6172 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6173 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6174 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6175 }
6176
6177 Fn->addFnAttr("interrupt", Kind);
6178
Reed Kotler373feca2013-01-16 17:10:28 +00006179 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006180
John McCall943fae92010-05-27 06:19:26 +00006181 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006182 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006183
Craig Topper4f12f102014-03-12 06:41:41 +00006184 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006185 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006186 }
John McCall943fae92010-05-27 06:19:26 +00006187};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006188}
John McCall943fae92010-05-27 06:19:26 +00006189
Eric Christopher7565e0d2015-05-29 23:09:49 +00006190void MipsABIInfo::CoerceToIntArgs(
6191 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006192 llvm::IntegerType *IntTy =
6193 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006194
6195 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6196 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6197 ArgList.push_back(IntTy);
6198
6199 // If necessary, add one more integer type to ArgList.
6200 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6201
6202 if (R)
6203 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006204}
6205
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006206// In N32/64, an aligned double precision floating point field is passed in
6207// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006208llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006209 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6210
6211 if (IsO32) {
6212 CoerceToIntArgs(TySize, ArgList);
6213 return llvm::StructType::get(getVMContext(), ArgList);
6214 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006215
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006216 if (Ty->isComplexType())
6217 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006218
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006219 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006220
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006221 // Unions/vectors are passed in integer registers.
6222 if (!RT || !RT->isStructureOrClassType()) {
6223 CoerceToIntArgs(TySize, ArgList);
6224 return llvm::StructType::get(getVMContext(), ArgList);
6225 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006226
6227 const RecordDecl *RD = RT->getDecl();
6228 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006229 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006230
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006231 uint64_t LastOffset = 0;
6232 unsigned idx = 0;
6233 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6234
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006235 // Iterate over fields in the struct/class and check if there are any aligned
6236 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006237 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6238 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006239 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006240 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6241
6242 if (!BT || BT->getKind() != BuiltinType::Double)
6243 continue;
6244
6245 uint64_t Offset = Layout.getFieldOffset(idx);
6246 if (Offset % 64) // Ignore doubles that are not aligned.
6247 continue;
6248
6249 // Add ((Offset - LastOffset) / 64) args of type i64.
6250 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6251 ArgList.push_back(I64);
6252
6253 // Add double type.
6254 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6255 LastOffset = Offset + 64;
6256 }
6257
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006258 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6259 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006260
6261 return llvm::StructType::get(getVMContext(), ArgList);
6262}
6263
Akira Hatanakaddd66342013-10-29 18:41:15 +00006264llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6265 uint64_t Offset) const {
6266 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006267 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006268
Akira Hatanakaddd66342013-10-29 18:41:15 +00006269 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006270}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006271
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006272ABIArgInfo
6273MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006274 Ty = useFirstFieldIfTransparentUnion(Ty);
6275
Akira Hatanaka1632af62012-01-09 19:31:25 +00006276 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006277 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006278 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006279
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006280 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6281 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006282 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6283 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006284
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006285 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006286 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006287 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006288 return ABIArgInfo::getIgnore();
6289
Mark Lacey3825e832013-10-06 01:33:34 +00006290 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006291 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006292 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006293 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006294
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006295 // If we have reached here, aggregates are passed directly by coercing to
6296 // another structure type. Padding is inserted if the offset of the
6297 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006298 ABIArgInfo ArgInfo =
6299 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6300 getPaddingType(OrigOffset, CurrOffset));
6301 ArgInfo.setInReg(true);
6302 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006303 }
6304
6305 // Treat an enum type as its underlying type.
6306 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6307 Ty = EnumTy->getDecl()->getIntegerType();
6308
Daniel Sanders5b445b32014-10-24 14:42:42 +00006309 // All integral types are promoted to the GPR width.
6310 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006311 return ABIArgInfo::getExtend();
6312
Akira Hatanakaddd66342013-10-29 18:41:15 +00006313 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006314 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006315}
6316
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006317llvm::Type*
6318MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006319 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006320 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006321
Akira Hatanakab6f74432012-02-09 18:49:26 +00006322 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006323 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006324 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6325 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006326
Akira Hatanakab6f74432012-02-09 18:49:26 +00006327 // N32/64 returns struct/classes in floating point registers if the
6328 // following conditions are met:
6329 // 1. The size of the struct/class is no larger than 128-bit.
6330 // 2. The struct/class has one or two fields all of which are floating
6331 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006332 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006333 //
6334 // Any other composite results are returned in integer registers.
6335 //
6336 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6337 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6338 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006339 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006340
Akira Hatanakab6f74432012-02-09 18:49:26 +00006341 if (!BT || !BT->isFloatingPoint())
6342 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006343
David Blaikie2d7c57e2012-04-30 02:36:29 +00006344 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006345 }
6346
6347 if (b == e)
6348 return llvm::StructType::get(getVMContext(), RTList,
6349 RD->hasAttr<PackedAttr>());
6350
6351 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006352 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006353 }
6354
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006355 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006356 return llvm::StructType::get(getVMContext(), RTList);
6357}
6358
Akira Hatanakab579fe52011-06-02 00:09:17 +00006359ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006360 uint64_t Size = getContext().getTypeSize(RetTy);
6361
Daniel Sandersed39f582014-09-04 13:28:14 +00006362 if (RetTy->isVoidType())
6363 return ABIArgInfo::getIgnore();
6364
6365 // O32 doesn't treat zero-sized structs differently from other structs.
6366 // However, N32/N64 ignores zero sized return values.
6367 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006368 return ABIArgInfo::getIgnore();
6369
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006370 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006371 if (Size <= 128) {
6372 if (RetTy->isAnyComplexType())
6373 return ABIArgInfo::getDirect();
6374
Daniel Sanderse5018b62014-09-04 15:05:39 +00006375 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006376 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006377 if (!IsO32 ||
6378 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6379 ABIArgInfo ArgInfo =
6380 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6381 ArgInfo.setInReg(true);
6382 return ArgInfo;
6383 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006384 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006385
John McCall7f416cc2015-09-08 08:05:57 +00006386 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006387 }
6388
6389 // Treat an enum type as its underlying type.
6390 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6391 RetTy = EnumTy->getDecl()->getIntegerType();
6392
6393 return (RetTy->isPromotableIntegerType() ?
6394 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6395}
6396
6397void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006398 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006399 if (!getCXXABI().classifyReturnType(FI))
6400 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006401
Eric Christopher7565e0d2015-05-29 23:09:49 +00006402 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006403 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006404
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006405 for (auto &I : FI.arguments())
6406 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006407}
6408
John McCall7f416cc2015-09-08 08:05:57 +00006409Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6410 QualType OrigTy) const {
6411 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006412
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006413 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6414 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006415 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006416 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006417 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006418 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006419 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006420 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006421 DidPromote = true;
6422 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6423 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006424 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006425
John McCall7f416cc2015-09-08 08:05:57 +00006426 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006427
John McCall7f416cc2015-09-08 08:05:57 +00006428 // The alignment of things in the argument area is never larger than
6429 // StackAlignInBytes.
6430 TyInfo.second =
6431 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6432
6433 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6434 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6435
6436 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6437 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6438
6439
6440 // If there was a promotion, "unpromote" into a temporary.
6441 // TODO: can we just use a pointer into a subset of the original slot?
6442 if (DidPromote) {
6443 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6444 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6445
6446 // Truncate down to the right width.
6447 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6448 : CGF.IntPtrTy);
6449 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6450 if (OrigTy->isPointerType())
6451 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6452
6453 CGF.Builder.CreateStore(V, Temp);
6454 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006455 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006456
John McCall7f416cc2015-09-08 08:05:57 +00006457 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006458}
6459
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006460bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6461 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006462
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006463 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6464 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6465 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006466
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006467 return false;
6468}
6469
John McCall943fae92010-05-27 06:19:26 +00006470bool
6471MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6472 llvm::Value *Address) const {
6473 // This information comes from gcc's implementation, which seems to
6474 // as canonical as it gets.
6475
John McCall943fae92010-05-27 06:19:26 +00006476 // Everything on MIPS is 4 bytes. Double-precision FP registers
6477 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006478 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006479
6480 // 0-31 are the general purpose registers, $0 - $31.
6481 // 32-63 are the floating-point registers, $f0 - $f31.
6482 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6483 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006484 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006485
6486 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6487 // They are one bit wide and ignored here.
6488
6489 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6490 // (coprocessor 1 is the FP unit)
6491 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6492 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6493 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006494 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006495 return false;
6496}
6497
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006498//===----------------------------------------------------------------------===//
6499// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006500// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006501// handling.
6502//===----------------------------------------------------------------------===//
6503
6504namespace {
6505
6506class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6507public:
6508 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6509 : DefaultTargetCodeGenInfo(CGT) {}
6510
Eric Christopher162c91c2015-06-05 22:03:00 +00006511 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006512 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006513};
6514
Eric Christopher162c91c2015-06-05 22:03:00 +00006515void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006516 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006517 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006518 if (!FD) return;
6519
6520 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006521
David Blaikiebbafb8a2012-03-11 07:00:24 +00006522 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006523 if (FD->hasAttr<OpenCLKernelAttr>()) {
6524 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006525 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006526 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6527 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006528 // Convert the reqd_work_group_size() attributes to metadata.
6529 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006530 llvm::NamedMDNode *OpenCLMetadata =
6531 M.getModule().getOrInsertNamedMetadata(
6532 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006533
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006534 SmallVector<llvm::Metadata *, 5> Operands;
6535 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006536
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006537 Operands.push_back(
6538 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6539 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6540 Operands.push_back(
6541 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6542 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6543 Operands.push_back(
6544 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6545 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006546
Eric Christopher7565e0d2015-05-29 23:09:49 +00006547 // Add a boolean constant operand for "required" (true) or "hint"
6548 // (false) for implementing the work_group_size_hint attr later.
6549 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006550 Operands.push_back(
6551 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006552 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6553 }
6554 }
6555 }
6556}
6557
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006558}
John McCall943fae92010-05-27 06:19:26 +00006559
Tony Linthicum76329bf2011-12-12 21:14:55 +00006560//===----------------------------------------------------------------------===//
6561// Hexagon ABI Implementation
6562//===----------------------------------------------------------------------===//
6563
6564namespace {
6565
6566class HexagonABIInfo : public ABIInfo {
6567
6568
6569public:
6570 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6571
6572private:
6573
6574 ABIArgInfo classifyReturnType(QualType RetTy) const;
6575 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6576
Craig Topper4f12f102014-03-12 06:41:41 +00006577 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006578
John McCall7f416cc2015-09-08 08:05:57 +00006579 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6580 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006581};
6582
6583class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6584public:
6585 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6586 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6587
Craig Topper4f12f102014-03-12 06:41:41 +00006588 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006589 return 29;
6590 }
6591};
6592
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006593}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006594
6595void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006596 if (!getCXXABI().classifyReturnType(FI))
6597 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006598 for (auto &I : FI.arguments())
6599 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006600}
6601
6602ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6603 if (!isAggregateTypeForABI(Ty)) {
6604 // Treat an enum type as its underlying type.
6605 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6606 Ty = EnumTy->getDecl()->getIntegerType();
6607
6608 return (Ty->isPromotableIntegerType() ?
6609 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6610 }
6611
6612 // Ignore empty records.
6613 if (isEmptyRecord(getContext(), Ty, true))
6614 return ABIArgInfo::getIgnore();
6615
Mark Lacey3825e832013-10-06 01:33:34 +00006616 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006617 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006618
6619 uint64_t Size = getContext().getTypeSize(Ty);
6620 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006621 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006622 // Pass in the smallest viable integer type.
6623 else if (Size > 32)
6624 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6625 else if (Size > 16)
6626 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6627 else if (Size > 8)
6628 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6629 else
6630 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6631}
6632
6633ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6634 if (RetTy->isVoidType())
6635 return ABIArgInfo::getIgnore();
6636
6637 // Large vector types should be returned via memory.
6638 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006639 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006640
6641 if (!isAggregateTypeForABI(RetTy)) {
6642 // Treat an enum type as its underlying type.
6643 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6644 RetTy = EnumTy->getDecl()->getIntegerType();
6645
6646 return (RetTy->isPromotableIntegerType() ?
6647 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6648 }
6649
Tony Linthicum76329bf2011-12-12 21:14:55 +00006650 if (isEmptyRecord(getContext(), RetTy, true))
6651 return ABIArgInfo::getIgnore();
6652
6653 // Aggregates <= 8 bytes are returned in r0; other aggregates
6654 // are returned indirectly.
6655 uint64_t Size = getContext().getTypeSize(RetTy);
6656 if (Size <= 64) {
6657 // Return in the smallest viable integer type.
6658 if (Size <= 8)
6659 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6660 if (Size <= 16)
6661 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6662 if (Size <= 32)
6663 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6664 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6665 }
6666
John McCall7f416cc2015-09-08 08:05:57 +00006667 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006668}
6669
John McCall7f416cc2015-09-08 08:05:57 +00006670Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6671 QualType Ty) const {
6672 // FIXME: Someone needs to audit that this handle alignment correctly.
6673 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6674 getContext().getTypeInfoInChars(Ty),
6675 CharUnits::fromQuantity(4),
6676 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006677}
6678
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006679//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006680// Lanai ABI Implementation
6681//===----------------------------------------------------------------------===//
6682
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006683namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006684class LanaiABIInfo : public DefaultABIInfo {
6685public:
6686 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6687
6688 bool shouldUseInReg(QualType Ty, CCState &State) const;
6689
6690 void computeInfo(CGFunctionInfo &FI) const override {
6691 CCState State(FI.getCallingConvention());
6692 // Lanai uses 4 registers to pass arguments unless the function has the
6693 // regparm attribute set.
6694 if (FI.getHasRegParm()) {
6695 State.FreeRegs = FI.getRegParm();
6696 } else {
6697 State.FreeRegs = 4;
6698 }
6699
6700 if (!getCXXABI().classifyReturnType(FI))
6701 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6702 for (auto &I : FI.arguments())
6703 I.info = classifyArgumentType(I.type, State);
6704 }
6705
Jacques Pienaare74d9132016-04-26 00:09:29 +00006706 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006707 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6708};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006709} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006710
6711bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6712 unsigned Size = getContext().getTypeSize(Ty);
6713 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6714
6715 if (SizeInRegs == 0)
6716 return false;
6717
6718 if (SizeInRegs > State.FreeRegs) {
6719 State.FreeRegs = 0;
6720 return false;
6721 }
6722
6723 State.FreeRegs -= SizeInRegs;
6724
6725 return true;
6726}
6727
Jacques Pienaare74d9132016-04-26 00:09:29 +00006728ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6729 CCState &State) const {
6730 if (!ByVal) {
6731 if (State.FreeRegs) {
6732 --State.FreeRegs; // Non-byval indirects just use one pointer.
6733 return getNaturalAlignIndirectInReg(Ty);
6734 }
6735 return getNaturalAlignIndirect(Ty, false);
6736 }
6737
6738 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006739 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006740 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6741 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6742 /*Realign=*/TypeAlign >
6743 MinABIStackAlignInBytes);
6744}
6745
Jacques Pienaard964cc22016-03-28 21:02:54 +00006746ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6747 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006748 // Check with the C++ ABI first.
6749 const RecordType *RT = Ty->getAs<RecordType>();
6750 if (RT) {
6751 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6752 if (RAA == CGCXXABI::RAA_Indirect) {
6753 return getIndirectResult(Ty, /*ByVal=*/false, State);
6754 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6755 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6756 }
6757 }
6758
6759 if (isAggregateTypeForABI(Ty)) {
6760 // Structures with flexible arrays are always indirect.
6761 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6762 return getIndirectResult(Ty, /*ByVal=*/true, State);
6763
6764 // Ignore empty structs/unions.
6765 if (isEmptyRecord(getContext(), Ty, true))
6766 return ABIArgInfo::getIgnore();
6767
6768 llvm::LLVMContext &LLVMContext = getVMContext();
6769 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6770 if (SizeInRegs <= State.FreeRegs) {
6771 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6772 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6773 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6774 State.FreeRegs -= SizeInRegs;
6775 return ABIArgInfo::getDirectInReg(Result);
6776 } else {
6777 State.FreeRegs = 0;
6778 }
6779 return getIndirectResult(Ty, true, State);
6780 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006781
6782 // Treat an enum type as its underlying type.
6783 if (const auto *EnumTy = Ty->getAs<EnumType>())
6784 Ty = EnumTy->getDecl()->getIntegerType();
6785
Jacques Pienaare74d9132016-04-26 00:09:29 +00006786 bool InReg = shouldUseInReg(Ty, State);
6787 if (Ty->isPromotableIntegerType()) {
6788 if (InReg)
6789 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006790 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006791 }
6792 if (InReg)
6793 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006794 return ABIArgInfo::getDirect();
6795}
6796
6797namespace {
6798class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6799public:
6800 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6801 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6802};
6803}
6804
6805//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006806// AMDGPU ABI Implementation
6807//===----------------------------------------------------------------------===//
6808
6809namespace {
6810
6811class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6812public:
6813 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6814 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006815 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006816 CodeGen::CodeGenModule &M) const override;
6817};
6818
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006819}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006820
Eric Christopher162c91c2015-06-05 22:03:00 +00006821void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006822 const Decl *D,
6823 llvm::GlobalValue *GV,
6824 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006825 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006826 if (!FD)
6827 return;
6828
6829 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6830 llvm::Function *F = cast<llvm::Function>(GV);
6831 uint32_t NumVGPR = Attr->getNumVGPR();
6832 if (NumVGPR != 0)
6833 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6834 }
6835
6836 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6837 llvm::Function *F = cast<llvm::Function>(GV);
6838 unsigned NumSGPR = Attr->getNumSGPR();
6839 if (NumSGPR != 0)
6840 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6841 }
6842}
6843
Tony Linthicum76329bf2011-12-12 21:14:55 +00006844
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006845//===----------------------------------------------------------------------===//
6846// SPARC v9 ABI Implementation.
6847// Based on the SPARC Compliance Definition version 2.4.1.
6848//
6849// Function arguments a mapped to a nominal "parameter array" and promoted to
6850// registers depending on their type. Each argument occupies 8 or 16 bytes in
6851// the array, structs larger than 16 bytes are passed indirectly.
6852//
6853// One case requires special care:
6854//
6855// struct mixed {
6856// int i;
6857// float f;
6858// };
6859//
6860// When a struct mixed is passed by value, it only occupies 8 bytes in the
6861// parameter array, but the int is passed in an integer register, and the float
6862// is passed in a floating point register. This is represented as two arguments
6863// with the LLVM IR inreg attribute:
6864//
6865// declare void f(i32 inreg %i, float inreg %f)
6866//
6867// The code generator will only allocate 4 bytes from the parameter array for
6868// the inreg arguments. All other arguments are allocated a multiple of 8
6869// bytes.
6870//
6871namespace {
6872class SparcV9ABIInfo : public ABIInfo {
6873public:
6874 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6875
6876private:
6877 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006878 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006879 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6880 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006881
6882 // Coercion type builder for structs passed in registers. The coercion type
6883 // serves two purposes:
6884 //
6885 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6886 // in registers.
6887 // 2. Expose aligned floating point elements as first-level elements, so the
6888 // code generator knows to pass them in floating point registers.
6889 //
6890 // We also compute the InReg flag which indicates that the struct contains
6891 // aligned 32-bit floats.
6892 //
6893 struct CoerceBuilder {
6894 llvm::LLVMContext &Context;
6895 const llvm::DataLayout &DL;
6896 SmallVector<llvm::Type*, 8> Elems;
6897 uint64_t Size;
6898 bool InReg;
6899
6900 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6901 : Context(c), DL(dl), Size(0), InReg(false) {}
6902
6903 // Pad Elems with integers until Size is ToSize.
6904 void pad(uint64_t ToSize) {
6905 assert(ToSize >= Size && "Cannot remove elements");
6906 if (ToSize == Size)
6907 return;
6908
6909 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006910 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006911 if (Aligned > Size && Aligned <= ToSize) {
6912 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6913 Size = Aligned;
6914 }
6915
6916 // Add whole 64-bit words.
6917 while (Size + 64 <= ToSize) {
6918 Elems.push_back(llvm::Type::getInt64Ty(Context));
6919 Size += 64;
6920 }
6921
6922 // Final in-word padding.
6923 if (Size < ToSize) {
6924 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6925 Size = ToSize;
6926 }
6927 }
6928
6929 // Add a floating point element at Offset.
6930 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6931 // Unaligned floats are treated as integers.
6932 if (Offset % Bits)
6933 return;
6934 // The InReg flag is only required if there are any floats < 64 bits.
6935 if (Bits < 64)
6936 InReg = true;
6937 pad(Offset);
6938 Elems.push_back(Ty);
6939 Size = Offset + Bits;
6940 }
6941
6942 // Add a struct type to the coercion type, starting at Offset (in bits).
6943 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6944 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6945 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6946 llvm::Type *ElemTy = StrTy->getElementType(i);
6947 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6948 switch (ElemTy->getTypeID()) {
6949 case llvm::Type::StructTyID:
6950 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6951 break;
6952 case llvm::Type::FloatTyID:
6953 addFloat(ElemOffset, ElemTy, 32);
6954 break;
6955 case llvm::Type::DoubleTyID:
6956 addFloat(ElemOffset, ElemTy, 64);
6957 break;
6958 case llvm::Type::FP128TyID:
6959 addFloat(ElemOffset, ElemTy, 128);
6960 break;
6961 case llvm::Type::PointerTyID:
6962 if (ElemOffset % 64 == 0) {
6963 pad(ElemOffset);
6964 Elems.push_back(ElemTy);
6965 Size += 64;
6966 }
6967 break;
6968 default:
6969 break;
6970 }
6971 }
6972 }
6973
6974 // Check if Ty is a usable substitute for the coercion type.
6975 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006976 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006977 }
6978
6979 // Get the coercion type as a literal struct type.
6980 llvm::Type *getType() const {
6981 if (Elems.size() == 1)
6982 return Elems.front();
6983 else
6984 return llvm::StructType::get(Context, Elems);
6985 }
6986 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006987};
6988} // end anonymous namespace
6989
6990ABIArgInfo
6991SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6992 if (Ty->isVoidType())
6993 return ABIArgInfo::getIgnore();
6994
6995 uint64_t Size = getContext().getTypeSize(Ty);
6996
6997 // Anything too big to fit in registers is passed with an explicit indirect
6998 // pointer / sret pointer.
6999 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007000 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007001
7002 // Treat an enum type as its underlying type.
7003 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7004 Ty = EnumTy->getDecl()->getIntegerType();
7005
7006 // Integer types smaller than a register are extended.
7007 if (Size < 64 && Ty->isIntegerType())
7008 return ABIArgInfo::getExtend();
7009
7010 // Other non-aggregates go in registers.
7011 if (!isAggregateTypeForABI(Ty))
7012 return ABIArgInfo::getDirect();
7013
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007014 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7015 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7016 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007017 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007018
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007019 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007020 // Build a coercion type from the LLVM struct type.
7021 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7022 if (!StrTy)
7023 return ABIArgInfo::getDirect();
7024
7025 CoerceBuilder CB(getVMContext(), getDataLayout());
7026 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007027 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007028
7029 // Try to use the original type for coercion.
7030 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7031
7032 if (CB.InReg)
7033 return ABIArgInfo::getDirectInReg(CoerceTy);
7034 else
7035 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007036}
7037
John McCall7f416cc2015-09-08 08:05:57 +00007038Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7039 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007040 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7041 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7042 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7043 AI.setCoerceToType(ArgTy);
7044
John McCall7f416cc2015-09-08 08:05:57 +00007045 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007046
John McCall7f416cc2015-09-08 08:05:57 +00007047 CGBuilderTy &Builder = CGF.Builder;
7048 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7049 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7050
7051 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7052
7053 Address ArgAddr = Address::invalid();
7054 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007055 switch (AI.getKind()) {
7056 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007057 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007058 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007059 llvm_unreachable("Unsupported ABI kind for va_arg");
7060
John McCall7f416cc2015-09-08 08:05:57 +00007061 case ABIArgInfo::Extend: {
7062 Stride = SlotSize;
7063 CharUnits Offset = SlotSize - TypeInfo.first;
7064 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007065 break;
John McCall7f416cc2015-09-08 08:05:57 +00007066 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007067
John McCall7f416cc2015-09-08 08:05:57 +00007068 case ABIArgInfo::Direct: {
7069 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007070 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007071 ArgAddr = Addr;
7072 break;
John McCall7f416cc2015-09-08 08:05:57 +00007073 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007074
7075 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007076 Stride = SlotSize;
7077 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7078 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7079 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007080 break;
7081
7082 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007083 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007084 }
7085
7086 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007087 llvm::Value *NextPtr =
7088 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7089 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007090
John McCall7f416cc2015-09-08 08:05:57 +00007091 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007092}
7093
7094void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7095 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007096 for (auto &I : FI.arguments())
7097 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007098}
7099
7100namespace {
7101class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7102public:
7103 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7104 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007105
Craig Topper4f12f102014-03-12 06:41:41 +00007106 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007107 return 14;
7108 }
7109
7110 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007111 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007112};
7113} // end anonymous namespace
7114
Roman Divackyf02c9942014-02-24 18:46:27 +00007115bool
7116SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7117 llvm::Value *Address) const {
7118 // This is calculated from the LLVM and GCC tables and verified
7119 // against gcc output. AFAIK all ABIs use the same encoding.
7120
7121 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7122
7123 llvm::IntegerType *i8 = CGF.Int8Ty;
7124 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7125 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7126
7127 // 0-31: the 8-byte general-purpose registers
7128 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7129
7130 // 32-63: f0-31, the 4-byte floating-point registers
7131 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7132
7133 // Y = 64
7134 // PSR = 65
7135 // WIM = 66
7136 // TBR = 67
7137 // PC = 68
7138 // NPC = 69
7139 // FSR = 70
7140 // CSR = 71
7141 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007142
Roman Divackyf02c9942014-02-24 18:46:27 +00007143 // 72-87: d0-15, the 8-byte floating-point registers
7144 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7145
7146 return false;
7147}
7148
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007149
Robert Lytton0e076492013-08-13 09:43:10 +00007150//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007151// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007152//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007153
Robert Lytton0e076492013-08-13 09:43:10 +00007154namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007155
7156/// A SmallStringEnc instance is used to build up the TypeString by passing
7157/// it by reference between functions that append to it.
7158typedef llvm::SmallString<128> SmallStringEnc;
7159
7160/// TypeStringCache caches the meta encodings of Types.
7161///
7162/// The reason for caching TypeStrings is two fold:
7163/// 1. To cache a type's encoding for later uses;
7164/// 2. As a means to break recursive member type inclusion.
7165///
7166/// A cache Entry can have a Status of:
7167/// NonRecursive: The type encoding is not recursive;
7168/// Recursive: The type encoding is recursive;
7169/// Incomplete: An incomplete TypeString;
7170/// IncompleteUsed: An incomplete TypeString that has been used in a
7171/// Recursive type encoding.
7172///
7173/// A NonRecursive entry will have all of its sub-members expanded as fully
7174/// as possible. Whilst it may contain types which are recursive, the type
7175/// itself is not recursive and thus its encoding may be safely used whenever
7176/// the type is encountered.
7177///
7178/// A Recursive entry will have all of its sub-members expanded as fully as
7179/// possible. The type itself is recursive and it may contain other types which
7180/// are recursive. The Recursive encoding must not be used during the expansion
7181/// of a recursive type's recursive branch. For simplicity the code uses
7182/// IncompleteCount to reject all usage of Recursive encodings for member types.
7183///
7184/// An Incomplete entry is always a RecordType and only encodes its
7185/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7186/// are placed into the cache during type expansion as a means to identify and
7187/// handle recursive inclusion of types as sub-members. If there is recursion
7188/// the entry becomes IncompleteUsed.
7189///
7190/// During the expansion of a RecordType's members:
7191///
7192/// If the cache contains a NonRecursive encoding for the member type, the
7193/// cached encoding is used;
7194///
7195/// If the cache contains a Recursive encoding for the member type, the
7196/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7197///
7198/// If the member is a RecordType, an Incomplete encoding is placed into the
7199/// cache to break potential recursive inclusion of itself as a sub-member;
7200///
7201/// Once a member RecordType has been expanded, its temporary incomplete
7202/// entry is removed from the cache. If a Recursive encoding was swapped out
7203/// it is swapped back in;
7204///
7205/// If an incomplete entry is used to expand a sub-member, the incomplete
7206/// entry is marked as IncompleteUsed. The cache keeps count of how many
7207/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7208///
7209/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7210/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7211/// Else the member is part of a recursive type and thus the recursion has
7212/// been exited too soon for the encoding to be correct for the member.
7213///
7214class TypeStringCache {
7215 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7216 struct Entry {
7217 std::string Str; // The encoded TypeString for the type.
7218 enum Status State; // Information about the encoding in 'Str'.
7219 std::string Swapped; // A temporary place holder for a Recursive encoding
7220 // during the expansion of RecordType's members.
7221 };
7222 std::map<const IdentifierInfo *, struct Entry> Map;
7223 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7224 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7225public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007226 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007227 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7228 bool removeIncomplete(const IdentifierInfo *ID);
7229 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7230 bool IsRecursive);
7231 StringRef lookupStr(const IdentifierInfo *ID);
7232};
7233
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007234/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007235/// FieldEncoding is a helper for this ordering process.
7236class FieldEncoding {
7237 bool HasName;
7238 std::string Enc;
7239public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007240 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7241 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007242 bool operator<(const FieldEncoding &rhs) const {
7243 if (HasName != rhs.HasName) return HasName;
7244 return Enc < rhs.Enc;
7245 }
7246};
7247
Robert Lytton7d1db152013-08-19 09:46:39 +00007248class XCoreABIInfo : public DefaultABIInfo {
7249public:
7250 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007251 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7252 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007253};
7254
Robert Lyttond21e2d72014-03-03 13:45:29 +00007255class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007256 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007257public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007258 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007259 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007260 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7261 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007262};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007263
Robert Lytton2d196952013-10-11 10:29:34 +00007264} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007265
James Y Knight29b5f082016-02-24 02:59:33 +00007266// TODO: this implementation is likely now redundant with the default
7267// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007268Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7269 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007270 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007271
Robert Lytton2d196952013-10-11 10:29:34 +00007272 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007273 CharUnits SlotSize = CharUnits::fromQuantity(4);
7274 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007275
Robert Lytton2d196952013-10-11 10:29:34 +00007276 // Handle the argument.
7277 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007278 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007279 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7280 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7281 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007282 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007283
7284 Address Val = Address::invalid();
7285 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007286 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007287 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007288 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007289 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007290 llvm_unreachable("Unsupported ABI kind for va_arg");
7291 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007292 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7293 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007294 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007295 case ABIArgInfo::Extend:
7296 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007297 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7298 ArgSize = CharUnits::fromQuantity(
7299 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007300 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007301 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007302 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007303 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7304 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7305 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007306 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007307 }
Robert Lytton2d196952013-10-11 10:29:34 +00007308
7309 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007310 if (!ArgSize.isZero()) {
7311 llvm::Value *APN =
7312 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7313 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007314 }
John McCall7f416cc2015-09-08 08:05:57 +00007315
Robert Lytton2d196952013-10-11 10:29:34 +00007316 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007317}
Robert Lytton0e076492013-08-13 09:43:10 +00007318
Robert Lytton844aeeb2014-05-02 09:33:20 +00007319/// During the expansion of a RecordType, an incomplete TypeString is placed
7320/// into the cache as a means to identify and break recursion.
7321/// If there is a Recursive encoding in the cache, it is swapped out and will
7322/// be reinserted by removeIncomplete().
7323/// All other types of encoding should have been used rather than arriving here.
7324void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7325 std::string StubEnc) {
7326 if (!ID)
7327 return;
7328 Entry &E = Map[ID];
7329 assert( (E.Str.empty() || E.State == Recursive) &&
7330 "Incorrectly use of addIncomplete");
7331 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7332 E.Swapped.swap(E.Str); // swap out the Recursive
7333 E.Str.swap(StubEnc);
7334 E.State = Incomplete;
7335 ++IncompleteCount;
7336}
7337
7338/// Once the RecordType has been expanded, the temporary incomplete TypeString
7339/// must be removed from the cache.
7340/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7341/// Returns true if the RecordType was defined recursively.
7342bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7343 if (!ID)
7344 return false;
7345 auto I = Map.find(ID);
7346 assert(I != Map.end() && "Entry not present");
7347 Entry &E = I->second;
7348 assert( (E.State == Incomplete ||
7349 E.State == IncompleteUsed) &&
7350 "Entry must be an incomplete type");
7351 bool IsRecursive = false;
7352 if (E.State == IncompleteUsed) {
7353 // We made use of our Incomplete encoding, thus we are recursive.
7354 IsRecursive = true;
7355 --IncompleteUsedCount;
7356 }
7357 if (E.Swapped.empty())
7358 Map.erase(I);
7359 else {
7360 // Swap the Recursive back.
7361 E.Swapped.swap(E.Str);
7362 E.Swapped.clear();
7363 E.State = Recursive;
7364 }
7365 --IncompleteCount;
7366 return IsRecursive;
7367}
7368
7369/// Add the encoded TypeString to the cache only if it is NonRecursive or
7370/// Recursive (viz: all sub-members were expanded as fully as possible).
7371void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7372 bool IsRecursive) {
7373 if (!ID || IncompleteUsedCount)
7374 return; // No key or it is is an incomplete sub-type so don't add.
7375 Entry &E = Map[ID];
7376 if (IsRecursive && !E.Str.empty()) {
7377 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7378 "This is not the same Recursive entry");
7379 // The parent container was not recursive after all, so we could have used
7380 // this Recursive sub-member entry after all, but we assumed the worse when
7381 // we started viz: IncompleteCount!=0.
7382 return;
7383 }
7384 assert(E.Str.empty() && "Entry already present");
7385 E.Str = Str.str();
7386 E.State = IsRecursive? Recursive : NonRecursive;
7387}
7388
7389/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7390/// are recursively expanding a type (IncompleteCount != 0) and the cached
7391/// encoding is Recursive, return an empty StringRef.
7392StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7393 if (!ID)
7394 return StringRef(); // We have no key.
7395 auto I = Map.find(ID);
7396 if (I == Map.end())
7397 return StringRef(); // We have no encoding.
7398 Entry &E = I->second;
7399 if (E.State == Recursive && IncompleteCount)
7400 return StringRef(); // We don't use Recursive encodings for member types.
7401
7402 if (E.State == Incomplete) {
7403 // The incomplete type is being used to break out of recursion.
7404 E.State = IncompleteUsed;
7405 ++IncompleteUsedCount;
7406 }
7407 return E.Str.c_str();
7408}
7409
7410/// The XCore ABI includes a type information section that communicates symbol
7411/// type information to the linker. The linker uses this information to verify
7412/// safety/correctness of things such as array bound and pointers et al.
7413/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7414/// This type information (TypeString) is emitted into meta data for all global
7415/// symbols: definitions, declarations, functions & variables.
7416///
7417/// The TypeString carries type, qualifier, name, size & value details.
7418/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007419/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007420/// The output is tested by test/CodeGen/xcore-stringtype.c.
7421///
7422static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7423 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7424
7425/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7426void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7427 CodeGen::CodeGenModule &CGM) const {
7428 SmallStringEnc Enc;
7429 if (getTypeString(Enc, D, CGM, TSC)) {
7430 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007431 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7432 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007433 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7434 llvm::NamedMDNode *MD =
7435 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7436 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7437 }
7438}
7439
Xiuli Pan972bea82016-03-24 03:57:17 +00007440//===----------------------------------------------------------------------===//
7441// SPIR ABI Implementation
7442//===----------------------------------------------------------------------===//
7443
7444namespace {
7445class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7446public:
7447 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7448 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7449 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7450 CodeGen::CodeGenModule &M) const override;
7451};
7452} // End anonymous namespace.
7453
7454/// Emit SPIR specific metadata: OpenCL and SPIR version.
7455void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7456 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007457 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7458 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7459 llvm::Module &M = CGM.getModule();
7460 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7461 // opencl.spir.version named metadata.
7462 llvm::Metadata *SPIRVerElts[] = {
7463 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7464 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7465 llvm::NamedMDNode *SPIRVerMD =
7466 M.getOrInsertNamedMetadata("opencl.spir.version");
7467 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7468 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7469 // opencl.ocl.version named metadata node.
7470 llvm::Metadata *OCLVerElts[] = {
7471 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7472 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7473 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7474 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7475 llvm::NamedMDNode *OCLVerMD =
7476 M.getOrInsertNamedMetadata("opencl.ocl.version");
7477 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7478}
7479
Robert Lytton844aeeb2014-05-02 09:33:20 +00007480static bool appendType(SmallStringEnc &Enc, QualType QType,
7481 const CodeGen::CodeGenModule &CGM,
7482 TypeStringCache &TSC);
7483
7484/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007485/// Builds a SmallVector containing the encoded field types in declaration
7486/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007487static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7488 const RecordDecl *RD,
7489 const CodeGen::CodeGenModule &CGM,
7490 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007491 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007492 SmallStringEnc Enc;
7493 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007494 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007495 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007496 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007497 Enc += "b(";
7498 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007499 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007500 Enc += ':';
7501 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007502 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007503 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007504 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007505 Enc += ')';
7506 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007507 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007508 }
7509 return true;
7510}
7511
7512/// Appends structure and union types to Enc and adds encoding to cache.
7513/// Recursively calls appendType (via extractFieldType) for each field.
7514/// Union types have their fields ordered according to the ABI.
7515static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7516 const CodeGen::CodeGenModule &CGM,
7517 TypeStringCache &TSC, const IdentifierInfo *ID) {
7518 // Append the cached TypeString if we have one.
7519 StringRef TypeString = TSC.lookupStr(ID);
7520 if (!TypeString.empty()) {
7521 Enc += TypeString;
7522 return true;
7523 }
7524
7525 // Start to emit an incomplete TypeString.
7526 size_t Start = Enc.size();
7527 Enc += (RT->isUnionType()? 'u' : 's');
7528 Enc += '(';
7529 if (ID)
7530 Enc += ID->getName();
7531 Enc += "){";
7532
7533 // We collect all encoded fields and order as necessary.
7534 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007535 const RecordDecl *RD = RT->getDecl()->getDefinition();
7536 if (RD && !RD->field_empty()) {
7537 // An incomplete TypeString stub is placed in the cache for this RecordType
7538 // so that recursive calls to this RecordType will use it whilst building a
7539 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007540 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007541 std::string StubEnc(Enc.substr(Start).str());
7542 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7543 TSC.addIncomplete(ID, std::move(StubEnc));
7544 if (!extractFieldType(FE, RD, CGM, TSC)) {
7545 (void) TSC.removeIncomplete(ID);
7546 return false;
7547 }
7548 IsRecursive = TSC.removeIncomplete(ID);
7549 // The ABI requires unions to be sorted but not structures.
7550 // See FieldEncoding::operator< for sort algorithm.
7551 if (RT->isUnionType())
7552 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007553 // We can now complete the TypeString.
7554 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007555 for (unsigned I = 0; I != E; ++I) {
7556 if (I)
7557 Enc += ',';
7558 Enc += FE[I].str();
7559 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007560 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007561 Enc += '}';
7562 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7563 return true;
7564}
7565
7566/// Appends enum types to Enc and adds the encoding to the cache.
7567static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7568 TypeStringCache &TSC,
7569 const IdentifierInfo *ID) {
7570 // Append the cached TypeString if we have one.
7571 StringRef TypeString = TSC.lookupStr(ID);
7572 if (!TypeString.empty()) {
7573 Enc += TypeString;
7574 return true;
7575 }
7576
7577 size_t Start = Enc.size();
7578 Enc += "e(";
7579 if (ID)
7580 Enc += ID->getName();
7581 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007582
7583 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007584 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007585 SmallVector<FieldEncoding, 16> FE;
7586 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7587 ++I) {
7588 SmallStringEnc EnumEnc;
7589 EnumEnc += "m(";
7590 EnumEnc += I->getName();
7591 EnumEnc += "){";
7592 I->getInitVal().toString(EnumEnc);
7593 EnumEnc += '}';
7594 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7595 }
7596 std::sort(FE.begin(), FE.end());
7597 unsigned E = FE.size();
7598 for (unsigned I = 0; I != E; ++I) {
7599 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007600 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007601 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007602 }
7603 }
7604 Enc += '}';
7605 TSC.addIfComplete(ID, Enc.substr(Start), false);
7606 return true;
7607}
7608
7609/// Appends type's qualifier to Enc.
7610/// This is done prior to appending the type's encoding.
7611static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7612 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007613 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007614 int Lookup = 0;
7615 if (QT.isConstQualified())
7616 Lookup += 1<<0;
7617 if (QT.isRestrictQualified())
7618 Lookup += 1<<1;
7619 if (QT.isVolatileQualified())
7620 Lookup += 1<<2;
7621 Enc += Table[Lookup];
7622}
7623
7624/// Appends built-in types to Enc.
7625static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7626 const char *EncType;
7627 switch (BT->getKind()) {
7628 case BuiltinType::Void:
7629 EncType = "0";
7630 break;
7631 case BuiltinType::Bool:
7632 EncType = "b";
7633 break;
7634 case BuiltinType::Char_U:
7635 EncType = "uc";
7636 break;
7637 case BuiltinType::UChar:
7638 EncType = "uc";
7639 break;
7640 case BuiltinType::SChar:
7641 EncType = "sc";
7642 break;
7643 case BuiltinType::UShort:
7644 EncType = "us";
7645 break;
7646 case BuiltinType::Short:
7647 EncType = "ss";
7648 break;
7649 case BuiltinType::UInt:
7650 EncType = "ui";
7651 break;
7652 case BuiltinType::Int:
7653 EncType = "si";
7654 break;
7655 case BuiltinType::ULong:
7656 EncType = "ul";
7657 break;
7658 case BuiltinType::Long:
7659 EncType = "sl";
7660 break;
7661 case BuiltinType::ULongLong:
7662 EncType = "ull";
7663 break;
7664 case BuiltinType::LongLong:
7665 EncType = "sll";
7666 break;
7667 case BuiltinType::Float:
7668 EncType = "ft";
7669 break;
7670 case BuiltinType::Double:
7671 EncType = "d";
7672 break;
7673 case BuiltinType::LongDouble:
7674 EncType = "ld";
7675 break;
7676 default:
7677 return false;
7678 }
7679 Enc += EncType;
7680 return true;
7681}
7682
7683/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7684static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7685 const CodeGen::CodeGenModule &CGM,
7686 TypeStringCache &TSC) {
7687 Enc += "p(";
7688 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7689 return false;
7690 Enc += ')';
7691 return true;
7692}
7693
7694/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007695static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7696 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007697 const CodeGen::CodeGenModule &CGM,
7698 TypeStringCache &TSC, StringRef NoSizeEnc) {
7699 if (AT->getSizeModifier() != ArrayType::Normal)
7700 return false;
7701 Enc += "a(";
7702 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7703 CAT->getSize().toStringUnsigned(Enc);
7704 else
7705 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7706 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007707 // The Qualifiers should be attached to the type rather than the array.
7708 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007709 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7710 return false;
7711 Enc += ')';
7712 return true;
7713}
7714
7715/// Appends a function encoding to Enc, calling appendType for the return type
7716/// and the arguments.
7717static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7718 const CodeGen::CodeGenModule &CGM,
7719 TypeStringCache &TSC) {
7720 Enc += "f{";
7721 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7722 return false;
7723 Enc += "}(";
7724 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7725 // N.B. we are only interested in the adjusted param types.
7726 auto I = FPT->param_type_begin();
7727 auto E = FPT->param_type_end();
7728 if (I != E) {
7729 do {
7730 if (!appendType(Enc, *I, CGM, TSC))
7731 return false;
7732 ++I;
7733 if (I != E)
7734 Enc += ',';
7735 } while (I != E);
7736 if (FPT->isVariadic())
7737 Enc += ",va";
7738 } else {
7739 if (FPT->isVariadic())
7740 Enc += "va";
7741 else
7742 Enc += '0';
7743 }
7744 }
7745 Enc += ')';
7746 return true;
7747}
7748
7749/// Handles the type's qualifier before dispatching a call to handle specific
7750/// type encodings.
7751static bool appendType(SmallStringEnc &Enc, QualType QType,
7752 const CodeGen::CodeGenModule &CGM,
7753 TypeStringCache &TSC) {
7754
7755 QualType QT = QType.getCanonicalType();
7756
Robert Lytton6adb20f2014-06-05 09:06:21 +00007757 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7758 // The Qualifiers should be attached to the type rather than the array.
7759 // Thus we don't call appendQualifier() here.
7760 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7761
Robert Lytton844aeeb2014-05-02 09:33:20 +00007762 appendQualifier(Enc, QT);
7763
7764 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7765 return appendBuiltinType(Enc, BT);
7766
Robert Lytton844aeeb2014-05-02 09:33:20 +00007767 if (const PointerType *PT = QT->getAs<PointerType>())
7768 return appendPointerType(Enc, PT, CGM, TSC);
7769
7770 if (const EnumType *ET = QT->getAs<EnumType>())
7771 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7772
7773 if (const RecordType *RT = QT->getAsStructureType())
7774 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7775
7776 if (const RecordType *RT = QT->getAsUnionType())
7777 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7778
7779 if (const FunctionType *FT = QT->getAs<FunctionType>())
7780 return appendFunctionType(Enc, FT, CGM, TSC);
7781
7782 return false;
7783}
7784
7785static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7786 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7787 if (!D)
7788 return false;
7789
7790 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7791 if (FD->getLanguageLinkage() != CLanguageLinkage)
7792 return false;
7793 return appendType(Enc, FD->getType(), CGM, TSC);
7794 }
7795
7796 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7797 if (VD->getLanguageLinkage() != CLanguageLinkage)
7798 return false;
7799 QualType QT = VD->getType().getCanonicalType();
7800 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7801 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007802 // The Qualifiers should be attached to the type rather than the array.
7803 // Thus we don't call appendQualifier() here.
7804 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007805 }
7806 return appendType(Enc, QT, CGM, TSC);
7807 }
7808 return false;
7809}
7810
7811
Robert Lytton0e076492013-08-13 09:43:10 +00007812//===----------------------------------------------------------------------===//
7813// Driver code
7814//===----------------------------------------------------------------------===//
7815
Rafael Espindola9f834732014-09-19 01:54:22 +00007816const llvm::Triple &CodeGenModule::getTriple() const {
7817 return getTarget().getTriple();
7818}
7819
7820bool CodeGenModule::supportsCOMDAT() const {
7821 return !getTriple().isOSBinFormatMachO();
7822}
7823
Chris Lattner2b037972010-07-29 02:01:43 +00007824const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007825 if (TheTargetCodeGenInfo)
7826 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007827
Reid Kleckner9305fd12016-04-13 23:37:17 +00007828 // Helper to set the unique_ptr while still keeping the return value.
7829 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
7830 this->TheTargetCodeGenInfo.reset(P);
7831 return *P;
7832 };
7833
John McCallc8e01702013-04-16 22:48:15 +00007834 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007835 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007836 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007837 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007838
Derek Schuff09338a22012-09-06 17:37:28 +00007839 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007840 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007841 case llvm::Triple::mips:
7842 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007843 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00007844 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
7845 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007846
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007847 case llvm::Triple::mips64:
7848 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007849 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007850
Tim Northover25e8a672014-05-24 12:51:25 +00007851 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007852 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007853 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007854 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007855 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007856
Reid Kleckner9305fd12016-04-13 23:37:17 +00007857 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007858 }
7859
Dan Gohmanc2853072015-09-03 22:51:53 +00007860 case llvm::Triple::wasm32:
7861 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007862 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00007863
Daniel Dunbard59655c2009-09-12 00:59:49 +00007864 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007865 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007866 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007867 case llvm::Triple::thumbeb: {
7868 if (Triple.getOS() == llvm::Triple::Win32) {
7869 return SetCGInfo(
7870 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007871 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007872
Reid Kleckner9305fd12016-04-13 23:37:17 +00007873 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
7874 StringRef ABIStr = getTarget().getABI();
7875 if (ABIStr == "apcs-gnu")
7876 Kind = ARMABIInfo::APCS;
7877 else if (ABIStr == "aapcs16")
7878 Kind = ARMABIInfo::AAPCS16_VFP;
7879 else if (CodeGenOpts.FloatABI == "hard" ||
7880 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007881 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
7882 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00007883 Kind = ARMABIInfo::AAPCS_VFP;
7884
7885 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
7886 }
7887
John McCallea8d8bb2010-03-11 00:10:12 +00007888 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007889 return SetCGInfo(
7890 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007891 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007892 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007893 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007894 if (getTarget().getABI() == "elfv2")
7895 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007896 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007897
Reid Kleckner9305fd12016-04-13 23:37:17 +00007898 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007899 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00007900 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007901 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007902 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007903 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007904 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007905 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007906 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007907
Reid Kleckner9305fd12016-04-13 23:37:17 +00007908 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007909 }
John McCallea8d8bb2010-03-11 00:10:12 +00007910
Peter Collingbournec947aae2012-05-20 23:28:41 +00007911 case llvm::Triple::nvptx:
7912 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007913 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007914
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007915 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007916 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007917
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007918 case llvm::Triple::systemz: {
7919 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00007920 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007921 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007922
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007923 case llvm::Triple::tce:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007924 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007925
Eli Friedman33465822011-07-08 23:31:17 +00007926 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007927 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007928 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007929 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007930 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007931
John McCall1fe2a8c2013-06-18 02:46:29 +00007932 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007933 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
7934 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7935 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007936 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007937 return SetCGInfo(new X86_32TargetCodeGenInfo(
7938 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7939 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7940 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007941 }
Eli Friedman33465822011-07-08 23:31:17 +00007942 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007943
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007944 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007945 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00007946 X86AVXABILevel AVXLevel =
7947 (ABI == "avx512"
7948 ? X86AVXABILevel::AVX512
7949 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007950
Chris Lattner04dc9572010-08-31 16:44:54 +00007951 switch (Triple.getOS()) {
7952 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007953 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007954 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007955 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007956 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007957 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007958 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007959 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007960 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007961 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00007962 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007963 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007964 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007965 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007966 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007967 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007968 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007969 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007970 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007971 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00007972 case llvm::Triple::spir:
7973 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007974 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007975 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007976}