blob: bbe98df77c9ef66d39ba1a6aa256320365c0e8af [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.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000275 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
276 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000277 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
278 }
279
280 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
281 return Addr;
282}
283
284/// Emit va_arg for a platform using the common void* representation,
285/// where arguments are simply emitted in an array of slots on the stack.
286///
287/// \param IsIndirect - Values of this type are passed indirectly.
288/// \param ValueInfo - The size and alignment of this type, generally
289/// computed with getContext().getTypeInfoInChars(ValueTy).
290/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
291/// Each argument will be allocated to a multiple of this number of
292/// slots, and all the slots will be aligned to this value.
293/// \param AllowHigherAlign - The slot alignment is not a cap;
294/// an argument type with an alignment greater than the slot size
295/// will be emitted on a higher-alignment address, potentially
296/// leaving one or more empty slots behind as padding.
297static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
298 QualType ValueTy, bool IsIndirect,
299 std::pair<CharUnits, CharUnits> ValueInfo,
300 CharUnits SlotSizeAndAlign,
301 bool AllowHigherAlign) {
302 // The size and alignment of the value that was passed directly.
303 CharUnits DirectSize, DirectAlign;
304 if (IsIndirect) {
305 DirectSize = CGF.getPointerSize();
306 DirectAlign = CGF.getPointerAlign();
307 } else {
308 DirectSize = ValueInfo.first;
309 DirectAlign = ValueInfo.second;
310 }
311
312 // Cast the address we've calculated to the right type.
313 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
314 if (IsIndirect)
315 DirectTy = DirectTy->getPointerTo(0);
316
317 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
318 DirectSize, DirectAlign,
319 SlotSizeAndAlign,
320 AllowHigherAlign);
321
322 if (IsIndirect) {
323 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
324 }
325
326 return Addr;
327
328}
329
330static Address emitMergePHI(CodeGenFunction &CGF,
331 Address Addr1, llvm::BasicBlock *Block1,
332 Address Addr2, llvm::BasicBlock *Block2,
333 const llvm::Twine &Name = "") {
334 assert(Addr1.getType() == Addr2.getType());
335 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
336 PHI->addIncoming(Addr1.getPointer(), Block1);
337 PHI->addIncoming(Addr2.getPointer(), Block2);
338 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
339 return Address(PHI, Align);
340}
341
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000342TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
343
John McCall3480ef22011-08-30 01:42:09 +0000344// If someone can figure out a general rule for this, that would be great.
345// It's probably just doomed to be platform-dependent, though.
346unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
347 // Verified for:
348 // x86-64 FreeBSD, Linux, Darwin
349 // x86-32 FreeBSD, Linux, Darwin
350 // PowerPC Linux, Darwin
351 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000352 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000353 return 32;
354}
355
John McCalla729c622012-02-17 03:33:10 +0000356bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
357 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000358 // The following conventions are known to require this to be false:
359 // x86_stdcall
360 // MIPS
361 // For everything else, we just prefer false unless we opt out.
362 return false;
363}
364
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000365void
366TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
367 llvm::SmallString<24> &Opt) const {
368 // This assumes the user is passing a library name like "rt" instead of a
369 // filename like "librt.a/so", and that they don't care whether it's static or
370 // dynamic.
371 Opt = "-l";
372 Opt += Lib;
373}
374
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000375static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000376
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000377/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000378/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000379static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
380 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000381 if (FD->isUnnamedBitfield())
382 return true;
383
384 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000385
Eli Friedman0b3f2012011-11-18 03:47:20 +0000386 // Constant arrays of empty records count as empty, strip them off.
387 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000388 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000389 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
390 if (AT->getSize() == 0)
391 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000392 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000393 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000394
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000395 const RecordType *RT = FT->getAs<RecordType>();
396 if (!RT)
397 return false;
398
399 // C++ record fields are never empty, at least in the Itanium ABI.
400 //
401 // FIXME: We should use a predicate for whether this behavior is true in the
402 // current ABI.
403 if (isa<CXXRecordDecl>(RT->getDecl()))
404 return false;
405
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000406 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000407}
408
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000409/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000410/// fields. Note that a structure with a flexible array member is not
411/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000412static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000413 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000414 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000415 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000416 const RecordDecl *RD = RT->getDecl();
417 if (RD->hasFlexibleArrayMember())
418 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000419
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000420 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000421 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000422 for (const auto &I : CXXRD->bases())
423 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000424 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000425
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000426 for (const auto *I : RD->fields())
427 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000428 return false;
429 return true;
430}
431
432/// isSingleElementStruct - Determine if a structure is a "single
433/// element struct", i.e. it has exactly one non-empty field or
434/// exactly one field which is itself a single element
435/// struct. Structures with flexible array members are never
436/// considered single element structs.
437///
438/// \return The field declaration for the single non-empty field, if
439/// it exists.
440static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000441 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000442 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000443 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000444
445 const RecordDecl *RD = RT->getDecl();
446 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000447 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000448
Craig Topper8a13c412014-05-21 05:09:00 +0000449 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000450
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000451 // If this is a C++ record, check the bases first.
452 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000453 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000454 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000455 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000456 continue;
457
458 // If we already found an element then this isn't a single-element struct.
459 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000460 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000461
462 // If this is non-empty and not a single element struct, the composite
463 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000464 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000465 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000466 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000467 }
468 }
469
470 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000471 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000472 QualType FT = FD->getType();
473
474 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000475 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000476 continue;
477
478 // If we already found an element then this isn't a single-element
479 // struct.
480 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000481 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000482
483 // Treat single element arrays as the element.
484 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
485 if (AT->getSize().getZExtValue() != 1)
486 break;
487 FT = AT->getElementType();
488 }
489
John McCalla1dee5302010-08-22 10:59:02 +0000490 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000491 Found = FT.getTypePtr();
492 } else {
493 Found = isSingleElementStruct(FT, Context);
494 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000495 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000496 }
497 }
498
Eli Friedmanee945342011-11-18 01:25:50 +0000499 // We don't consider a struct a single-element struct if it has
500 // padding beyond the element type.
501 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000502 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000503
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000504 return Found;
505}
506
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000507namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000508Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
509 const ABIArgInfo &AI) {
510 // This default implementation defers to the llvm backend's va_arg
511 // instruction. It can handle only passing arguments directly
512 // (typically only handled in the backend for primitive types), or
513 // aggregates passed indirectly by pointer (NOTE: if the "byval"
514 // flag has ABI impact in the callee, this implementation cannot
515 // work.)
516
517 // Only a few cases are covered here at the moment -- those needed
518 // by the default abi.
519 llvm::Value *Val;
520
521 if (AI.isIndirect()) {
522 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000523 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000524 assert(
525 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000526 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000527
528 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
529 CharUnits TyAlignForABI = TyInfo.second;
530
531 llvm::Type *BaseTy =
532 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
533 llvm::Value *Addr =
534 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
535 return Address(Addr, TyAlignForABI);
536 } else {
537 assert((AI.isDirect() || AI.isExtend()) &&
538 "Unexpected ArgInfo Kind in generic VAArg emitter!");
539
540 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000541 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000542 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000543 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000544 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000545 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000546 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000547 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000548
549 Address Temp = CGF.CreateMemTemp(Ty, "varet");
550 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
551 CGF.Builder.CreateStore(Val, Temp);
552 return Temp;
553 }
554}
555
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000556/// DefaultABIInfo - The default implementation for ABI specific
557/// details. This implementation provides information which results in
558/// self-consistent and sensible LLVM IR generation, but does not
559/// conform to any particular ABI.
560class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000561public:
562 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000563
Chris Lattner458b2aa2010-07-29 02:16:43 +0000564 ABIArgInfo classifyReturnType(QualType RetTy) const;
565 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000566
Craig Topper4f12f102014-03-12 06:41:41 +0000567 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000568 if (!getCXXABI().classifyReturnType(FI))
569 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000570 for (auto &I : FI.arguments())
571 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000572 }
573
John McCall7f416cc2015-09-08 08:05:57 +0000574 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000575 QualType Ty) const override {
576 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
577 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578};
579
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000580class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
581public:
Chris Lattner2b037972010-07-29 02:01:43 +0000582 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
583 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000584};
585
Chris Lattner458b2aa2010-07-29 02:16:43 +0000586ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000587 Ty = useFirstFieldIfTransparentUnion(Ty);
588
589 if (isAggregateTypeForABI(Ty)) {
590 // Records with non-trivial destructors/copy-constructors should not be
591 // passed by value.
592 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000593 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000594
John McCall7f416cc2015-09-08 08:05:57 +0000595 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000596 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000597
Chris Lattner9723d6c2010-03-11 18:19:55 +0000598 // Treat an enum type as its underlying type.
599 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
600 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000601
Chris Lattner9723d6c2010-03-11 18:19:55 +0000602 return (Ty->isPromotableIntegerType() ?
603 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000604}
605
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000606ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
607 if (RetTy->isVoidType())
608 return ABIArgInfo::getIgnore();
609
610 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000611 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000612
613 // Treat an enum type as its underlying type.
614 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
615 RetTy = EnumTy->getDecl()->getIntegerType();
616
617 return (RetTy->isPromotableIntegerType() ?
618 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
619}
620
Derek Schuff09338a22012-09-06 17:37:28 +0000621//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000622// WebAssembly ABI Implementation
623//
624// This is a very simple ABI that relies a lot on DefaultABIInfo.
625//===----------------------------------------------------------------------===//
626
627class WebAssemblyABIInfo final : public DefaultABIInfo {
628public:
629 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
630 : DefaultABIInfo(CGT) {}
631
632private:
633 ABIArgInfo classifyReturnType(QualType RetTy) const;
634 ABIArgInfo classifyArgumentType(QualType Ty) const;
635
636 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000637 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000638 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000639 void computeInfo(CGFunctionInfo &FI) const override {
640 if (!getCXXABI().classifyReturnType(FI))
641 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
642 for (auto &Arg : FI.arguments())
643 Arg.info = classifyArgumentType(Arg.type);
644 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000645
646 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
647 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000648};
649
650class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
651public:
652 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
653 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
654};
655
656/// \brief Classify argument of given type \p Ty.
657ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
658 Ty = useFirstFieldIfTransparentUnion(Ty);
659
660 if (isAggregateTypeForABI(Ty)) {
661 // Records with non-trivial destructors/copy-constructors should not be
662 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000663 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000664 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000665 // Ignore empty structs/unions.
666 if (isEmptyRecord(getContext(), Ty, true))
667 return ABIArgInfo::getIgnore();
668 // Lower single-element structs to just pass a regular value. TODO: We
669 // could do reasonable-size multiple-element structs too, using getExpand(),
670 // though watch out for things like bitfields.
671 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
672 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000673 }
674
675 // Otherwise just do the default thing.
676 return DefaultABIInfo::classifyArgumentType(Ty);
677}
678
679ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
680 if (isAggregateTypeForABI(RetTy)) {
681 // Records with non-trivial destructors/copy-constructors should not be
682 // returned by value.
683 if (!getRecordArgABI(RetTy, getCXXABI())) {
684 // Ignore empty structs/unions.
685 if (isEmptyRecord(getContext(), RetTy, true))
686 return ABIArgInfo::getIgnore();
687 // Lower single-element structs to just return a regular value. TODO: We
688 // could do reasonable-size multiple-element structs too, using
689 // ABIArgInfo::getDirect().
690 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
691 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
692 }
693 }
694
695 // Otherwise just do the default thing.
696 return DefaultABIInfo::classifyReturnType(RetTy);
697}
698
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000699Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
700 QualType Ty) const {
701 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
702 getContext().getTypeInfoInChars(Ty),
703 CharUnits::fromQuantity(4),
704 /*AllowHigherAlign=*/ true);
705}
706
Dan Gohmanc2853072015-09-03 22:51:53 +0000707//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000708// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000709//
710// This is a simplified version of the x86_32 ABI. Arguments and return values
711// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000712//===----------------------------------------------------------------------===//
713
714class PNaClABIInfo : public ABIInfo {
715 public:
716 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
717
718 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000719 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000720
Craig Topper4f12f102014-03-12 06:41:41 +0000721 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000722 Address EmitVAArg(CodeGenFunction &CGF,
723 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000724};
725
726class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
727 public:
728 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
729 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
730};
731
732void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000733 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000734 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
735
Reid Kleckner40ca9132014-05-13 22:05:45 +0000736 for (auto &I : FI.arguments())
737 I.info = classifyArgumentType(I.type);
738}
Derek Schuff09338a22012-09-06 17:37:28 +0000739
John McCall7f416cc2015-09-08 08:05:57 +0000740Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
741 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000742 // The PNaCL ABI is a bit odd, in that varargs don't use normal
743 // function classification. Structs get passed directly for varargs
744 // functions, through a rewriting transform in
745 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
746 // this target to actually support a va_arg instructions with an
747 // aggregate type, unlike other targets.
748 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000749}
750
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000751/// \brief Classify argument of given type \p Ty.
752ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000753 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000754 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000755 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
756 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000757 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
758 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000759 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000760 } else if (Ty->isFloatingType()) {
761 // Floating-point types don't go inreg.
762 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000763 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000764
765 return (Ty->isPromotableIntegerType() ?
766 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000767}
768
769ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
770 if (RetTy->isVoidType())
771 return ABIArgInfo::getIgnore();
772
Eli Benderskye20dad62013-04-04 22:49:35 +0000773 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000774 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000775 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000776
777 // Treat an enum type as its underlying type.
778 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
779 RetTy = EnumTy->getDecl()->getIntegerType();
780
781 return (RetTy->isPromotableIntegerType() ?
782 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
783}
784
Chad Rosier651c1832013-03-25 21:00:27 +0000785/// IsX86_MMXType - Return true if this is an MMX type.
786bool IsX86_MMXType(llvm::Type *IRType) {
787 // 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 +0000788 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
789 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
790 IRType->getScalarSizeInBits() != 64;
791}
792
Jay Foad7c57be32011-07-11 09:56:20 +0000793static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000794 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000795 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000796 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
797 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
798 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000799 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000800 }
801
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000802 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000803 }
804
805 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000806 return Ty;
807}
808
Reid Kleckner80944df2014-10-31 22:00:51 +0000809/// Returns true if this type can be passed in SSE registers with the
810/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
811static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
812 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
813 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
814 return true;
815 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
816 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
817 // registers specially.
818 unsigned VecSize = Context.getTypeSize(VT);
819 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
820 return true;
821 }
822 return false;
823}
824
825/// Returns true if this aggregate is small enough to be passed in SSE registers
826/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
827static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
828 return NumMembers <= 4;
829}
830
Chris Lattner0cf24192010-06-28 20:05:43 +0000831//===----------------------------------------------------------------------===//
832// X86-32 ABI Implementation
833//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000834
Reid Kleckner661f35b2014-01-18 01:12:41 +0000835/// \brief Similar to llvm::CCState, but for Clang.
836struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000837 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000838
839 unsigned CC;
840 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000841 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000842};
843
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000844/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000845class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000846 enum Class {
847 Integer,
848 Float
849 };
850
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000851 static const unsigned MinABIStackAlignInBytes = 4;
852
David Chisnallde3a0692009-08-17 23:08:21 +0000853 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000854 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000855 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000856 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000857 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000858 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000859
860 static bool isRegisterSize(unsigned Size) {
861 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
862 }
863
Reid Kleckner80944df2014-10-31 22:00:51 +0000864 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
865 // FIXME: Assumes vectorcall is in use.
866 return isX86VectorTypeForVectorCall(getContext(), Ty);
867 }
868
869 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
870 uint64_t NumMembers) const override {
871 // FIXME: Assumes vectorcall is in use.
872 return isX86VectorCallAggregateSmallEnough(NumMembers);
873 }
874
Reid Kleckner40ca9132014-05-13 22:05:45 +0000875 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000876
Daniel Dunbar557893d2010-04-21 19:10:51 +0000877 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
878 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000879 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
880
John McCall7f416cc2015-09-08 08:05:57 +0000881 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000882
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000883 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000884 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000885
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000886 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000887 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000888 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000889 /// \brief Updates the number of available free registers, returns
890 /// true if any registers were allocated.
891 bool updateFreeRegs(QualType Ty, CCState &State) const;
892
893 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
894 bool &NeedsPadding) const;
895 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000896
Reid Kleckner04046052016-05-02 17:41:07 +0000897 bool canExpandIndirectArgument(QualType Ty) const;
898
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000899 /// \brief Rewrite the function info so that all memory arguments use
900 /// inalloca.
901 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
902
903 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000904 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000905 QualType Type) const;
906
Rafael Espindola75419dc2012-07-23 23:30:29 +0000907public:
908
Craig Topper4f12f102014-03-12 06:41:41 +0000909 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000910 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
911 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000912
Michael Kupersteindc745202015-10-19 07:52:25 +0000913 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
914 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000915 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000916 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000917 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
918 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000919 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000920 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000921 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000922
923 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
924 ArrayRef<llvm::Type*> scalars,
925 bool asReturnValue) const override {
926 // LLVM's x86-32 lowering currently only assigns up to three
927 // integer registers and three fp registers. Oddly, it'll use up to
928 // four vector registers for vectors, but those can overlap with the
929 // scalar registers.
930 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
931 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000932};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000933
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000934class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
935public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000936 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
937 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000938 unsigned NumRegisterParameters, bool SoftFloatABI)
939 : TargetCodeGenInfo(new X86_32ABIInfo(
940 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
941 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000942
John McCall1fe2a8c2013-06-18 02:46:29 +0000943 static bool isStructReturnInRegABI(
944 const llvm::Triple &Triple, const CodeGenOptions &Opts);
945
Eric Christopher162c91c2015-06-05 22:03:00 +0000946 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000947 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000948
Craig Topper4f12f102014-03-12 06:41:41 +0000949 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000950 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000951 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000952 return 4;
953 }
954
955 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000956 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000957
Jay Foad7c57be32011-07-11 09:56:20 +0000958 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000959 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000960 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000961 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
962 }
963
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000964 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
965 std::string &Constraints,
966 std::vector<llvm::Type *> &ResultRegTypes,
967 std::vector<llvm::Type *> &ResultTruncRegTypes,
968 std::vector<LValue> &ResultRegDests,
969 std::string &AsmString,
970 unsigned NumOutputs) const override;
971
Craig Topper4f12f102014-03-12 06:41:41 +0000972 llvm::Constant *
973 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000974 unsigned Sig = (0xeb << 0) | // jmp rel8
975 (0x06 << 8) | // .+0x08
976 ('F' << 16) |
977 ('T' << 24);
978 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
979 }
John McCall01391782016-02-05 21:37:38 +0000980
981 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
982 return "movl\t%ebp, %ebp"
983 "\t\t## marker for objc_retainAutoreleaseReturnValue";
984 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000985};
986
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000987}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000988
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000989/// Rewrite input constraint references after adding some output constraints.
990/// In the case where there is one output and one input and we add one output,
991/// we need to replace all operand references greater than or equal to 1:
992/// mov $0, $1
993/// mov eax, $1
994/// The result will be:
995/// mov $0, $2
996/// mov eax, $2
997static void rewriteInputConstraintReferences(unsigned FirstIn,
998 unsigned NumNewOuts,
999 std::string &AsmString) {
1000 std::string Buf;
1001 llvm::raw_string_ostream OS(Buf);
1002 size_t Pos = 0;
1003 while (Pos < AsmString.size()) {
1004 size_t DollarStart = AsmString.find('$', Pos);
1005 if (DollarStart == std::string::npos)
1006 DollarStart = AsmString.size();
1007 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1008 if (DollarEnd == std::string::npos)
1009 DollarEnd = AsmString.size();
1010 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1011 Pos = DollarEnd;
1012 size_t NumDollars = DollarEnd - DollarStart;
1013 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1014 // We have an operand reference.
1015 size_t DigitStart = Pos;
1016 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1017 if (DigitEnd == std::string::npos)
1018 DigitEnd = AsmString.size();
1019 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1020 unsigned OperandIndex;
1021 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1022 if (OperandIndex >= FirstIn)
1023 OperandIndex += NumNewOuts;
1024 OS << OperandIndex;
1025 } else {
1026 OS << OperandStr;
1027 }
1028 Pos = DigitEnd;
1029 }
1030 }
1031 AsmString = std::move(OS.str());
1032}
1033
1034/// Add output constraints for EAX:EDX because they are return registers.
1035void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1036 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1037 std::vector<llvm::Type *> &ResultRegTypes,
1038 std::vector<llvm::Type *> &ResultTruncRegTypes,
1039 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1040 unsigned NumOutputs) const {
1041 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1042
1043 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1044 // larger.
1045 if (!Constraints.empty())
1046 Constraints += ',';
1047 if (RetWidth <= 32) {
1048 Constraints += "={eax}";
1049 ResultRegTypes.push_back(CGF.Int32Ty);
1050 } else {
1051 // Use the 'A' constraint for EAX:EDX.
1052 Constraints += "=A";
1053 ResultRegTypes.push_back(CGF.Int64Ty);
1054 }
1055
1056 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1057 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1058 ResultTruncRegTypes.push_back(CoerceTy);
1059
1060 // Coerce the integer by bitcasting the return slot pointer.
1061 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1062 CoerceTy->getPointerTo()));
1063 ResultRegDests.push_back(ReturnSlot);
1064
1065 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1066}
1067
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001068/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001069/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001070bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1071 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001072 uint64_t Size = Context.getTypeSize(Ty);
1073
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001074 // For i386, type must be register sized.
1075 // For the MCU ABI, it only needs to be <= 8-byte
1076 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1077 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001078
1079 if (Ty->isVectorType()) {
1080 // 64- and 128- bit vectors inside structures are not returned in
1081 // registers.
1082 if (Size == 64 || Size == 128)
1083 return false;
1084
1085 return true;
1086 }
1087
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001088 // If this is a builtin, pointer, enum, complex type, member pointer, or
1089 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001090 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001091 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001092 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001093 return true;
1094
1095 // Arrays are treated like records.
1096 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001097 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001098
1099 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001100 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101 if (!RT) return false;
1102
Anders Carlsson40446e82010-01-27 03:25:19 +00001103 // FIXME: Traverse bases here too.
1104
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001105 // Structure types are passed in register if all fields would be
1106 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001107 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001108 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001109 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001110 continue;
1111
1112 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001113 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001114 return false;
1115 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116 return true;
1117}
1118
Reid Kleckner04046052016-05-02 17:41:07 +00001119static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1120 // Treat complex types as the element type.
1121 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1122 Ty = CTy->getElementType();
1123
1124 // Check for a type which we know has a simple scalar argument-passing
1125 // convention without any padding. (We're specifically looking for 32
1126 // and 64-bit integer and integer-equivalents, float, and double.)
1127 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1128 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1129 return false;
1130
1131 uint64_t Size = Context.getTypeSize(Ty);
1132 return Size == 32 || Size == 64;
1133}
1134
1135/// Test whether an argument type which is to be passed indirectly (on the
1136/// stack) would have the equivalent layout if it was expanded into separate
1137/// arguments. If so, we prefer to do the latter to avoid inhibiting
1138/// optimizations.
1139bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1140 // We can only expand structure types.
1141 const RecordType *RT = Ty->getAs<RecordType>();
1142 if (!RT)
1143 return false;
1144 const RecordDecl *RD = RT->getDecl();
1145 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1146 if (!IsWin32StructABI ) {
1147 // On non-Windows, we have to conservatively match our old bitcode
1148 // prototypes in order to be ABI-compatible at the bitcode level.
1149 if (!CXXRD->isCLike())
1150 return false;
1151 } else {
1152 // Don't do this for dynamic classes.
1153 if (CXXRD->isDynamicClass())
1154 return false;
1155 // Don't do this if there are any non-empty bases.
1156 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1157 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1158 return false;
1159 }
1160 }
1161 }
1162
1163 uint64_t Size = 0;
1164
1165 for (const auto *FD : RD->fields()) {
1166 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1167 // argument is smaller than 32-bits, expanding the struct will create
1168 // alignment padding.
1169 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1170 return false;
1171
1172 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1173 // how to expand them yet, and the predicate for telling if a bitfield still
1174 // counts as "basic" is more complicated than what we were doing previously.
1175 if (FD->isBitField())
1176 return false;
1177
1178 Size += getContext().getTypeSize(FD->getType());
1179 }
1180
1181 // We can do this if there was no alignment padding.
1182 return Size == getContext().getTypeSize(Ty);
1183}
1184
John McCall7f416cc2015-09-08 08:05:57 +00001185ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001186 // If the return value is indirect, then the hidden argument is consuming one
1187 // integer register.
1188 if (State.FreeRegs) {
1189 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001190 if (!IsMCUABI)
1191 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001192 }
John McCall7f416cc2015-09-08 08:05:57 +00001193 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001194}
1195
Eric Christopher7565e0d2015-05-29 23:09:49 +00001196ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1197 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001198 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001199 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001200
Reid Kleckner80944df2014-10-31 22:00:51 +00001201 const Type *Base = nullptr;
1202 uint64_t NumElts = 0;
1203 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1204 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1205 // The LLVM struct type for such an aggregate should lower properly.
1206 return ABIArgInfo::getDirect();
1207 }
1208
Chris Lattner458b2aa2010-07-29 02:16:43 +00001209 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001210 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001211 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001212 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001213
1214 // 128-bit vectors are a special case; they are returned in
1215 // registers and we need to make sure to pick a type the LLVM
1216 // backend will like.
1217 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001218 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001219 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001220
1221 // Always return in register if it fits in a general purpose
1222 // register, or if it is 64 bits and has a single element.
1223 if ((Size == 8 || Size == 16 || Size == 32) ||
1224 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001225 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001226 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001227
John McCall7f416cc2015-09-08 08:05:57 +00001228 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001229 }
1230
1231 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001232 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001233
John McCalla1dee5302010-08-22 10:59:02 +00001234 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001235 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001236 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001237 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001238 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001239 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001240
David Chisnallde3a0692009-08-17 23:08:21 +00001241 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001242 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001243 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001244
Denis Zobnin380b2242016-02-11 11:26:03 +00001245 // Ignore empty structs/unions.
1246 if (isEmptyRecord(getContext(), RetTy, true))
1247 return ABIArgInfo::getIgnore();
1248
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001249 // Small structures which are register sized are generally returned
1250 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001251 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001252 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001253
1254 // As a special-case, if the struct is a "single-element" struct, and
1255 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001256 // floating-point register. (MSVC does not apply this special case.)
1257 // We apply a similar transformation for pointer types to improve the
1258 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001259 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001260 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001261 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001262 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1263
1264 // FIXME: We should be able to narrow this integer in cases with dead
1265 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001266 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001267 }
1268
John McCall7f416cc2015-09-08 08:05:57 +00001269 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001270 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001271
Chris Lattner458b2aa2010-07-29 02:16:43 +00001272 // Treat an enum type as its underlying type.
1273 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1274 RetTy = EnumTy->getDecl()->getIntegerType();
1275
1276 return (RetTy->isPromotableIntegerType() ?
1277 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278}
1279
Eli Friedman7919bea2012-06-05 19:40:46 +00001280static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1281 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1282}
1283
Daniel Dunbared23de32010-09-16 20:42:00 +00001284static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1285 const RecordType *RT = Ty->getAs<RecordType>();
1286 if (!RT)
1287 return 0;
1288 const RecordDecl *RD = RT->getDecl();
1289
1290 // If this is a C++ record, check the bases first.
1291 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001292 for (const auto &I : CXXRD->bases())
1293 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001294 return false;
1295
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001296 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001297 QualType FT = i->getType();
1298
Eli Friedman7919bea2012-06-05 19:40:46 +00001299 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001300 return true;
1301
1302 if (isRecordWithSSEVectorType(Context, FT))
1303 return true;
1304 }
1305
1306 return false;
1307}
1308
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001309unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1310 unsigned Align) const {
1311 // Otherwise, if the alignment is less than or equal to the minimum ABI
1312 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001313 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001314 return 0; // Use default alignment.
1315
1316 // On non-Darwin, the stack type alignment is always 4.
1317 if (!IsDarwinVectorABI) {
1318 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001319 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001320 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001321
Daniel Dunbared23de32010-09-16 20:42:00 +00001322 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001323 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1324 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001325 return 16;
1326
1327 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001328}
1329
Rafael Espindola703c47f2012-10-19 05:04:37 +00001330ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001331 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001332 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001333 if (State.FreeRegs) {
1334 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001335 if (!IsMCUABI)
1336 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001337 }
John McCall7f416cc2015-09-08 08:05:57 +00001338 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001339 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001340
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001341 // Compute the byval alignment.
1342 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1343 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1344 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001345 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001346
1347 // If the stack alignment is less than the type alignment, realign the
1348 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001349 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001350 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1351 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001352}
1353
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001354X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1355 const Type *T = isSingleElementStruct(Ty, getContext());
1356 if (!T)
1357 T = Ty.getTypePtr();
1358
1359 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1360 BuiltinType::Kind K = BT->getKind();
1361 if (K == BuiltinType::Float || K == BuiltinType::Double)
1362 return Float;
1363 }
1364 return Integer;
1365}
1366
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001367bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001368 if (!IsSoftFloatABI) {
1369 Class C = classify(Ty);
1370 if (C == Float)
1371 return false;
1372 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001373
Rafael Espindola077dd592012-10-24 01:58:58 +00001374 unsigned Size = getContext().getTypeSize(Ty);
1375 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001376
1377 if (SizeInRegs == 0)
1378 return false;
1379
Michael Kuperstein68901882015-10-25 08:18:20 +00001380 if (!IsMCUABI) {
1381 if (SizeInRegs > State.FreeRegs) {
1382 State.FreeRegs = 0;
1383 return false;
1384 }
1385 } else {
1386 // The MCU psABI allows passing parameters in-reg even if there are
1387 // earlier parameters that are passed on the stack. Also,
1388 // it does not allow passing >8-byte structs in-register,
1389 // even if there are 3 free registers available.
1390 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1391 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001392 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001393
Reid Kleckner661f35b2014-01-18 01:12:41 +00001394 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001395 return true;
1396}
1397
1398bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1399 bool &InReg,
1400 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001401 // On Windows, aggregates other than HFAs are never passed in registers, and
1402 // they do not consume register slots. Homogenous floating-point aggregates
1403 // (HFAs) have already been dealt with at this point.
1404 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1405 return false;
1406
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001407 NeedsPadding = false;
1408 InReg = !IsMCUABI;
1409
1410 if (!updateFreeRegs(Ty, State))
1411 return false;
1412
1413 if (IsMCUABI)
1414 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001415
Reid Kleckner80944df2014-10-31 22:00:51 +00001416 if (State.CC == llvm::CallingConv::X86_FastCall ||
1417 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001418 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001419 NeedsPadding = true;
1420
Rafael Espindola077dd592012-10-24 01:58:58 +00001421 return false;
1422 }
1423
Rafael Espindola703c47f2012-10-19 05:04:37 +00001424 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001425}
1426
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001427bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1428 if (!updateFreeRegs(Ty, State))
1429 return false;
1430
1431 if (IsMCUABI)
1432 return false;
1433
1434 if (State.CC == llvm::CallingConv::X86_FastCall ||
1435 State.CC == llvm::CallingConv::X86_VectorCall) {
1436 if (getContext().getTypeSize(Ty) > 32)
1437 return false;
1438
1439 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1440 Ty->isReferenceType());
1441 }
1442
1443 return true;
1444}
1445
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001446ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1447 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001448 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001449
Reid Klecknerb1be6832014-11-15 01:41:41 +00001450 Ty = useFirstFieldIfTransparentUnion(Ty);
1451
Reid Kleckner80944df2014-10-31 22:00:51 +00001452 // Check with the C++ ABI first.
1453 const RecordType *RT = Ty->getAs<RecordType>();
1454 if (RT) {
1455 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1456 if (RAA == CGCXXABI::RAA_Indirect) {
1457 return getIndirectResult(Ty, false, State);
1458 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1459 // The field index doesn't matter, we'll fix it up later.
1460 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1461 }
1462 }
1463
1464 // vectorcall adds the concept of a homogenous vector aggregate, similar
1465 // to other targets.
1466 const Type *Base = nullptr;
1467 uint64_t NumElts = 0;
1468 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1469 isHomogeneousAggregate(Ty, Base, NumElts)) {
1470 if (State.FreeSSERegs >= NumElts) {
1471 State.FreeSSERegs -= NumElts;
1472 if (Ty->isBuiltinType() || Ty->isVectorType())
1473 return ABIArgInfo::getDirect();
1474 return ABIArgInfo::getExpand();
1475 }
1476 return getIndirectResult(Ty, /*ByVal=*/false, State);
1477 }
1478
1479 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001480 // Structures with flexible arrays are always indirect.
1481 // FIXME: This should not be byval!
1482 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1483 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001484
Reid Kleckner04046052016-05-02 17:41:07 +00001485 // Ignore empty structs/unions on non-Windows.
1486 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001487 return ABIArgInfo::getIgnore();
1488
Rafael Espindolafad28de2012-10-24 01:59:00 +00001489 llvm::LLVMContext &LLVMContext = getVMContext();
1490 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001491 bool NeedsPadding = false;
1492 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001493 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001494 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001495 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001496 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001497 if (InReg)
1498 return ABIArgInfo::getDirectInReg(Result);
1499 else
1500 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001501 }
Craig Topper8a13c412014-05-21 05:09:00 +00001502 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001503
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001504 // Expand small (<= 128-bit) record types when we know that the stack layout
1505 // of those arguments will match the struct. This is important because the
1506 // LLVM backend isn't smart enough to remove byval, which inhibits many
1507 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001508 // Don't do this for the MCU if there are still free integer registers
1509 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001510 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1511 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001512 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001513 State.CC == llvm::CallingConv::X86_FastCall ||
1514 State.CC == llvm::CallingConv::X86_VectorCall,
1515 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001516
Reid Kleckner661f35b2014-01-18 01:12:41 +00001517 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001518 }
1519
Chris Lattnerd774ae92010-08-26 20:05:13 +00001520 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001521 // On Darwin, some vectors are passed in memory, we handle this by passing
1522 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001523 if (IsDarwinVectorABI) {
1524 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001525 if ((Size == 8 || Size == 16 || Size == 32) ||
1526 (Size == 64 && VT->getNumElements() == 1))
1527 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1528 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001529 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001530
Chad Rosier651c1832013-03-25 21:00:27 +00001531 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1532 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001533
Chris Lattnerd774ae92010-08-26 20:05:13 +00001534 return ABIArgInfo::getDirect();
1535 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001536
1537
Chris Lattner458b2aa2010-07-29 02:16:43 +00001538 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1539 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001540
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001541 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001542
1543 if (Ty->isPromotableIntegerType()) {
1544 if (InReg)
1545 return ABIArgInfo::getExtendInReg();
1546 return ABIArgInfo::getExtend();
1547 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001548
Rafael Espindola703c47f2012-10-19 05:04:37 +00001549 if (InReg)
1550 return ABIArgInfo::getDirectInReg();
1551 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001552}
1553
Rafael Espindolaa6472962012-07-24 00:01:07 +00001554void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001555 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001556 if (IsMCUABI)
1557 State.FreeRegs = 3;
1558 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001559 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001560 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1561 State.FreeRegs = 2;
1562 State.FreeSSERegs = 6;
1563 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001564 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001565 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001566 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001567
Reid Kleckner677539d2014-07-10 01:58:55 +00001568 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001569 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001570 } else if (FI.getReturnInfo().isIndirect()) {
1571 // The C++ ABI is not aware of register usage, so we have to check if the
1572 // return value was sret and put it in a register ourselves if appropriate.
1573 if (State.FreeRegs) {
1574 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001575 if (!IsMCUABI)
1576 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001577 }
1578 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001579
Peter Collingbournef7706832014-12-12 23:41:25 +00001580 // The chain argument effectively gives us another free register.
1581 if (FI.isChainCall())
1582 ++State.FreeRegs;
1583
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001584 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001585 for (auto &I : FI.arguments()) {
1586 I.info = classifyArgumentType(I.type, State);
1587 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001588 }
1589
1590 // If we needed to use inalloca for any argument, do a second pass and rewrite
1591 // all the memory arguments to use inalloca.
1592 if (UsedInAlloca)
1593 rewriteWithInAlloca(FI);
1594}
1595
1596void
1597X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001598 CharUnits &StackOffset, ABIArgInfo &Info,
1599 QualType Type) const {
1600 // Arguments are always 4-byte-aligned.
1601 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1602
1603 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001604 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1605 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001606 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001607
John McCall7f416cc2015-09-08 08:05:57 +00001608 // Insert padding bytes to respect alignment.
1609 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001610 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001611 if (StackOffset != FieldEnd) {
1612 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001613 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001614 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001615 FrameFields.push_back(Ty);
1616 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001617}
1618
Reid Kleckner852361d2014-07-26 00:12:26 +00001619static bool isArgInAlloca(const ABIArgInfo &Info) {
1620 // Leave ignored and inreg arguments alone.
1621 switch (Info.getKind()) {
1622 case ABIArgInfo::InAlloca:
1623 return true;
1624 case ABIArgInfo::Indirect:
1625 assert(Info.getIndirectByVal());
1626 return true;
1627 case ABIArgInfo::Ignore:
1628 return false;
1629 case ABIArgInfo::Direct:
1630 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001631 if (Info.getInReg())
1632 return false;
1633 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001634 case ABIArgInfo::Expand:
1635 case ABIArgInfo::CoerceAndExpand:
1636 // These are aggregate types which are never passed in registers when
1637 // inalloca is involved.
1638 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001639 }
1640 llvm_unreachable("invalid enum");
1641}
1642
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001643void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1644 assert(IsWin32StructABI && "inalloca only supported on win32");
1645
1646 // Build a packed struct type for all of the arguments in memory.
1647 SmallVector<llvm::Type *, 6> FrameFields;
1648
John McCall7f416cc2015-09-08 08:05:57 +00001649 // The stack alignment is always 4.
1650 CharUnits StackAlign = CharUnits::fromQuantity(4);
1651
1652 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001653 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1654
1655 // Put 'this' into the struct before 'sret', if necessary.
1656 bool IsThisCall =
1657 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1658 ABIArgInfo &Ret = FI.getReturnInfo();
1659 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1660 isArgInAlloca(I->info)) {
1661 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1662 ++I;
1663 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001664
1665 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001666 if (Ret.isIndirect() && !Ret.getInReg()) {
1667 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1668 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001669 // On Windows, the hidden sret parameter is always returned in eax.
1670 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001671 }
1672
1673 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001674 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001675 ++I;
1676
1677 // Put arguments passed in memory into the struct.
1678 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001679 if (isArgInAlloca(I->info))
1680 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001681 }
1682
1683 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001684 /*isPacked=*/true),
1685 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001686}
1687
John McCall7f416cc2015-09-08 08:05:57 +00001688Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1689 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001690
John McCall7f416cc2015-09-08 08:05:57 +00001691 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001692
John McCall7f416cc2015-09-08 08:05:57 +00001693 // x86-32 changes the alignment of certain arguments on the stack.
1694 //
1695 // Just messing with TypeInfo like this works because we never pass
1696 // anything indirectly.
1697 TypeInfo.second = CharUnits::fromQuantity(
1698 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001699
John McCall7f416cc2015-09-08 08:05:57 +00001700 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1701 TypeInfo, CharUnits::fromQuantity(4),
1702 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001703}
1704
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001705bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1706 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1707 assert(Triple.getArch() == llvm::Triple::x86);
1708
1709 switch (Opts.getStructReturnConvention()) {
1710 case CodeGenOptions::SRCK_Default:
1711 break;
1712 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1713 return false;
1714 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1715 return true;
1716 }
1717
Michael Kupersteind749f232015-10-27 07:46:22 +00001718 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001719 return true;
1720
1721 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001722 case llvm::Triple::DragonFly:
1723 case llvm::Triple::FreeBSD:
1724 case llvm::Triple::OpenBSD:
1725 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001726 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001727 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001728 default:
1729 return false;
1730 }
1731}
1732
Eric Christopher162c91c2015-06-05 22:03:00 +00001733void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001734 llvm::GlobalValue *GV,
1735 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001736 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001737 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1738 // Get the LLVM function.
1739 llvm::Function *Fn = cast<llvm::Function>(GV);
1740
1741 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001742 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001743 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001744 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1745 llvm::AttributeSet::get(CGM.getLLVMContext(),
1746 llvm::AttributeSet::FunctionIndex,
1747 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001748 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001749 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1750 llvm::Function *Fn = cast<llvm::Function>(GV);
1751 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1752 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001753 }
1754}
1755
John McCallbeec5a02010-03-06 00:35:14 +00001756bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1757 CodeGen::CodeGenFunction &CGF,
1758 llvm::Value *Address) const {
1759 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001760
Chris Lattnerece04092012-02-07 00:39:47 +00001761 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001762
John McCallbeec5a02010-03-06 00:35:14 +00001763 // 0-7 are the eight integer registers; the order is different
1764 // on Darwin (for EH), but the range is the same.
1765 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001766 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001767
John McCallc8e01702013-04-16 22:48:15 +00001768 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001769 // 12-16 are st(0..4). Not sure why we stop at 4.
1770 // These have size 16, which is sizeof(long double) on
1771 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001772 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001773 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001774
John McCallbeec5a02010-03-06 00:35:14 +00001775 } else {
1776 // 9 is %eflags, which doesn't get a size on Darwin for some
1777 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001778 Builder.CreateAlignedStore(
1779 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1780 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001781
1782 // 11-16 are st(0..5). Not sure why we stop at 5.
1783 // These have size 12, which is sizeof(long double) on
1784 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001785 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001786 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1787 }
John McCallbeec5a02010-03-06 00:35:14 +00001788
1789 return false;
1790}
1791
Chris Lattner0cf24192010-06-28 20:05:43 +00001792//===----------------------------------------------------------------------===//
1793// X86-64 ABI Implementation
1794//===----------------------------------------------------------------------===//
1795
1796
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001797namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001798/// The AVX ABI level for X86 targets.
1799enum class X86AVXABILevel {
1800 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001801 AVX,
1802 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001803};
1804
1805/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1806static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1807 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001808 case X86AVXABILevel::AVX512:
1809 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001810 case X86AVXABILevel::AVX:
1811 return 256;
1812 case X86AVXABILevel::None:
1813 return 128;
1814 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001815 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001816}
1817
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001818/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001819class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001820 enum Class {
1821 Integer = 0,
1822 SSE,
1823 SSEUp,
1824 X87,
1825 X87Up,
1826 ComplexX87,
1827 NoClass,
1828 Memory
1829 };
1830
1831 /// merge - Implement the X86_64 ABI merging algorithm.
1832 ///
1833 /// Merge an accumulating classification \arg Accum with a field
1834 /// classification \arg Field.
1835 ///
1836 /// \param Accum - The accumulating classification. This should
1837 /// always be either NoClass or the result of a previous merge
1838 /// call. In addition, this should never be Memory (the caller
1839 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001840 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001841
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001842 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1843 ///
1844 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1845 /// final MEMORY or SSE classes when necessary.
1846 ///
1847 /// \param AggregateSize - The size of the current aggregate in
1848 /// the classification process.
1849 ///
1850 /// \param Lo - The classification for the parts of the type
1851 /// residing in the low word of the containing object.
1852 ///
1853 /// \param Hi - The classification for the parts of the type
1854 /// residing in the higher words of the containing object.
1855 ///
1856 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1857
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001858 /// classify - Determine the x86_64 register classes in which the
1859 /// given type T should be passed.
1860 ///
1861 /// \param Lo - The classification for the parts of the type
1862 /// residing in the low word of the containing object.
1863 ///
1864 /// \param Hi - The classification for the parts of the type
1865 /// residing in the high word of the containing object.
1866 ///
1867 /// \param OffsetBase - The bit offset of this type in the
1868 /// containing object. Some parameters are classified different
1869 /// depending on whether they straddle an eightbyte boundary.
1870 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001871 /// \param isNamedArg - Whether the argument in question is a "named"
1872 /// argument, as used in AMD64-ABI 3.5.7.
1873 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001874 /// If a word is unused its result will be NoClass; if a type should
1875 /// be passed in Memory then at least the classification of \arg Lo
1876 /// will be Memory.
1877 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001878 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001879 ///
1880 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1881 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001882 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1883 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001885 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001886 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1887 unsigned IROffset, QualType SourceTy,
1888 unsigned SourceOffset) const;
1889 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1890 unsigned IROffset, QualType SourceTy,
1891 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001892
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001893 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001894 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001895 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001896
1897 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001898 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001899 ///
1900 /// \param freeIntRegs - The number of free integer registers remaining
1901 /// available.
1902 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001903
Chris Lattner458b2aa2010-07-29 02:16:43 +00001904 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001905
Bill Wendling5cd41c42010-10-18 03:41:31 +00001906 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001907 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001908 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001909 unsigned &neededSSE,
1910 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001911
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001912 bool IsIllegalVectorType(QualType Ty) const;
1913
John McCalle0fda732011-04-21 01:20:55 +00001914 /// The 0.98 ABI revision clarified a lot of ambiguities,
1915 /// unfortunately in ways that were not always consistent with
1916 /// certain previous compilers. In particular, platforms which
1917 /// required strict binary compatibility with older versions of GCC
1918 /// may need to exempt themselves.
1919 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001920 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001921 }
1922
David Majnemere2ae2282016-03-04 05:26:16 +00001923 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1924 // compilers require us to classify it as INTEGER.
1925 bool classifyIntegerMMXAsSSE() const {
1926 const llvm::Triple &Triple = getTarget().getTriple();
1927 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1928 return false;
1929 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1930 return false;
1931 return true;
1932 }
1933
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001934 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001935 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1936 // 64-bit hardware.
1937 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001938
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001939public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001940 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001941 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001942 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001943 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001944
John McCalla729c622012-02-17 03:33:10 +00001945 bool isPassedUsingAVXType(QualType type) const {
1946 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001947 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001948 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1949 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001950 if (info.isDirect()) {
1951 llvm::Type *ty = info.getCoerceToType();
1952 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1953 return (vectorTy->getBitWidth() > 128);
1954 }
1955 return false;
1956 }
1957
Craig Topper4f12f102014-03-12 06:41:41 +00001958 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001959
John McCall7f416cc2015-09-08 08:05:57 +00001960 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1961 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001962 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1963 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001964
1965 bool has64BitPointers() const {
1966 return Has64BitPointers;
1967 }
John McCall12f23522016-04-04 18:33:08 +00001968
1969 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1970 ArrayRef<llvm::Type*> scalars,
1971 bool asReturnValue) const override {
1972 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
1973 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001974};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001975
Chris Lattner04dc9572010-08-31 16:44:54 +00001976/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001977class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001978public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001979 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1980 : ABIInfo(CGT),
1981 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001982
Craig Topper4f12f102014-03-12 06:41:41 +00001983 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001984
John McCall7f416cc2015-09-08 08:05:57 +00001985 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1986 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001987
1988 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1989 // FIXME: Assumes vectorcall is in use.
1990 return isX86VectorTypeForVectorCall(getContext(), Ty);
1991 }
1992
1993 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1994 uint64_t NumMembers) const override {
1995 // FIXME: Assumes vectorcall is in use.
1996 return isX86VectorCallAggregateSmallEnough(NumMembers);
1997 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001998
1999private:
2000 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2001 bool IsReturnType) const;
2002
2003 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002004};
2005
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002006class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2007public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002008 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002009 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002010
John McCalla729c622012-02-17 03:33:10 +00002011 const X86_64ABIInfo &getABIInfo() const {
2012 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2013 }
2014
Craig Topper4f12f102014-03-12 06:41:41 +00002015 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002016 return 7;
2017 }
2018
2019 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002020 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002021 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002022
John McCall943fae92010-05-27 06:19:26 +00002023 // 0-15 are the 16 integer registers.
2024 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002025 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002026 return false;
2027 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002028
Jay Foad7c57be32011-07-11 09:56:20 +00002029 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002030 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002031 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002032 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2033 }
2034
John McCalla729c622012-02-17 03:33:10 +00002035 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002036 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002037 // The default CC on x86-64 sets %al to the number of SSA
2038 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002039 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002040 // that when AVX types are involved: the ABI explicitly states it is
2041 // undefined, and it doesn't work in practice because of how the ABI
2042 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002043 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002044 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002045 for (CallArgList::const_iterator
2046 it = args.begin(), ie = args.end(); it != ie; ++it) {
2047 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2048 HasAVXType = true;
2049 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002050 }
2051 }
John McCalla729c622012-02-17 03:33:10 +00002052
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002053 if (!HasAVXType)
2054 return true;
2055 }
John McCallcbc038a2011-09-21 08:08:30 +00002056
John McCalla729c622012-02-17 03:33:10 +00002057 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002058 }
2059
Craig Topper4f12f102014-03-12 06:41:41 +00002060 llvm::Constant *
2061 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002062 unsigned Sig;
2063 if (getABIInfo().has64BitPointers())
2064 Sig = (0xeb << 0) | // jmp rel8
2065 (0x0a << 8) | // .+0x0c
2066 ('F' << 16) |
2067 ('T' << 24);
2068 else
2069 Sig = (0xeb << 0) | // jmp rel8
2070 (0x06 << 8) | // .+0x08
2071 ('F' << 16) |
2072 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002073 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2074 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002075
2076 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2077 CodeGen::CodeGenModule &CGM) const override {
2078 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2079 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2080 llvm::Function *Fn = cast<llvm::Function>(GV);
2081 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2082 }
2083 }
2084 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002085};
2086
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002087class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2088public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002089 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2090 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002091
2092 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002093 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002094 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002095 // If the argument contains a space, enclose it in quotes.
2096 if (Lib.find(" ") != StringRef::npos)
2097 Opt += "\"" + Lib.str() + "\"";
2098 else
2099 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002100 }
2101};
2102
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002103static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002104 // If the argument does not end in .lib, automatically add the suffix.
2105 // If the argument contains a space, enclose it in quotes.
2106 // This matches the behavior of MSVC.
2107 bool Quote = (Lib.find(" ") != StringRef::npos);
2108 std::string ArgStr = Quote ? "\"" : "";
2109 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002110 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002111 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002112 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002113 return ArgStr;
2114}
2115
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002116class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2117public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002118 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002119 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2120 unsigned NumRegisterParameters)
2121 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002122 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002123
Eric Christopher162c91c2015-06-05 22:03:00 +00002124 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002125 CodeGen::CodeGenModule &CGM) const override;
2126
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002127 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002128 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002129 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002130 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002131 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002132
2133 void getDetectMismatchOption(llvm::StringRef Name,
2134 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002135 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002136 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002137 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002138};
2139
Hans Wennborg77dc2362015-01-20 19:45:50 +00002140static void addStackProbeSizeTargetAttribute(const Decl *D,
2141 llvm::GlobalValue *GV,
2142 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002143 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002144 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2145 llvm::Function *Fn = cast<llvm::Function>(GV);
2146
Eric Christopher7565e0d2015-05-29 23:09:49 +00002147 Fn->addFnAttr("stack-probe-size",
2148 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002149 }
2150 }
2151}
2152
Eric Christopher162c91c2015-06-05 22:03:00 +00002153void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002154 llvm::GlobalValue *GV,
2155 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002156 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002157
2158 addStackProbeSizeTargetAttribute(D, GV, CGM);
2159}
2160
Chris Lattner04dc9572010-08-31 16:44:54 +00002161class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2162public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002163 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2164 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002165 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002166
Eric Christopher162c91c2015-06-05 22:03:00 +00002167 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002168 CodeGen::CodeGenModule &CGM) const override;
2169
Craig Topper4f12f102014-03-12 06:41:41 +00002170 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002171 return 7;
2172 }
2173
2174 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002175 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002176 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002177
Chris Lattner04dc9572010-08-31 16:44:54 +00002178 // 0-15 are the 16 integer registers.
2179 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002180 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002181 return false;
2182 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002183
2184 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002185 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002186 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002187 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002188 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002189
2190 void getDetectMismatchOption(llvm::StringRef Name,
2191 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002192 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002193 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002194 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002195};
2196
Eric Christopher162c91c2015-06-05 22:03:00 +00002197void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002198 llvm::GlobalValue *GV,
2199 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002200 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002201
Alexey Bataevd51e9932016-01-15 04:06:31 +00002202 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2203 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2204 llvm::Function *Fn = cast<llvm::Function>(GV);
2205 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2206 }
2207 }
2208
Hans Wennborg77dc2362015-01-20 19:45:50 +00002209 addStackProbeSizeTargetAttribute(D, GV, CGM);
2210}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002211}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002212
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002213void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2214 Class &Hi) const {
2215 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2216 //
2217 // (a) If one of the classes is Memory, the whole argument is passed in
2218 // memory.
2219 //
2220 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2221 // memory.
2222 //
2223 // (c) If the size of the aggregate exceeds two eightbytes and the first
2224 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2225 // argument is passed in memory. NOTE: This is necessary to keep the
2226 // ABI working for processors that don't support the __m256 type.
2227 //
2228 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2229 //
2230 // Some of these are enforced by the merging logic. Others can arise
2231 // only with unions; for example:
2232 // union { _Complex double; unsigned; }
2233 //
2234 // Note that clauses (b) and (c) were added in 0.98.
2235 //
2236 if (Hi == Memory)
2237 Lo = Memory;
2238 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2239 Lo = Memory;
2240 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2241 Lo = Memory;
2242 if (Hi == SSEUp && Lo != SSE)
2243 Hi = SSE;
2244}
2245
Chris Lattnerd776fb12010-06-28 21:43:59 +00002246X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002247 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2248 // classified recursively so that always two fields are
2249 // considered. The resulting class is calculated according to
2250 // the classes of the fields in the eightbyte:
2251 //
2252 // (a) If both classes are equal, this is the resulting class.
2253 //
2254 // (b) If one of the classes is NO_CLASS, the resulting class is
2255 // the other class.
2256 //
2257 // (c) If one of the classes is MEMORY, the result is the MEMORY
2258 // class.
2259 //
2260 // (d) If one of the classes is INTEGER, the result is the
2261 // INTEGER.
2262 //
2263 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2264 // MEMORY is used as class.
2265 //
2266 // (f) Otherwise class SSE is used.
2267
2268 // Accum should never be memory (we should have returned) or
2269 // ComplexX87 (because this cannot be passed in a structure).
2270 assert((Accum != Memory && Accum != ComplexX87) &&
2271 "Invalid accumulated classification during merge.");
2272 if (Accum == Field || Field == NoClass)
2273 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002274 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002275 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002276 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002277 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002278 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002279 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002280 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2281 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002282 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002283 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002284}
2285
Chris Lattner5c740f12010-06-30 19:14:05 +00002286void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002287 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002288 // FIXME: This code can be simplified by introducing a simple value class for
2289 // Class pairs with appropriate constructor methods for the various
2290 // situations.
2291
2292 // FIXME: Some of the split computations are wrong; unaligned vectors
2293 // shouldn't be passed in registers for example, so there is no chance they
2294 // can straddle an eightbyte. Verify & simplify.
2295
2296 Lo = Hi = NoClass;
2297
2298 Class &Current = OffsetBase < 64 ? Lo : Hi;
2299 Current = Memory;
2300
John McCall9dd450b2009-09-21 23:43:11 +00002301 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002302 BuiltinType::Kind k = BT->getKind();
2303
2304 if (k == BuiltinType::Void) {
2305 Current = NoClass;
2306 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2307 Lo = Integer;
2308 Hi = Integer;
2309 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2310 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002311 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002312 Current = SSE;
2313 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002314 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2315 if (LDF == &llvm::APFloat::IEEEquad) {
2316 Lo = SSE;
2317 Hi = SSEUp;
2318 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2319 Lo = X87;
2320 Hi = X87Up;
2321 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2322 Current = SSE;
2323 } else
2324 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002325 }
2326 // FIXME: _Decimal32 and _Decimal64 are SSE.
2327 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002328 return;
2329 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002330
Chris Lattnerd776fb12010-06-28 21:43:59 +00002331 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002332 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002333 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002334 return;
2335 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002336
Chris Lattnerd776fb12010-06-28 21:43:59 +00002337 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002339 return;
2340 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002341
Chris Lattnerd776fb12010-06-28 21:43:59 +00002342 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002343 if (Ty->isMemberFunctionPointerType()) {
2344 if (Has64BitPointers) {
2345 // If Has64BitPointers, this is an {i64, i64}, so classify both
2346 // Lo and Hi now.
2347 Lo = Hi = Integer;
2348 } else {
2349 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2350 // straddles an eightbyte boundary, Hi should be classified as well.
2351 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2352 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2353 if (EB_FuncPtr != EB_ThisAdj) {
2354 Lo = Hi = Integer;
2355 } else {
2356 Current = Integer;
2357 }
2358 }
2359 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002360 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002361 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002362 return;
2363 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002364
Chris Lattnerd776fb12010-06-28 21:43:59 +00002365 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002366 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002367 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2368 // gcc passes the following as integer:
2369 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2370 // 2 bytes - <2 x char>, <1 x short>
2371 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002372 Current = Integer;
2373
2374 // If this type crosses an eightbyte boundary, it should be
2375 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002376 uint64_t EB_Lo = (OffsetBase) / 64;
2377 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2378 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002379 Hi = Lo;
2380 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002381 QualType ElementType = VT->getElementType();
2382
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002383 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002384 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002385 return;
2386
David Majnemere2ae2282016-03-04 05:26:16 +00002387 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2388 // pass them as integer. For platforms where clang is the de facto
2389 // platform compiler, we must continue to use integer.
2390 if (!classifyIntegerMMXAsSSE() &&
2391 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2392 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2393 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2394 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002395 Current = Integer;
2396 else
2397 Current = SSE;
2398
2399 // If this type crosses an eightbyte boundary, it should be
2400 // split.
2401 if (OffsetBase && OffsetBase != 64)
2402 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002403 } else if (Size == 128 ||
2404 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002405 // Arguments of 256-bits are split into four eightbyte chunks. The
2406 // least significant one belongs to class SSE and all the others to class
2407 // SSEUP. The original Lo and Hi design considers that types can't be
2408 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2409 // This design isn't correct for 256-bits, but since there're no cases
2410 // where the upper parts would need to be inspected, avoid adding
2411 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002412 //
2413 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2414 // registers if they are "named", i.e. not part of the "..." of a
2415 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002416 //
2417 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2418 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002419 Lo = SSE;
2420 Hi = SSEUp;
2421 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002422 return;
2423 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002424
Chris Lattnerd776fb12010-06-28 21:43:59 +00002425 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002426 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002427
Chris Lattner2b037972010-07-29 02:01:43 +00002428 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002429 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002430 if (Size <= 64)
2431 Current = Integer;
2432 else if (Size <= 128)
2433 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002434 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002435 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002436 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002437 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002438 } else if (ET == getContext().LongDoubleTy) {
2439 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2440 if (LDF == &llvm::APFloat::IEEEquad)
2441 Current = Memory;
2442 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2443 Current = ComplexX87;
2444 else if (LDF == &llvm::APFloat::IEEEdouble)
2445 Lo = Hi = SSE;
2446 else
2447 llvm_unreachable("unexpected long double representation!");
2448 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002449
2450 // If this complex type crosses an eightbyte boundary then it
2451 // should be split.
2452 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002453 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454 if (Hi == NoClass && EB_Real != EB_Imag)
2455 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002456
Chris Lattnerd776fb12010-06-28 21:43:59 +00002457 return;
2458 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002459
Chris Lattner2b037972010-07-29 02:01:43 +00002460 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002461 // Arrays are treated like structures.
2462
Chris Lattner2b037972010-07-29 02:01:43 +00002463 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002464
2465 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002466 // than four eightbytes, ..., it has class MEMORY.
2467 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468 return;
2469
2470 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2471 // fields, it has class MEMORY.
2472 //
2473 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002474 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002475 return;
2476
2477 // Otherwise implement simplified merge. We could be smarter about
2478 // this, but it isn't worth it and would be harder to verify.
2479 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002480 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002481 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002482
2483 // The only case a 256-bit wide vector could be used is when the array
2484 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2485 // to work for sizes wider than 128, early check and fallback to memory.
2486 if (Size > 128 && EltSize != 256)
2487 return;
2488
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002489 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2490 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002491 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002492 Lo = merge(Lo, FieldLo);
2493 Hi = merge(Hi, FieldHi);
2494 if (Lo == Memory || Hi == Memory)
2495 break;
2496 }
2497
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002498 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002499 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002500 return;
2501 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002502
Chris Lattnerd776fb12010-06-28 21:43:59 +00002503 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002504 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002505
2506 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002507 // than four eightbytes, ..., it has class MEMORY.
2508 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 return;
2510
Anders Carlsson20759ad2009-09-16 15:53:40 +00002511 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2512 // copy constructor or a non-trivial destructor, it is passed by invisible
2513 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002514 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002515 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002516
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002517 const RecordDecl *RD = RT->getDecl();
2518
2519 // Assume variable sized types are passed in memory.
2520 if (RD->hasFlexibleArrayMember())
2521 return;
2522
Chris Lattner2b037972010-07-29 02:01:43 +00002523 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002524
2525 // Reset Lo class, this will be recomputed.
2526 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002527
2528 // If this is a C++ record, classify the bases first.
2529 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002530 for (const auto &I : CXXRD->bases()) {
2531 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002532 "Unexpected base class!");
2533 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002534 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002535
2536 // Classify this field.
2537 //
2538 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2539 // single eightbyte, each is classified separately. Each eightbyte gets
2540 // initialized to class NO_CLASS.
2541 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002542 uint64_t Offset =
2543 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002544 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002545 Lo = merge(Lo, FieldLo);
2546 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002547 if (Lo == Memory || Hi == Memory) {
2548 postMerge(Size, Lo, Hi);
2549 return;
2550 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002551 }
2552 }
2553
2554 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002556 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002557 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2559 bool BitField = i->isBitField();
2560
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002561 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2562 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002563 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002564 // The only case a 256-bit wide vector could be used is when the struct
2565 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2566 // to work for sizes wider than 128, early check and fallback to memory.
2567 //
2568 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2569 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002570 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002571 return;
2572 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002573 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002574 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002575 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002576 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002577 return;
2578 }
2579
2580 // Classify this field.
2581 //
2582 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2583 // exceeds a single eightbyte, each is classified
2584 // separately. Each eightbyte gets initialized to class
2585 // NO_CLASS.
2586 Class FieldLo, FieldHi;
2587
2588 // Bit-fields require special handling, they do not force the
2589 // structure to be passed in memory even if unaligned, and
2590 // therefore they can straddle an eightbyte.
2591 if (BitField) {
2592 // Ignore padding bit-fields.
2593 if (i->isUnnamedBitfield())
2594 continue;
2595
2596 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002597 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002598
2599 uint64_t EB_Lo = Offset / 64;
2600 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002601
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002602 if (EB_Lo) {
2603 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2604 FieldLo = NoClass;
2605 FieldHi = Integer;
2606 } else {
2607 FieldLo = Integer;
2608 FieldHi = EB_Hi ? Integer : NoClass;
2609 }
2610 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002611 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002612 Lo = merge(Lo, FieldLo);
2613 Hi = merge(Hi, FieldHi);
2614 if (Lo == Memory || Hi == Memory)
2615 break;
2616 }
2617
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002618 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002619 }
2620}
2621
Chris Lattner22a931e2010-06-29 06:01:59 +00002622ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002623 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2624 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002625 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002626 // Treat an enum type as its underlying type.
2627 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2628 Ty = EnumTy->getDecl()->getIntegerType();
2629
2630 return (Ty->isPromotableIntegerType() ?
2631 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2632 }
2633
John McCall7f416cc2015-09-08 08:05:57 +00002634 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002635}
2636
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002637bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2638 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2639 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002640 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002641 if (Size <= 64 || Size > LargestVector)
2642 return true;
2643 }
2644
2645 return false;
2646}
2647
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002648ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2649 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002650 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2651 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002652 //
2653 // This assumption is optimistic, as there could be free registers available
2654 // when we need to pass this argument in memory, and LLVM could try to pass
2655 // the argument in the free register. This does not seem to happen currently,
2656 // but this code would be much safer if we could mark the argument with
2657 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002658 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002659 // Treat an enum type as its underlying type.
2660 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2661 Ty = EnumTy->getDecl()->getIntegerType();
2662
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002663 return (Ty->isPromotableIntegerType() ?
2664 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002665 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002666
Mark Lacey3825e832013-10-06 01:33:34 +00002667 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002668 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002669
Chris Lattner44c2b902011-05-22 23:21:23 +00002670 // Compute the byval alignment. We specify the alignment of the byval in all
2671 // cases so that the mid-level optimizer knows the alignment of the byval.
2672 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002673
2674 // Attempt to avoid passing indirect results using byval when possible. This
2675 // is important for good codegen.
2676 //
2677 // We do this by coercing the value into a scalar type which the backend can
2678 // handle naturally (i.e., without using byval).
2679 //
2680 // For simplicity, we currently only do this when we have exhausted all of the
2681 // free integer registers. Doing this when there are free integer registers
2682 // would require more care, as we would have to ensure that the coerced value
2683 // did not claim the unused register. That would require either reording the
2684 // arguments to the function (so that any subsequent inreg values came first),
2685 // or only doing this optimization when there were no following arguments that
2686 // might be inreg.
2687 //
2688 // We currently expect it to be rare (particularly in well written code) for
2689 // arguments to be passed on the stack when there are still free integer
2690 // registers available (this would typically imply large structs being passed
2691 // by value), so this seems like a fair tradeoff for now.
2692 //
2693 // We can revisit this if the backend grows support for 'onstack' parameter
2694 // attributes. See PR12193.
2695 if (freeIntRegs == 0) {
2696 uint64_t Size = getContext().getTypeSize(Ty);
2697
2698 // If this type fits in an eightbyte, coerce it into the matching integral
2699 // type, which will end up on the stack (with alignment 8).
2700 if (Align == 8 && Size <= 64)
2701 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2702 Size));
2703 }
2704
John McCall7f416cc2015-09-08 08:05:57 +00002705 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706}
2707
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002708/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2709/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002710llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002711 // Wrapper structs/arrays that only contain vectors are passed just like
2712 // vectors; strip them off if present.
2713 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2714 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002715
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002716 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002717 if (isa<llvm::VectorType>(IRType) ||
2718 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002719 return IRType;
2720
2721 // We couldn't find the preferred IR vector type for 'Ty'.
2722 uint64_t Size = getContext().getTypeSize(Ty);
2723 assert((Size == 128 || Size == 256) && "Invalid type found!");
2724
2725 // Return a LLVM IR vector type based on the size of 'Ty'.
2726 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2727 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002728}
2729
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002730/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2731/// is known to either be off the end of the specified type or being in
2732/// alignment padding. The user type specified is known to be at most 128 bits
2733/// in size, and have passed through X86_64ABIInfo::classify with a successful
2734/// classification that put one of the two halves in the INTEGER class.
2735///
2736/// It is conservatively correct to return false.
2737static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2738 unsigned EndBit, ASTContext &Context) {
2739 // If the bytes being queried are off the end of the type, there is no user
2740 // data hiding here. This handles analysis of builtins, vectors and other
2741 // types that don't contain interesting padding.
2742 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2743 if (TySize <= StartBit)
2744 return true;
2745
Chris Lattner98076a22010-07-29 07:43:55 +00002746 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2747 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2748 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2749
2750 // Check each element to see if the element overlaps with the queried range.
2751 for (unsigned i = 0; i != NumElts; ++i) {
2752 // If the element is after the span we care about, then we're done..
2753 unsigned EltOffset = i*EltSize;
2754 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002755
Chris Lattner98076a22010-07-29 07:43:55 +00002756 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2757 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2758 EndBit-EltOffset, Context))
2759 return false;
2760 }
2761 // If it overlaps no elements, then it is safe to process as padding.
2762 return true;
2763 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002764
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002765 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2766 const RecordDecl *RD = RT->getDecl();
2767 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002768
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002769 // If this is a C++ record, check the bases first.
2770 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002771 for (const auto &I : CXXRD->bases()) {
2772 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002773 "Unexpected base class!");
2774 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002775 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002776
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002777 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002778 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002779 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002780
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002781 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002782 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002783 EndBit-BaseOffset, Context))
2784 return false;
2785 }
2786 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002787
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002788 // Verify that no field has data that overlaps the region of interest. Yes
2789 // this could be sped up a lot by being smarter about queried fields,
2790 // however we're only looking at structs up to 16 bytes, so we don't care
2791 // much.
2792 unsigned idx = 0;
2793 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2794 i != e; ++i, ++idx) {
2795 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002796
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002797 // If we found a field after the region we care about, then we're done.
2798 if (FieldOffset >= EndBit) break;
2799
2800 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2801 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2802 Context))
2803 return false;
2804 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002805
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002806 // If nothing in this record overlapped the area of interest, then we're
2807 // clean.
2808 return true;
2809 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002810
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002811 return false;
2812}
2813
Chris Lattnere556a712010-07-29 18:39:32 +00002814/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2815/// float member at the specified offset. For example, {int,{float}} has a
2816/// float at offset 4. It is conservatively correct for this routine to return
2817/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002818static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002819 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002820 // Base case if we find a float.
2821 if (IROffset == 0 && IRType->isFloatTy())
2822 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002823
Chris Lattnere556a712010-07-29 18:39:32 +00002824 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002825 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002826 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2827 unsigned Elt = SL->getElementContainingOffset(IROffset);
2828 IROffset -= SL->getElementOffset(Elt);
2829 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2830 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002831
Chris Lattnere556a712010-07-29 18:39:32 +00002832 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002833 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2834 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002835 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2836 IROffset -= IROffset/EltSize*EltSize;
2837 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2838 }
2839
2840 return false;
2841}
2842
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002843
2844/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2845/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002846llvm::Type *X86_64ABIInfo::
2847GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002848 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002849 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002850 // pass as float if the last 4 bytes is just padding. This happens for
2851 // structs that contain 3 floats.
2852 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2853 SourceOffset*8+64, getContext()))
2854 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002855
Chris Lattnere556a712010-07-29 18:39:32 +00002856 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2857 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2858 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002859 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2860 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002861 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002862
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002863 return llvm::Type::getDoubleTy(getVMContext());
2864}
2865
2866
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002867/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2868/// an 8-byte GPR. This means that we either have a scalar or we are talking
2869/// about the high or low part of an up-to-16-byte struct. This routine picks
2870/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002871/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2872/// etc).
2873///
2874/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2875/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2876/// the 8-byte value references. PrefType may be null.
2877///
Alp Toker9907f082014-07-09 14:06:35 +00002878/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002879/// an offset into this that we're processing (which is always either 0 or 8).
2880///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002881llvm::Type *X86_64ABIInfo::
2882GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002883 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002884 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2885 // returning an 8-byte unit starting with it. See if we can safely use it.
2886 if (IROffset == 0) {
2887 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002888 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2889 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002890 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002891
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002892 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2893 // goodness in the source type is just tail padding. This is allowed to
2894 // kick in for struct {double,int} on the int, but not on
2895 // struct{double,int,int} because we wouldn't return the second int. We
2896 // have to do this analysis on the source type because we can't depend on
2897 // unions being lowered a specific way etc.
2898 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002899 IRType->isIntegerTy(32) ||
2900 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2901 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2902 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002903
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002904 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2905 SourceOffset*8+64, getContext()))
2906 return IRType;
2907 }
2908 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002909
Chris Lattner2192fe52011-07-18 04:24:23 +00002910 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002911 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002912 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002913 if (IROffset < SL->getSizeInBytes()) {
2914 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2915 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002916
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002917 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2918 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002919 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002920 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002921
Chris Lattner2192fe52011-07-18 04:24:23 +00002922 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002923 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002924 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002925 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002926 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2927 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002928 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002929
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002930 // Okay, we don't have any better idea of what to pass, so we pass this in an
2931 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002932 unsigned TySizeInBytes =
2933 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002934
Chris Lattner3f763422010-07-29 17:34:39 +00002935 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002936
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002937 // It is always safe to classify this as an integer type up to i64 that
2938 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002939 return llvm::IntegerType::get(getVMContext(),
2940 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002941}
2942
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002943
2944/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2945/// be used as elements of a two register pair to pass or return, return a
2946/// first class aggregate to represent them. For example, if the low part of
2947/// a by-value argument should be passed as i32* and the high part as float,
2948/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002949static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002950GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002951 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002952 // In order to correctly satisfy the ABI, we need to the high part to start
2953 // at offset 8. If the high and low parts we inferred are both 4-byte types
2954 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2955 // the second element at offset 8. Check for this:
2956 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2957 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002958 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002959 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002960
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002961 // To handle this, we have to increase the size of the low part so that the
2962 // second element will start at an 8 byte offset. We can't increase the size
2963 // of the second element because it might make us access off the end of the
2964 // struct.
2965 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002966 // There are usually two sorts of types the ABI generation code can produce
2967 // for the low part of a pair that aren't 8 bytes in size: float or
2968 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2969 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002970 // Promote these to a larger type.
2971 if (Lo->isFloatTy())
2972 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2973 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002974 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2975 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002976 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2977 }
2978 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002979
Reid Kleckneree7cf842014-12-01 22:02:27 +00002980 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002981
2982
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002983 // Verify that the second element is at an 8-byte offset.
2984 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2985 "Invalid x86-64 argument pair!");
2986 return Result;
2987}
2988
Chris Lattner31faff52010-07-28 23:06:14 +00002989ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002990classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002991 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2992 // classification algorithm.
2993 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002994 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002995
2996 // Check some invariants.
2997 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002998 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2999
Craig Topper8a13c412014-05-21 05:09:00 +00003000 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003001 switch (Lo) {
3002 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003003 if (Hi == NoClass)
3004 return ABIArgInfo::getIgnore();
3005 // If the low part is just padding, it takes no register, leave ResType
3006 // null.
3007 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3008 "Unknown missing lo part");
3009 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003010
3011 case SSEUp:
3012 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003013 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003014
3015 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3016 // hidden argument.
3017 case Memory:
3018 return getIndirectReturnResult(RetTy);
3019
3020 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3021 // available register of the sequence %rax, %rdx is used.
3022 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003023 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003024
Chris Lattner1f3a0632010-07-29 21:42:50 +00003025 // If we have a sign or zero extended integer, make sure to return Extend
3026 // so that the parameter gets the right LLVM IR attributes.
3027 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3028 // Treat an enum type as its underlying type.
3029 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3030 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003031
Chris Lattner1f3a0632010-07-29 21:42:50 +00003032 if (RetTy->isIntegralOrEnumerationType() &&
3033 RetTy->isPromotableIntegerType())
3034 return ABIArgInfo::getExtend();
3035 }
Chris Lattner31faff52010-07-28 23:06:14 +00003036 break;
3037
3038 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3039 // available SSE register of the sequence %xmm0, %xmm1 is used.
3040 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003041 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003042 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003043
3044 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3045 // returned on the X87 stack in %st0 as 80-bit x87 number.
3046 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003047 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003048 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003049
3050 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3051 // part of the value is returned in %st0 and the imaginary part in
3052 // %st1.
3053 case ComplexX87:
3054 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003055 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003056 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003057 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003058 break;
3059 }
3060
Craig Topper8a13c412014-05-21 05:09:00 +00003061 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003062 switch (Hi) {
3063 // Memory was handled previously and X87 should
3064 // never occur as a hi class.
3065 case Memory:
3066 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003067 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003068
3069 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003070 case NoClass:
3071 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003072
Chris Lattner52b3c132010-09-01 00:20:33 +00003073 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003074 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003075 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3076 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003077 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003078 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003079 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003080 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3081 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003082 break;
3083
3084 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003085 // is passed in the next available eightbyte chunk if the last used
3086 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003087 //
Chris Lattner57540c52011-04-15 05:22:18 +00003088 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003089 case SSEUp:
3090 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003091 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003092 break;
3093
3094 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3095 // returned together with the previous X87 value in %st0.
3096 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003097 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003098 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003099 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003100 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003101 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003102 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003103 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3104 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003105 }
Chris Lattner31faff52010-07-28 23:06:14 +00003106 break;
3107 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003108
Chris Lattner52b3c132010-09-01 00:20:33 +00003109 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003110 // known to pass in the high eightbyte of the result. We do this by forming a
3111 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003112 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003113 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003114
Chris Lattner1f3a0632010-07-29 21:42:50 +00003115 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003116}
3117
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003118ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003119 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3120 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003121 const
3122{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003123 Ty = useFirstFieldIfTransparentUnion(Ty);
3124
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003125 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003126 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003127
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003128 // Check some invariants.
3129 // FIXME: Enforce these by construction.
3130 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3132
3133 neededInt = 0;
3134 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003135 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003136 switch (Lo) {
3137 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003138 if (Hi == NoClass)
3139 return ABIArgInfo::getIgnore();
3140 // If the low part is just padding, it takes no register, leave ResType
3141 // null.
3142 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3143 "Unknown missing lo part");
3144 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003145
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003146 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3147 // on the stack.
3148 case Memory:
3149
3150 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3151 // COMPLEX_X87, it is passed in memory.
3152 case X87:
3153 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003154 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003155 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003156 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003157
3158 case SSEUp:
3159 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003160 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003161
3162 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3163 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3164 // and %r9 is used.
3165 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003166 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003167
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003168 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003169 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003170
3171 // If we have a sign or zero extended integer, make sure to return Extend
3172 // so that the parameter gets the right LLVM IR attributes.
3173 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3174 // Treat an enum type as its underlying type.
3175 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3176 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003177
Chris Lattner1f3a0632010-07-29 21:42:50 +00003178 if (Ty->isIntegralOrEnumerationType() &&
3179 Ty->isPromotableIntegerType())
3180 return ABIArgInfo::getExtend();
3181 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003182
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003183 break;
3184
3185 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3186 // available SSE register is used, the registers are taken in the
3187 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003188 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003189 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003190 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003191 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003192 break;
3193 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003194 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003195
Craig Topper8a13c412014-05-21 05:09:00 +00003196 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003197 switch (Hi) {
3198 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003199 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003200 // which is passed in memory.
3201 case Memory:
3202 case X87:
3203 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003204 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003205
3206 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003207
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003208 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003209 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003210 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003211 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003212
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003213 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3214 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003215 break;
3216
3217 // X87Up generally doesn't occur here (long double is passed in
3218 // memory), except in situations involving unions.
3219 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003220 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003221 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003222
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003223 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3224 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003225
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003226 ++neededSSE;
3227 break;
3228
3229 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3230 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003231 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003232 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003233 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003234 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003235 break;
3236 }
3237
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003238 // If a high part was specified, merge it together with the low part. It is
3239 // known to pass in the high eightbyte of the result. We do this by forming a
3240 // first class struct aggregate with the high and low part: {low, high}
3241 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003242 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003243
Chris Lattner1f3a0632010-07-29 21:42:50 +00003244 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003245}
3246
Chris Lattner22326a12010-07-29 02:31:05 +00003247void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003248
Reid Kleckner40ca9132014-05-13 22:05:45 +00003249 if (!getCXXABI().classifyReturnType(FI))
3250 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003251
3252 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003253 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003254
3255 // If the return value is indirect, then the hidden argument is consuming one
3256 // integer register.
3257 if (FI.getReturnInfo().isIndirect())
3258 --freeIntRegs;
3259
Peter Collingbournef7706832014-12-12 23:41:25 +00003260 // The chain argument effectively gives us another free register.
3261 if (FI.isChainCall())
3262 ++freeIntRegs;
3263
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003264 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003265 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3266 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003267 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003268 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003269 it != ie; ++it, ++ArgNo) {
3270 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003271
Bill Wendling9987c0e2010-10-18 23:51:38 +00003272 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003273 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003274 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003275
3276 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3277 // eightbyte of an argument, the whole argument is passed on the
3278 // stack. If registers have already been assigned for some
3279 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003280 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003281 freeIntRegs -= neededInt;
3282 freeSSERegs -= neededSSE;
3283 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003284 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003285 }
3286 }
3287}
3288
John McCall7f416cc2015-09-08 08:05:57 +00003289static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3290 Address VAListAddr, QualType Ty) {
3291 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3292 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003293 llvm::Value *overflow_arg_area =
3294 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3295
3296 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3297 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003298 // It isn't stated explicitly in the standard, but in practice we use
3299 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003300 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3301 if (Align > CharUnits::fromQuantity(8)) {
3302 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3303 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003304 }
3305
3306 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003307 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003308 llvm::Value *Res =
3309 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003310 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003311
3312 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3313 // l->overflow_arg_area + sizeof(type).
3314 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3315 // an 8 byte boundary.
3316
3317 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003318 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003319 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003320 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3321 "overflow_arg_area.next");
3322 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3323
3324 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003325 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003326}
3327
John McCall7f416cc2015-09-08 08:05:57 +00003328Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3329 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003330 // Assume that va_list type is correct; should be pointer to LLVM type:
3331 // struct {
3332 // i32 gp_offset;
3333 // i32 fp_offset;
3334 // i8* overflow_arg_area;
3335 // i8* reg_save_area;
3336 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003337 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003338
John McCall7f416cc2015-09-08 08:05:57 +00003339 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003340 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003341 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003342
3343 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3344 // in the registers. If not go to step 7.
3345 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003346 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003347
3348 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3349 // general purpose registers needed to pass type and num_fp to hold
3350 // the number of floating point registers needed.
3351
3352 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3353 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3354 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3355 //
3356 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3357 // register save space).
3358
Craig Topper8a13c412014-05-21 05:09:00 +00003359 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003360 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3361 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003362 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003363 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003364 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3365 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003366 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003367 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3368 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003369 }
3370
3371 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003372 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003373 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3374 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003375 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3376 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003377 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3378 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003379 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3380 }
3381
3382 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3383 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3384 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3385 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3386
3387 // Emit code to load the value if it was passed in registers.
3388
3389 CGF.EmitBlock(InRegBlock);
3390
3391 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3392 // an offset of l->gp_offset and/or l->fp_offset. This may require
3393 // copying to a temporary location in case the parameter is passed
3394 // in different register classes or requires an alignment greater
3395 // than 8 for general purpose registers and 16 for XMM registers.
3396 //
3397 // FIXME: This really results in shameful code when we end up needing to
3398 // collect arguments from different places; often what should result in a
3399 // simple assembling of a structure from scattered addresses has many more
3400 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003401 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003402 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3403 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3404 "reg_save_area");
3405
3406 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003407 if (neededInt && neededSSE) {
3408 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003409 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003410 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003411 Address Tmp = CGF.CreateMemTemp(Ty);
3412 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003413 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003414 llvm::Type *TyLo = ST->getElementType(0);
3415 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003416 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003417 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003418 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3419 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003420 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3421 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003422 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3423 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003424
John McCall7f416cc2015-09-08 08:05:57 +00003425 // Copy the first element.
3426 llvm::Value *V =
3427 CGF.Builder.CreateDefaultAlignedLoad(
3428 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3429 CGF.Builder.CreateStore(V,
3430 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3431
3432 // Copy the second element.
3433 V = CGF.Builder.CreateDefaultAlignedLoad(
3434 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3435 CharUnits Offset = CharUnits::fromQuantity(
3436 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3437 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3438
3439 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003440 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003441 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3442 CharUnits::fromQuantity(8));
3443 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003444
3445 // Copy to a temporary if necessary to ensure the appropriate alignment.
3446 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003447 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003448 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003449 CharUnits TyAlign = SizeAlign.second;
3450
3451 // Copy into a temporary if the type is more aligned than the
3452 // register save area.
3453 if (TyAlign.getQuantity() > 8) {
3454 Address Tmp = CGF.CreateMemTemp(Ty);
3455 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003456 RegAddr = Tmp;
3457 }
John McCall7f416cc2015-09-08 08:05:57 +00003458
Chris Lattner0cf24192010-06-28 20:05:43 +00003459 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003460 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3461 CharUnits::fromQuantity(16));
3462 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003463 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003464 assert(neededSSE == 2 && "Invalid number of needed registers!");
3465 // SSE registers are spaced 16 bytes apart in the register save
3466 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003467 // The ABI isn't explicit about this, but it seems reasonable
3468 // to assume that the slots are 16-byte aligned, since the stack is
3469 // naturally 16-byte aligned and the prologue is expected to store
3470 // all the SSE registers to the RSA.
3471 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3472 CharUnits::fromQuantity(16));
3473 Address RegAddrHi =
3474 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3475 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003476 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003477 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003478 llvm::Value *V;
3479 Address Tmp = CGF.CreateMemTemp(Ty);
3480 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3481 V = CGF.Builder.CreateLoad(
3482 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3483 CGF.Builder.CreateStore(V,
3484 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3485 V = CGF.Builder.CreateLoad(
3486 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3487 CGF.Builder.CreateStore(V,
3488 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3489
3490 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003491 }
3492
3493 // AMD64-ABI 3.5.7p5: Step 5. Set:
3494 // l->gp_offset = l->gp_offset + num_gp * 8
3495 // l->fp_offset = l->fp_offset + num_fp * 16.
3496 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003497 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003498 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3499 gp_offset_p);
3500 }
3501 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003502 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003503 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3504 fp_offset_p);
3505 }
3506 CGF.EmitBranch(ContBlock);
3507
3508 // Emit code to load the value if it was passed in memory.
3509
3510 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003511 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003512
3513 // Return the appropriate result.
3514
3515 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003516 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3517 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003518 return ResAddr;
3519}
3520
Charles Davisc7d5c942015-09-17 20:55:33 +00003521Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3522 QualType Ty) const {
3523 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3524 CGF.getContext().getTypeInfoInChars(Ty),
3525 CharUnits::fromQuantity(8),
3526 /*allowHigherAlign*/ false);
3527}
3528
Reid Kleckner80944df2014-10-31 22:00:51 +00003529ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3530 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003531
3532 if (Ty->isVoidType())
3533 return ABIArgInfo::getIgnore();
3534
3535 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3536 Ty = EnumTy->getDecl()->getIntegerType();
3537
Reid Kleckner80944df2014-10-31 22:00:51 +00003538 TypeInfo Info = getContext().getTypeInfo(Ty);
3539 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003540 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003541
Reid Kleckner9005f412014-05-02 00:51:20 +00003542 const RecordType *RT = Ty->getAs<RecordType>();
3543 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003544 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003545 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003546 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003547 }
3548
3549 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003550 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003551
Reid Kleckner9005f412014-05-02 00:51:20 +00003552 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003553
Reid Kleckner80944df2014-10-31 22:00:51 +00003554 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3555 // other targets.
3556 const Type *Base = nullptr;
3557 uint64_t NumElts = 0;
3558 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3559 if (FreeSSERegs >= NumElts) {
3560 FreeSSERegs -= NumElts;
3561 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3562 return ABIArgInfo::getDirect();
3563 return ABIArgInfo::getExpand();
3564 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003565 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003566 }
3567
3568
Reid Klecknerec87fec2014-05-02 01:17:12 +00003569 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003570 // If the member pointer is represented by an LLVM int or ptr, pass it
3571 // directly.
3572 llvm::Type *LLTy = CGT.ConvertType(Ty);
3573 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3574 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003575 }
3576
Michael Kuperstein4f818702015-02-24 09:35:58 +00003577 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003578 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3579 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003580 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003581 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003582
Reid Kleckner9005f412014-05-02 00:51:20 +00003583 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003584 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003585 }
3586
Julien Lerouge10dcff82014-08-27 00:36:55 +00003587 // Bool type is always extended to the ABI, other builtin types are not
3588 // extended.
3589 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3590 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003591 return ABIArgInfo::getExtend();
3592
Reid Kleckner11a17192015-10-28 22:29:52 +00003593 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3594 // passes them indirectly through memory.
3595 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3596 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3597 if (LDF == &llvm::APFloat::x87DoubleExtended)
3598 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3599 }
3600
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003601 return ABIArgInfo::getDirect();
3602}
3603
3604void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003605 bool IsVectorCall =
3606 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003607
Reid Kleckner80944df2014-10-31 22:00:51 +00003608 // We can use up to 4 SSE return registers with vectorcall.
3609 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3610 if (!getCXXABI().classifyReturnType(FI))
3611 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3612
3613 // We can use up to 6 SSE register parameters with vectorcall.
3614 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003615 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003616 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003617}
3618
John McCall7f416cc2015-09-08 08:05:57 +00003619Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3620 QualType Ty) const {
3621 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3622 CGF.getContext().getTypeInfoInChars(Ty),
3623 CharUnits::fromQuantity(8),
3624 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003625}
Chris Lattner0cf24192010-06-28 20:05:43 +00003626
John McCallea8d8bb2010-03-11 00:10:12 +00003627// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003628namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003629/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3630class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003631bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003632public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003633 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3634 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003635
John McCall7f416cc2015-09-08 08:05:57 +00003636 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3637 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003638};
3639
3640class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3641public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003642 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3643 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003644
Craig Topper4f12f102014-03-12 06:41:41 +00003645 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003646 // This is recovered from gcc output.
3647 return 1; // r1 is the dedicated stack pointer
3648 }
3649
3650 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003651 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003652};
3653
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003654}
John McCallea8d8bb2010-03-11 00:10:12 +00003655
James Y Knight29b5f082016-02-24 02:59:33 +00003656// TODO: this implementation is now likely redundant with
3657// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003658Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3659 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003660 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003661 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3662 // TODO: Implement this. For now ignore.
3663 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003664 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003665 }
3666
John McCall7f416cc2015-09-08 08:05:57 +00003667 // struct __va_list_tag {
3668 // unsigned char gpr;
3669 // unsigned char fpr;
3670 // unsigned short reserved;
3671 // void *overflow_arg_area;
3672 // void *reg_save_area;
3673 // };
3674
Roman Divacky8a12d842014-11-03 18:32:54 +00003675 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003676 bool isInt =
3677 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003678 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003679
3680 // All aggregates are passed indirectly? That doesn't seem consistent
3681 // with the argument-lowering code.
3682 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003683
3684 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003685
3686 // The calling convention either uses 1-2 GPRs or 1 FPR.
3687 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003688 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003689 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3690 } else {
3691 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003692 }
John McCall7f416cc2015-09-08 08:05:57 +00003693
3694 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3695
3696 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003697 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003698 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3699 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3700 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003701
Eric Christopher7565e0d2015-05-29 23:09:49 +00003702 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003703 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003704
3705 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3706 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3707 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3708
3709 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3710
John McCall7f416cc2015-09-08 08:05:57 +00003711 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3712 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003713
John McCall7f416cc2015-09-08 08:05:57 +00003714 // Case 1: consume registers.
3715 Address RegAddr = Address::invalid();
3716 {
3717 CGF.EmitBlock(UsingRegs);
3718
3719 Address RegSaveAreaPtr =
3720 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3721 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3722 CharUnits::fromQuantity(8));
3723 assert(RegAddr.getElementType() == CGF.Int8Ty);
3724
3725 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003726 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003727 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3728 CharUnits::fromQuantity(32));
3729 }
3730
3731 // Get the address of the saved value by scaling the number of
3732 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003733 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003734 llvm::Value *RegOffset =
3735 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3736 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3737 RegAddr.getPointer(), RegOffset),
3738 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3739 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3740
3741 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003742 NumRegs =
3743 Builder.CreateAdd(NumRegs,
3744 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003745 Builder.CreateStore(NumRegs, NumRegsAddr);
3746
3747 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003748 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003749
John McCall7f416cc2015-09-08 08:05:57 +00003750 // Case 2: consume space in the overflow area.
3751 Address MemAddr = Address::invalid();
3752 {
3753 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003754
Roman Divacky039b9702016-02-20 08:31:24 +00003755 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3756
John McCall7f416cc2015-09-08 08:05:57 +00003757 // Everything in the overflow area is rounded up to a size of at least 4.
3758 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3759
3760 CharUnits Size;
3761 if (!isIndirect) {
3762 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003763 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003764 } else {
3765 Size = CGF.getPointerSize();
3766 }
3767
3768 Address OverflowAreaAddr =
3769 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003770 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003771 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003772 // Round up address of argument to alignment
3773 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3774 if (Align > OverflowAreaAlign) {
3775 llvm::Value *Ptr = OverflowArea.getPointer();
3776 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3777 Align);
3778 }
3779
John McCall7f416cc2015-09-08 08:05:57 +00003780 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3781
3782 // Increase the overflow area.
3783 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3784 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3785 CGF.EmitBranch(Cont);
3786 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003787
3788 CGF.EmitBlock(Cont);
3789
John McCall7f416cc2015-09-08 08:05:57 +00003790 // Merge the cases with a phi.
3791 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3792 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003793
John McCall7f416cc2015-09-08 08:05:57 +00003794 // Load the pointer if the argument was passed indirectly.
3795 if (isIndirect) {
3796 Result = Address(Builder.CreateLoad(Result, "aggr"),
3797 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003798 }
3799
3800 return Result;
3801}
3802
John McCallea8d8bb2010-03-11 00:10:12 +00003803bool
3804PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3805 llvm::Value *Address) const {
3806 // This is calculated from the LLVM and GCC tables and verified
3807 // against gcc output. AFAIK all ABIs use the same encoding.
3808
3809 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003810
Chris Lattnerece04092012-02-07 00:39:47 +00003811 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003812 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3813 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3814 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3815
3816 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003817 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003818
3819 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003820 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003821
3822 // 64-76 are various 4-byte special-purpose registers:
3823 // 64: mq
3824 // 65: lr
3825 // 66: ctr
3826 // 67: ap
3827 // 68-75 cr0-7
3828 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003829 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003830
3831 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003832 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003833
3834 // 109: vrsave
3835 // 110: vscr
3836 // 111: spe_acc
3837 // 112: spefscr
3838 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003839 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003840
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003841 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003842}
3843
Roman Divackyd966e722012-05-09 18:22:46 +00003844// PowerPC-64
3845
3846namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003847/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003848class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003849public:
3850 enum ABIKind {
3851 ELFv1 = 0,
3852 ELFv2
3853 };
3854
3855private:
3856 static const unsigned GPRBits = 64;
3857 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003858 bool HasQPX;
3859
3860 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3861 // will be passed in a QPX register.
3862 bool IsQPXVectorTy(const Type *Ty) const {
3863 if (!HasQPX)
3864 return false;
3865
3866 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3867 unsigned NumElements = VT->getNumElements();
3868 if (NumElements == 1)
3869 return false;
3870
3871 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3872 if (getContext().getTypeSize(Ty) <= 256)
3873 return true;
3874 } else if (VT->getElementType()->
3875 isSpecificBuiltinType(BuiltinType::Float)) {
3876 if (getContext().getTypeSize(Ty) <= 128)
3877 return true;
3878 }
3879 }
3880
3881 return false;
3882 }
3883
3884 bool IsQPXVectorTy(QualType Ty) const {
3885 return IsQPXVectorTy(Ty.getTypePtr());
3886 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003887
3888public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003889 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
James Y Knight29b5f082016-02-24 02:59:33 +00003890 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003891
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003892 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003893 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003894
3895 ABIArgInfo classifyReturnType(QualType RetTy) const;
3896 ABIArgInfo classifyArgumentType(QualType Ty) const;
3897
Reid Klecknere9f6a712014-10-31 17:10:41 +00003898 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3899 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3900 uint64_t Members) const override;
3901
Bill Schmidt84d37792012-10-12 19:26:17 +00003902 // TODO: We can add more logic to computeInfo to improve performance.
3903 // Example: For aggregate arguments that fit in a register, we could
3904 // use getDirectInReg (as is done below for structs containing a single
3905 // floating-point value) to avoid pushing them to memory on function
3906 // entry. This would require changing the logic in PPCISelLowering
3907 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003908 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003909 if (!getCXXABI().classifyReturnType(FI))
3910 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003911 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003912 // We rely on the default argument classification for the most part.
3913 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003914 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003915 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003916 if (T) {
3917 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003918 if (IsQPXVectorTy(T) ||
3919 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003920 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003921 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003922 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003923 continue;
3924 }
3925 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003926 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003927 }
3928 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003929
John McCall7f416cc2015-09-08 08:05:57 +00003930 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3931 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003932};
3933
3934class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003935
Bill Schmidt25cb3492012-10-03 19:18:57 +00003936public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003937 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003938 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003939 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003940
Craig Topper4f12f102014-03-12 06:41:41 +00003941 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003942 // This is recovered from gcc output.
3943 return 1; // r1 is the dedicated stack pointer
3944 }
3945
3946 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003947 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003948};
3949
Roman Divackyd966e722012-05-09 18:22:46 +00003950class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3951public:
3952 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3953
Craig Topper4f12f102014-03-12 06:41:41 +00003954 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003955 // This is recovered from gcc output.
3956 return 1; // r1 is the dedicated stack pointer
3957 }
3958
3959 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003960 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003961};
3962
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003963}
Roman Divackyd966e722012-05-09 18:22:46 +00003964
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003965// Return true if the ABI requires Ty to be passed sign- or zero-
3966// extended to 64 bits.
3967bool
3968PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3969 // Treat an enum type as its underlying type.
3970 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3971 Ty = EnumTy->getDecl()->getIntegerType();
3972
3973 // Promotable integer types are required to be promoted by the ABI.
3974 if (Ty->isPromotableIntegerType())
3975 return true;
3976
3977 // In addition to the usual promotable integer types, we also need to
3978 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3979 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3980 switch (BT->getKind()) {
3981 case BuiltinType::Int:
3982 case BuiltinType::UInt:
3983 return true;
3984 default:
3985 break;
3986 }
3987
3988 return false;
3989}
3990
John McCall7f416cc2015-09-08 08:05:57 +00003991/// isAlignedParamType - Determine whether a type requires 16-byte or
3992/// higher alignment in the parameter area. Always returns at least 8.
3993CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003994 // Complex types are passed just like their elements.
3995 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3996 Ty = CTy->getElementType();
3997
3998 // Only vector types of size 16 bytes need alignment (larger types are
3999 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004000 if (IsQPXVectorTy(Ty)) {
4001 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004002 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004003
John McCall7f416cc2015-09-08 08:05:57 +00004004 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004005 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004006 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004007 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004008
4009 // For single-element float/vector structs, we consider the whole type
4010 // to have the same alignment requirements as its single element.
4011 const Type *AlignAsType = nullptr;
4012 const Type *EltType = isSingleElementStruct(Ty, getContext());
4013 if (EltType) {
4014 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004015 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004016 getContext().getTypeSize(EltType) == 128) ||
4017 (BT && BT->isFloatingPoint()))
4018 AlignAsType = EltType;
4019 }
4020
Ulrich Weigandb7122372014-07-21 00:48:09 +00004021 // Likewise for ELFv2 homogeneous aggregates.
4022 const Type *Base = nullptr;
4023 uint64_t Members = 0;
4024 if (!AlignAsType && Kind == ELFv2 &&
4025 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4026 AlignAsType = Base;
4027
Ulrich Weigand581badc2014-07-10 17:20:07 +00004028 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004029 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4030 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004031 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004032
John McCall7f416cc2015-09-08 08:05:57 +00004033 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004034 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004035 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004036 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004037
4038 // Otherwise, we only need alignment for any aggregate type that
4039 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004040 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4041 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004042 return CharUnits::fromQuantity(32);
4043 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004044 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004045
John McCall7f416cc2015-09-08 08:05:57 +00004046 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004047}
4048
Ulrich Weigandb7122372014-07-21 00:48:09 +00004049/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4050/// aggregate. Base is set to the base element type, and Members is set
4051/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004052bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4053 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004054 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4055 uint64_t NElements = AT->getSize().getZExtValue();
4056 if (NElements == 0)
4057 return false;
4058 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4059 return false;
4060 Members *= NElements;
4061 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4062 const RecordDecl *RD = RT->getDecl();
4063 if (RD->hasFlexibleArrayMember())
4064 return false;
4065
4066 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004067
4068 // If this is a C++ record, check the bases first.
4069 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4070 for (const auto &I : CXXRD->bases()) {
4071 // Ignore empty records.
4072 if (isEmptyRecord(getContext(), I.getType(), true))
4073 continue;
4074
4075 uint64_t FldMembers;
4076 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4077 return false;
4078
4079 Members += FldMembers;
4080 }
4081 }
4082
Ulrich Weigandb7122372014-07-21 00:48:09 +00004083 for (const auto *FD : RD->fields()) {
4084 // Ignore (non-zero arrays of) empty records.
4085 QualType FT = FD->getType();
4086 while (const ConstantArrayType *AT =
4087 getContext().getAsConstantArrayType(FT)) {
4088 if (AT->getSize().getZExtValue() == 0)
4089 return false;
4090 FT = AT->getElementType();
4091 }
4092 if (isEmptyRecord(getContext(), FT, true))
4093 continue;
4094
4095 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4096 if (getContext().getLangOpts().CPlusPlus &&
4097 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4098 continue;
4099
4100 uint64_t FldMembers;
4101 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4102 return false;
4103
4104 Members = (RD->isUnion() ?
4105 std::max(Members, FldMembers) : Members + FldMembers);
4106 }
4107
4108 if (!Base)
4109 return false;
4110
4111 // Ensure there is no padding.
4112 if (getContext().getTypeSize(Base) * Members !=
4113 getContext().getTypeSize(Ty))
4114 return false;
4115 } else {
4116 Members = 1;
4117 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4118 Members = 2;
4119 Ty = CT->getElementType();
4120 }
4121
Reid Klecknere9f6a712014-10-31 17:10:41 +00004122 // Most ABIs only support float, double, and some vector type widths.
4123 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004124 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004125
4126 // The base type must be the same for all members. Types that
4127 // agree in both total size and mode (float vs. vector) are
4128 // treated as being equivalent here.
4129 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004130 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004131 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004132 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4133 // so make sure to widen it explicitly.
4134 if (const VectorType *VT = Base->getAs<VectorType>()) {
4135 QualType EltTy = VT->getElementType();
4136 unsigned NumElements =
4137 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4138 Base = getContext()
4139 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4140 .getTypePtr();
4141 }
4142 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004143
4144 if (Base->isVectorType() != TyPtr->isVectorType() ||
4145 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4146 return false;
4147 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004148 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4149}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004150
Reid Klecknere9f6a712014-10-31 17:10:41 +00004151bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4152 // Homogeneous aggregates for ELFv2 must have base types of float,
4153 // double, long double, or 128-bit vectors.
4154 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4155 if (BT->getKind() == BuiltinType::Float ||
4156 BT->getKind() == BuiltinType::Double ||
4157 BT->getKind() == BuiltinType::LongDouble)
4158 return true;
4159 }
4160 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004161 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004162 return true;
4163 }
4164 return false;
4165}
4166
4167bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4168 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004169 // Vector types require one register, floating point types require one
4170 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004171 uint32_t NumRegs =
4172 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004173
4174 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004175 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004176}
4177
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004178ABIArgInfo
4179PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004180 Ty = useFirstFieldIfTransparentUnion(Ty);
4181
Bill Schmidt90b22c92012-11-27 02:46:43 +00004182 if (Ty->isAnyComplexType())
4183 return ABIArgInfo::getDirect();
4184
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004185 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4186 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004187 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004188 uint64_t Size = getContext().getTypeSize(Ty);
4189 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004190 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004191 else if (Size < 128) {
4192 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4193 return ABIArgInfo::getDirect(CoerceTy);
4194 }
4195 }
4196
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004197 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004198 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004199 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004200
John McCall7f416cc2015-09-08 08:05:57 +00004201 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4202 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004203
4204 // ELFv2 homogeneous aggregates are passed as array types.
4205 const Type *Base = nullptr;
4206 uint64_t Members = 0;
4207 if (Kind == ELFv2 &&
4208 isHomogeneousAggregate(Ty, Base, Members)) {
4209 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4210 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4211 return ABIArgInfo::getDirect(CoerceTy);
4212 }
4213
Ulrich Weigand601957f2014-07-21 00:56:36 +00004214 // If an aggregate may end up fully in registers, we do not
4215 // use the ByVal method, but pass the aggregate as array.
4216 // This is usually beneficial since we avoid forcing the
4217 // back-end to store the argument to memory.
4218 uint64_t Bits = getContext().getTypeSize(Ty);
4219 if (Bits > 0 && Bits <= 8 * GPRBits) {
4220 llvm::Type *CoerceTy;
4221
4222 // Types up to 8 bytes are passed as integer type (which will be
4223 // properly aligned in the argument save area doubleword).
4224 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004225 CoerceTy =
4226 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004227 // Larger types are passed as arrays, with the base type selected
4228 // according to the required alignment in the save area.
4229 else {
4230 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004231 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004232 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4233 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4234 }
4235
4236 return ABIArgInfo::getDirect(CoerceTy);
4237 }
4238
Ulrich Weigandb7122372014-07-21 00:48:09 +00004239 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004240 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4241 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004242 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004243 }
4244
4245 return (isPromotableTypeForABI(Ty) ?
4246 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4247}
4248
4249ABIArgInfo
4250PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4251 if (RetTy->isVoidType())
4252 return ABIArgInfo::getIgnore();
4253
Bill Schmidta3d121c2012-12-17 04:20:17 +00004254 if (RetTy->isAnyComplexType())
4255 return ABIArgInfo::getDirect();
4256
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004257 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4258 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004259 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004260 uint64_t Size = getContext().getTypeSize(RetTy);
4261 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004262 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004263 else if (Size < 128) {
4264 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4265 return ABIArgInfo::getDirect(CoerceTy);
4266 }
4267 }
4268
Ulrich Weigandb7122372014-07-21 00:48:09 +00004269 if (isAggregateTypeForABI(RetTy)) {
4270 // ELFv2 homogeneous aggregates are returned as array types.
4271 const Type *Base = nullptr;
4272 uint64_t Members = 0;
4273 if (Kind == ELFv2 &&
4274 isHomogeneousAggregate(RetTy, Base, Members)) {
4275 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4276 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4277 return ABIArgInfo::getDirect(CoerceTy);
4278 }
4279
4280 // ELFv2 small aggregates are returned in up to two registers.
4281 uint64_t Bits = getContext().getTypeSize(RetTy);
4282 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4283 if (Bits == 0)
4284 return ABIArgInfo::getIgnore();
4285
4286 llvm::Type *CoerceTy;
4287 if (Bits > GPRBits) {
4288 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004289 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004290 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004291 CoerceTy =
4292 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004293 return ABIArgInfo::getDirect(CoerceTy);
4294 }
4295
4296 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004297 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004298 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004299
4300 return (isPromotableTypeForABI(RetTy) ?
4301 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4302}
4303
Bill Schmidt25cb3492012-10-03 19:18:57 +00004304// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004305Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4306 QualType Ty) const {
4307 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4308 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004309
John McCall7f416cc2015-09-08 08:05:57 +00004310 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004311
Bill Schmidt924c4782013-01-14 17:45:36 +00004312 // If we have a complex type and the base type is smaller than 8 bytes,
4313 // the ABI calls for the real and imaginary parts to be right-adjusted
4314 // in separate doublewords. However, Clang expects us to produce a
4315 // pointer to a structure with the two parts packed tightly. So generate
4316 // loads of the real and imaginary parts relative to the va_list pointer,
4317 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004318 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4319 CharUnits EltSize = TypeInfo.first / 2;
4320 if (EltSize < SlotSize) {
4321 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4322 SlotSize * 2, SlotSize,
4323 SlotSize, /*AllowHigher*/ true);
4324
4325 Address RealAddr = Addr;
4326 Address ImagAddr = RealAddr;
4327 if (CGF.CGM.getDataLayout().isBigEndian()) {
4328 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4329 SlotSize - EltSize);
4330 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4331 2 * SlotSize - EltSize);
4332 } else {
4333 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4334 }
4335
4336 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4337 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4338 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4339 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4340 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4341
4342 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4343 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4344 /*init*/ true);
4345 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004346 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004347 }
4348
John McCall7f416cc2015-09-08 08:05:57 +00004349 // Otherwise, just use the general rule.
4350 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4351 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004352}
4353
4354static bool
4355PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4356 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004357 // This is calculated from the LLVM and GCC tables and verified
4358 // against gcc output. AFAIK all ABIs use the same encoding.
4359
4360 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4361
4362 llvm::IntegerType *i8 = CGF.Int8Ty;
4363 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4364 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4365 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4366
4367 // 0-31: r0-31, the 8-byte general-purpose registers
4368 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4369
4370 // 32-63: fp0-31, the 8-byte floating-point registers
4371 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4372
4373 // 64-76 are various 4-byte special-purpose registers:
4374 // 64: mq
4375 // 65: lr
4376 // 66: ctr
4377 // 67: ap
4378 // 68-75 cr0-7
4379 // 76: xer
4380 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4381
4382 // 77-108: v0-31, the 16-byte vector registers
4383 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4384
4385 // 109: vrsave
4386 // 110: vscr
4387 // 111: spe_acc
4388 // 112: spefscr
4389 // 113: sfp
4390 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4391
4392 return false;
4393}
John McCallea8d8bb2010-03-11 00:10:12 +00004394
Bill Schmidt25cb3492012-10-03 19:18:57 +00004395bool
4396PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4397 CodeGen::CodeGenFunction &CGF,
4398 llvm::Value *Address) const {
4399
4400 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4401}
4402
4403bool
4404PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4405 llvm::Value *Address) const {
4406
4407 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4408}
4409
Chris Lattner0cf24192010-06-28 20:05:43 +00004410//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004411// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004412//===----------------------------------------------------------------------===//
4413
4414namespace {
4415
John McCall12f23522016-04-04 18:33:08 +00004416class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004417public:
4418 enum ABIKind {
4419 AAPCS = 0,
4420 DarwinPCS
4421 };
4422
4423private:
4424 ABIKind Kind;
4425
4426public:
John McCall12f23522016-04-04 18:33:08 +00004427 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4428 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004429
4430private:
4431 ABIKind getABIKind() const { return Kind; }
4432 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4433
4434 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004435 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004436 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4437 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4438 uint64_t Members) const override;
4439
Tim Northovera2ee4332014-03-29 15:09:45 +00004440 bool isIllegalVectorType(QualType Ty) const;
4441
David Blaikie1cbb9712014-11-14 19:09:44 +00004442 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004443 if (!getCXXABI().classifyReturnType(FI))
4444 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004445
Tim Northoverb047bfa2014-11-27 21:02:49 +00004446 for (auto &it : FI.arguments())
4447 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004448 }
4449
John McCall7f416cc2015-09-08 08:05:57 +00004450 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4451 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004452
John McCall7f416cc2015-09-08 08:05:57 +00004453 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4454 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004455
John McCall7f416cc2015-09-08 08:05:57 +00004456 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4457 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004458 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4459 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4460 }
John McCall12f23522016-04-04 18:33:08 +00004461
4462 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4463 ArrayRef<llvm::Type*> scalars,
4464 bool asReturnValue) const override {
4465 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4466 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004467};
4468
Tim Northover573cbee2014-05-24 12:52:07 +00004469class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004470public:
Tim Northover573cbee2014-05-24 12:52:07 +00004471 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4472 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004473
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004474 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004475 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4476 }
4477
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004478 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4479 return 31;
4480 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004481
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004482 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004483};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004484}
Tim Northovera2ee4332014-03-29 15:09:45 +00004485
Tim Northoverb047bfa2014-11-27 21:02:49 +00004486ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004487 Ty = useFirstFieldIfTransparentUnion(Ty);
4488
Tim Northovera2ee4332014-03-29 15:09:45 +00004489 // Handle illegal vector types here.
4490 if (isIllegalVectorType(Ty)) {
4491 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004492 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004493 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004494 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4495 return ABIArgInfo::getDirect(ResType);
4496 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004497 if (Size <= 32) {
4498 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004499 return ABIArgInfo::getDirect(ResType);
4500 }
4501 if (Size == 64) {
4502 llvm::Type *ResType =
4503 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004504 return ABIArgInfo::getDirect(ResType);
4505 }
4506 if (Size == 128) {
4507 llvm::Type *ResType =
4508 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004509 return ABIArgInfo::getDirect(ResType);
4510 }
John McCall7f416cc2015-09-08 08:05:57 +00004511 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004512 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004513
4514 if (!isAggregateTypeForABI(Ty)) {
4515 // Treat an enum type as its underlying type.
4516 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4517 Ty = EnumTy->getDecl()->getIntegerType();
4518
Tim Northovera2ee4332014-03-29 15:09:45 +00004519 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4520 ? ABIArgInfo::getExtend()
4521 : ABIArgInfo::getDirect());
4522 }
4523
4524 // Structures with either a non-trivial destructor or a non-trivial
4525 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004526 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004527 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4528 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004529 }
4530
4531 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4532 // elsewhere for GNU compatibility.
4533 if (isEmptyRecord(getContext(), Ty, true)) {
4534 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4535 return ABIArgInfo::getIgnore();
4536
Tim Northovera2ee4332014-03-29 15:09:45 +00004537 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4538 }
4539
4540 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004541 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004542 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004543 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004544 return ABIArgInfo::getDirect(
4545 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004546 }
4547
4548 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4549 uint64_t Size = getContext().getTypeSize(Ty);
4550 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004551 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004552 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004553
Tim Northovera2ee4332014-03-29 15:09:45 +00004554 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4555 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004556 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004557 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4558 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4559 }
4560 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4561 }
4562
John McCall7f416cc2015-09-08 08:05:57 +00004563 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004564}
4565
Tim Northover573cbee2014-05-24 12:52:07 +00004566ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004567 if (RetTy->isVoidType())
4568 return ABIArgInfo::getIgnore();
4569
4570 // Large vector types should be returned via memory.
4571 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004572 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004573
4574 if (!isAggregateTypeForABI(RetTy)) {
4575 // Treat an enum type as its underlying type.
4576 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4577 RetTy = EnumTy->getDecl()->getIntegerType();
4578
Tim Northover4dab6982014-04-18 13:46:08 +00004579 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4580 ? ABIArgInfo::getExtend()
4581 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004582 }
4583
Tim Northovera2ee4332014-03-29 15:09:45 +00004584 if (isEmptyRecord(getContext(), RetTy, true))
4585 return ABIArgInfo::getIgnore();
4586
Craig Topper8a13c412014-05-21 05:09:00 +00004587 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004588 uint64_t Members = 0;
4589 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004590 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4591 return ABIArgInfo::getDirect();
4592
4593 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4594 uint64_t Size = getContext().getTypeSize(RetTy);
4595 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004596 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004597 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004598
4599 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4600 // For aggregates with 16-byte alignment, we use i128.
4601 if (Alignment < 128 && Size == 128) {
4602 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4603 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4604 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004605 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4606 }
4607
John McCall7f416cc2015-09-08 08:05:57 +00004608 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004609}
4610
Tim Northover573cbee2014-05-24 12:52:07 +00004611/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4612bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004613 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4614 // Check whether VT is legal.
4615 unsigned NumElements = VT->getNumElements();
4616 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004617 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004618 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004619 return true;
4620 return Size != 64 && (Size != 128 || NumElements == 1);
4621 }
4622 return false;
4623}
4624
Reid Klecknere9f6a712014-10-31 17:10:41 +00004625bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4626 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4627 // point type or a short-vector type. This is the same as the 32-bit ABI,
4628 // but with the difference that any floating-point type is allowed,
4629 // including __fp16.
4630 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4631 if (BT->isFloatingPoint())
4632 return true;
4633 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4634 unsigned VecSize = getContext().getTypeSize(VT);
4635 if (VecSize == 64 || VecSize == 128)
4636 return true;
4637 }
4638 return false;
4639}
4640
4641bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4642 uint64_t Members) const {
4643 return Members <= 4;
4644}
4645
John McCall7f416cc2015-09-08 08:05:57 +00004646Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004647 QualType Ty,
4648 CodeGenFunction &CGF) const {
4649 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004650 bool IsIndirect = AI.isIndirect();
4651
Tim Northoverb047bfa2014-11-27 21:02:49 +00004652 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4653 if (IsIndirect)
4654 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4655 else if (AI.getCoerceToType())
4656 BaseTy = AI.getCoerceToType();
4657
4658 unsigned NumRegs = 1;
4659 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4660 BaseTy = ArrTy->getElementType();
4661 NumRegs = ArrTy->getNumElements();
4662 }
4663 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4664
Tim Northovera2ee4332014-03-29 15:09:45 +00004665 // The AArch64 va_list type and handling is specified in the Procedure Call
4666 // Standard, section B.4:
4667 //
4668 // struct {
4669 // void *__stack;
4670 // void *__gr_top;
4671 // void *__vr_top;
4672 // int __gr_offs;
4673 // int __vr_offs;
4674 // };
4675
4676 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4677 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4678 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4679 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004680
John McCall7f416cc2015-09-08 08:05:57 +00004681 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4682 CharUnits TyAlign = TyInfo.second;
4683
4684 Address reg_offs_p = Address::invalid();
4685 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004686 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004687 CharUnits reg_top_offset;
4688 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004689 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004690 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004691 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004692 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4693 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004694 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4695 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004696 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004697 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004699 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004700 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004701 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4702 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004703 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4704 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004705 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004706 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004707 }
4708
4709 //=======================================
4710 // Find out where argument was passed
4711 //=======================================
4712
4713 // If reg_offs >= 0 we're already using the stack for this type of
4714 // argument. We don't want to keep updating reg_offs (in case it overflows,
4715 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4716 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004717 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004718 UsingStack = CGF.Builder.CreateICmpSGE(
4719 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4720
4721 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4722
4723 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004724 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004725 CGF.EmitBlock(MaybeRegBlock);
4726
4727 // Integer arguments may need to correct register alignment (for example a
4728 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4729 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004730 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4731 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004732
4733 reg_offs = CGF.Builder.CreateAdd(
4734 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4735 "align_regoffs");
4736 reg_offs = CGF.Builder.CreateAnd(
4737 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4738 "aligned_regoffs");
4739 }
4740
4741 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004742 // The fact that this is done unconditionally reflects the fact that
4743 // allocating an argument to the stack also uses up all the remaining
4744 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004745 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004746 NewOffset = CGF.Builder.CreateAdd(
4747 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4748 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4749
4750 // Now we're in a position to decide whether this argument really was in
4751 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004752 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004753 InRegs = CGF.Builder.CreateICmpSLE(
4754 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4755
4756 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4757
4758 //=======================================
4759 // Argument was in registers
4760 //=======================================
4761
4762 // Now we emit the code for if the argument was originally passed in
4763 // registers. First start the appropriate block:
4764 CGF.EmitBlock(InRegBlock);
4765
John McCall7f416cc2015-09-08 08:05:57 +00004766 llvm::Value *reg_top = nullptr;
4767 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4768 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004769 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004770 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4771 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4772 Address RegAddr = Address::invalid();
4773 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004774
4775 if (IsIndirect) {
4776 // If it's been passed indirectly (actually a struct), whatever we find from
4777 // stored registers or on the stack will actually be a struct **.
4778 MemTy = llvm::PointerType::getUnqual(MemTy);
4779 }
4780
Craig Topper8a13c412014-05-21 05:09:00 +00004781 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004782 uint64_t NumMembers = 0;
4783 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004784 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004785 // Homogeneous aggregates passed in registers will have their elements split
4786 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4787 // qN+1, ...). We reload and store into a temporary local variable
4788 // contiguously.
4789 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004790 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004791 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4792 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004793 Address Tmp = CGF.CreateTempAlloca(HFATy,
4794 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004795
John McCall7f416cc2015-09-08 08:05:57 +00004796 // On big-endian platforms, the value will be right-aligned in its slot.
4797 int Offset = 0;
4798 if (CGF.CGM.getDataLayout().isBigEndian() &&
4799 BaseTyInfo.first.getQuantity() < 16)
4800 Offset = 16 - BaseTyInfo.first.getQuantity();
4801
Tim Northovera2ee4332014-03-29 15:09:45 +00004802 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004803 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4804 Address LoadAddr =
4805 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4806 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4807
4808 Address StoreAddr =
4809 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004810
4811 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4812 CGF.Builder.CreateStore(Elem, StoreAddr);
4813 }
4814
John McCall7f416cc2015-09-08 08:05:57 +00004815 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004816 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004817 // Otherwise the object is contiguous in memory.
4818
4819 // It might be right-aligned in its slot.
4820 CharUnits SlotSize = BaseAddr.getAlignment();
4821 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004822 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004823 TyInfo.first < SlotSize) {
4824 CharUnits Offset = SlotSize - TyInfo.first;
4825 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004826 }
4827
John McCall7f416cc2015-09-08 08:05:57 +00004828 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004829 }
4830
4831 CGF.EmitBranch(ContBlock);
4832
4833 //=======================================
4834 // Argument was on the stack
4835 //=======================================
4836 CGF.EmitBlock(OnStackBlock);
4837
John McCall7f416cc2015-09-08 08:05:57 +00004838 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4839 CharUnits::Zero(), "stack_p");
4840 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004841
John McCall7f416cc2015-09-08 08:05:57 +00004842 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004843 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004844 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4845 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004846
John McCall7f416cc2015-09-08 08:05:57 +00004847 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004848
John McCall7f416cc2015-09-08 08:05:57 +00004849 OnStackPtr = CGF.Builder.CreateAdd(
4850 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004851 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004852 OnStackPtr = CGF.Builder.CreateAnd(
4853 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004854 "align_stack");
4855
John McCall7f416cc2015-09-08 08:05:57 +00004856 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004857 }
John McCall7f416cc2015-09-08 08:05:57 +00004858 Address OnStackAddr(OnStackPtr,
4859 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004860
John McCall7f416cc2015-09-08 08:05:57 +00004861 // All stack slots are multiples of 8 bytes.
4862 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4863 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004864 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004865 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004866 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004867 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004868
John McCall7f416cc2015-09-08 08:05:57 +00004869 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004870 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004871 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004872
4873 // Write the new value of __stack for the next call to va_arg
4874 CGF.Builder.CreateStore(NewStack, stack_p);
4875
4876 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004877 TyInfo.first < StackSlotSize) {
4878 CharUnits Offset = StackSlotSize - TyInfo.first;
4879 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004880 }
4881
John McCall7f416cc2015-09-08 08:05:57 +00004882 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004883
4884 CGF.EmitBranch(ContBlock);
4885
4886 //=======================================
4887 // Tidy up
4888 //=======================================
4889 CGF.EmitBlock(ContBlock);
4890
John McCall7f416cc2015-09-08 08:05:57 +00004891 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4892 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004893
4894 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004895 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4896 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004897
4898 return ResAddr;
4899}
4900
John McCall7f416cc2015-09-08 08:05:57 +00004901Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4902 CodeGenFunction &CGF) const {
4903 // The backend's lowering doesn't support va_arg for aggregates or
4904 // illegal vector types. Lower VAArg here for these cases and use
4905 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004906 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004907 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004908
John McCall7f416cc2015-09-08 08:05:57 +00004909 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004910
John McCall7f416cc2015-09-08 08:05:57 +00004911 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004912 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004913 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4914 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4915 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004916 }
4917
John McCall7f416cc2015-09-08 08:05:57 +00004918 // The size of the actual thing passed, which might end up just
4919 // being a pointer for indirect types.
4920 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4921
4922 // Arguments bigger than 16 bytes which aren't homogeneous
4923 // aggregates should be passed indirectly.
4924 bool IsIndirect = false;
4925 if (TyInfo.first.getQuantity() > 16) {
4926 const Type *Base = nullptr;
4927 uint64_t Members = 0;
4928 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004929 }
4930
John McCall7f416cc2015-09-08 08:05:57 +00004931 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4932 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004933}
4934
4935//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004936// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004937//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004938
4939namespace {
4940
John McCall12f23522016-04-04 18:33:08 +00004941class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004942public:
4943 enum ABIKind {
4944 APCS = 0,
4945 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004946 AAPCS_VFP = 2,
4947 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004948 };
4949
4950private:
4951 ABIKind Kind;
4952
4953public:
John McCall12f23522016-04-04 18:33:08 +00004954 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
4955 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004956 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004957 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004958
John McCall3480ef22011-08-30 01:42:09 +00004959 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004960 switch (getTarget().getTriple().getEnvironment()) {
4961 case llvm::Triple::Android:
4962 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004963 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004964 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004965 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00004966 case llvm::Triple::MuslEABI:
4967 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004968 return true;
4969 default:
4970 return false;
4971 }
John McCall3480ef22011-08-30 01:42:09 +00004972 }
4973
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004974 bool isEABIHF() const {
4975 switch (getTarget().getTriple().getEnvironment()) {
4976 case llvm::Triple::EABIHF:
4977 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00004978 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004979 return true;
4980 default:
4981 return false;
4982 }
4983 }
4984
Daniel Dunbar020daa92009-09-12 01:00:39 +00004985 ABIKind getABIKind() const { return Kind; }
4986
Tim Northovera484bc02013-10-01 14:34:25 +00004987private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004988 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004989 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004990 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004991
Reid Klecknere9f6a712014-10-31 17:10:41 +00004992 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4993 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4994 uint64_t Members) const override;
4995
Craig Topper4f12f102014-03-12 06:41:41 +00004996 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004997
John McCall7f416cc2015-09-08 08:05:57 +00004998 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4999 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005000
5001 llvm::CallingConv::ID getLLVMDefaultCC() const;
5002 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005003 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005004
5005 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5006 ArrayRef<llvm::Type*> scalars,
5007 bool asReturnValue) const override {
5008 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5009 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005010};
5011
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005012class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5013public:
Chris Lattner2b037972010-07-29 02:01:43 +00005014 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5015 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005016
John McCall3480ef22011-08-30 01:42:09 +00005017 const ARMABIInfo &getABIInfo() const {
5018 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5019 }
5020
Craig Topper4f12f102014-03-12 06:41:41 +00005021 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005022 return 13;
5023 }
Roman Divackyc1617352011-05-18 19:36:54 +00005024
Craig Topper4f12f102014-03-12 06:41:41 +00005025 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005026 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5027 }
5028
Roman Divackyc1617352011-05-18 19:36:54 +00005029 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005030 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005031 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005032
5033 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005034 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005035 return false;
5036 }
John McCall3480ef22011-08-30 01:42:09 +00005037
Craig Topper4f12f102014-03-12 06:41:41 +00005038 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005039 if (getABIInfo().isEABI()) return 88;
5040 return TargetCodeGenInfo::getSizeOfUnwindException();
5041 }
Tim Northovera484bc02013-10-01 14:34:25 +00005042
Eric Christopher162c91c2015-06-05 22:03:00 +00005043 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005044 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005045 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005046 if (!FD)
5047 return;
5048
5049 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5050 if (!Attr)
5051 return;
5052
5053 const char *Kind;
5054 switch (Attr->getInterrupt()) {
5055 case ARMInterruptAttr::Generic: Kind = ""; break;
5056 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5057 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5058 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5059 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5060 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5061 }
5062
5063 llvm::Function *Fn = cast<llvm::Function>(GV);
5064
5065 Fn->addFnAttr("interrupt", Kind);
5066
Tim Northover5627d392015-10-30 16:30:45 +00005067 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5068 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005069 return;
5070
5071 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5072 // however this is not necessarily true on taking any interrupt. Instruct
5073 // the backend to perform a realignment as part of the function prologue.
5074 llvm::AttrBuilder B;
5075 B.addStackAlignmentAttr(8);
5076 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5077 llvm::AttributeSet::get(CGM.getLLVMContext(),
5078 llvm::AttributeSet::FunctionIndex,
5079 B));
5080 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005081};
5082
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005083class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005084public:
5085 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5086 : ARMTargetCodeGenInfo(CGT, K) {}
5087
Eric Christopher162c91c2015-06-05 22:03:00 +00005088 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005089 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005090
5091 void getDependentLibraryOption(llvm::StringRef Lib,
5092 llvm::SmallString<24> &Opt) const override {
5093 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5094 }
5095
5096 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5097 llvm::SmallString<32> &Opt) const override {
5098 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5099 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005100};
5101
Eric Christopher162c91c2015-06-05 22:03:00 +00005102void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005103 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005104 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005105 addStackProbeSizeTargetAttribute(D, GV, CGM);
5106}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005107}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005108
Chris Lattner22326a12010-07-29 02:31:05 +00005109void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005110 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005111 FI.getReturnInfo() =
5112 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005113
Tim Northoverbc784d12015-02-24 17:22:40 +00005114 for (auto &I : FI.arguments())
5115 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005116
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005117 // Always honor user-specified calling convention.
5118 if (FI.getCallingConvention() != llvm::CallingConv::C)
5119 return;
5120
John McCall882987f2013-02-28 19:01:20 +00005121 llvm::CallingConv::ID cc = getRuntimeCC();
5122 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005123 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005124}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005125
John McCall882987f2013-02-28 19:01:20 +00005126/// Return the default calling convention that LLVM will use.
5127llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5128 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005129 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005130 return llvm::CallingConv::ARM_AAPCS_VFP;
5131 else if (isEABI())
5132 return llvm::CallingConv::ARM_AAPCS;
5133 else
5134 return llvm::CallingConv::ARM_APCS;
5135}
5136
5137/// Return the calling convention that our ABI would like us to use
5138/// as the C calling convention.
5139llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005140 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005141 case APCS: return llvm::CallingConv::ARM_APCS;
5142 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5143 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005144 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005145 }
John McCall882987f2013-02-28 19:01:20 +00005146 llvm_unreachable("bad ABI kind");
5147}
5148
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005149void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005150 assert(getRuntimeCC() == llvm::CallingConv::C);
5151
5152 // Don't muddy up the IR with a ton of explicit annotations if
5153 // they'd just match what LLVM will infer from the triple.
5154 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5155 if (abiCC != getLLVMDefaultCC())
5156 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005157
Tim Northover5627d392015-10-30 16:30:45 +00005158 // AAPCS apparently requires runtime support functions to be soft-float, but
5159 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5160 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5161 switch (getABIKind()) {
5162 case APCS:
5163 case AAPCS16_VFP:
5164 if (abiCC != getLLVMDefaultCC())
5165 BuiltinCC = abiCC;
5166 break;
5167 case AAPCS:
5168 case AAPCS_VFP:
5169 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5170 break;
5171 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005172}
5173
Tim Northoverbc784d12015-02-24 17:22:40 +00005174ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5175 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005176 // 6.1.2.1 The following argument types are VFP CPRCs:
5177 // A single-precision floating-point type (including promoted
5178 // half-precision types); A double-precision floating-point type;
5179 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5180 // with a Base Type of a single- or double-precision floating-point type,
5181 // 64-bit containerized vectors or 128-bit containerized vectors with one
5182 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005183 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005184
Reid Klecknerb1be6832014-11-15 01:41:41 +00005185 Ty = useFirstFieldIfTransparentUnion(Ty);
5186
Manman Renfef9e312012-10-16 19:18:39 +00005187 // Handle illegal vector types here.
5188 if (isIllegalVectorType(Ty)) {
5189 uint64_t Size = getContext().getTypeSize(Ty);
5190 if (Size <= 32) {
5191 llvm::Type *ResType =
5192 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005193 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005194 }
5195 if (Size == 64) {
5196 llvm::Type *ResType = llvm::VectorType::get(
5197 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005198 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005199 }
5200 if (Size == 128) {
5201 llvm::Type *ResType = llvm::VectorType::get(
5202 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005203 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005204 }
John McCall7f416cc2015-09-08 08:05:57 +00005205 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005206 }
5207
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005208 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5209 // unspecified. This is not done for OpenCL as it handles the half type
5210 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005211 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005212 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5213 llvm::Type::getFloatTy(getVMContext()) :
5214 llvm::Type::getInt32Ty(getVMContext());
5215 return ABIArgInfo::getDirect(ResType);
5216 }
5217
John McCalla1dee5302010-08-22 10:59:02 +00005218 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005219 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005220 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005221 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005222 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005223
Tim Northover5a1558e2014-11-07 22:30:50 +00005224 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5225 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005226 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005227
Oliver Stannard405bded2014-02-11 09:25:50 +00005228 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005229 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005230 }
Tim Northover1060eae2013-06-21 22:49:34 +00005231
Daniel Dunbar09d33622009-09-14 21:54:03 +00005232 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005233 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005234 return ABIArgInfo::getIgnore();
5235
Tim Northover5a1558e2014-11-07 22:30:50 +00005236 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005237 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5238 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005239 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005240 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005241 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005242 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005243 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005244 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005245 }
Tim Northover5627d392015-10-30 16:30:45 +00005246 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5247 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5248 // this convention even for a variadic function: the backend will use GPRs
5249 // if needed.
5250 const Type *Base = nullptr;
5251 uint64_t Members = 0;
5252 if (isHomogeneousAggregate(Ty, Base, Members)) {
5253 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5254 llvm::Type *Ty =
5255 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5256 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5257 }
5258 }
5259
5260 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5261 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5262 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5263 // bigger than 128-bits, they get placed in space allocated by the caller,
5264 // and a pointer is passed.
5265 return ABIArgInfo::getIndirect(
5266 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005267 }
5268
Manman Ren6c30e132012-08-13 21:23:55 +00005269 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005270 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5271 // most 8-byte. We realign the indirect argument if type alignment is bigger
5272 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005273 uint64_t ABIAlign = 4;
5274 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5275 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005276 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005277 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005278
Manman Ren8cd99812012-11-06 04:58:01 +00005279 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005280 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005281 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5282 /*ByVal=*/true,
5283 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005284 }
5285
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005286 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005287 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005288 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005289 // FIXME: Try to match the types of the arguments more accurately where
5290 // we can.
5291 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005292 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5293 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005294 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005295 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5296 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005297 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005298
Tim Northover5a1558e2014-11-07 22:30:50 +00005299 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005300}
5301
Chris Lattner458b2aa2010-07-29 02:16:43 +00005302static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005303 llvm::LLVMContext &VMContext) {
5304 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5305 // is called integer-like if its size is less than or equal to one word, and
5306 // the offset of each of its addressable sub-fields is zero.
5307
5308 uint64_t Size = Context.getTypeSize(Ty);
5309
5310 // Check that the type fits in a word.
5311 if (Size > 32)
5312 return false;
5313
5314 // FIXME: Handle vector types!
5315 if (Ty->isVectorType())
5316 return false;
5317
Daniel Dunbard53bac72009-09-14 02:20:34 +00005318 // Float types are never treated as "integer like".
5319 if (Ty->isRealFloatingType())
5320 return false;
5321
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005322 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005323 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005324 return true;
5325
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005326 // Small complex integer types are "integer like".
5327 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5328 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005329
5330 // Single element and zero sized arrays should be allowed, by the definition
5331 // above, but they are not.
5332
5333 // Otherwise, it must be a record type.
5334 const RecordType *RT = Ty->getAs<RecordType>();
5335 if (!RT) return false;
5336
5337 // Ignore records with flexible arrays.
5338 const RecordDecl *RD = RT->getDecl();
5339 if (RD->hasFlexibleArrayMember())
5340 return false;
5341
5342 // Check that all sub-fields are at offset 0, and are themselves "integer
5343 // like".
5344 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5345
5346 bool HadField = false;
5347 unsigned idx = 0;
5348 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5349 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005350 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005351
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005352 // Bit-fields are not addressable, we only need to verify they are "integer
5353 // like". We still have to disallow a subsequent non-bitfield, for example:
5354 // struct { int : 0; int x }
5355 // is non-integer like according to gcc.
5356 if (FD->isBitField()) {
5357 if (!RD->isUnion())
5358 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005359
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005360 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5361 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005362
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005363 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005364 }
5365
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005366 // Check if this field is at offset 0.
5367 if (Layout.getFieldOffset(idx) != 0)
5368 return false;
5369
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005370 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5371 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005372
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005373 // Only allow at most one field in a structure. This doesn't match the
5374 // wording above, but follows gcc in situations with a field following an
5375 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005376 if (!RD->isUnion()) {
5377 if (HadField)
5378 return false;
5379
5380 HadField = true;
5381 }
5382 }
5383
5384 return true;
5385}
5386
Oliver Stannard405bded2014-02-11 09:25:50 +00005387ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5388 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005389 bool IsEffectivelyAAPCS_VFP =
5390 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005391
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005392 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005393 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005394
Daniel Dunbar19964db2010-09-23 01:54:32 +00005395 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005396 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005397 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005398 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005399
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005400 // __fp16 gets returned as if it were an int or float, but with the top 16
5401 // bits unspecified. This is not done for OpenCL as it handles the half type
5402 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005403 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005404 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5405 llvm::Type::getFloatTy(getVMContext()) :
5406 llvm::Type::getInt32Ty(getVMContext());
5407 return ABIArgInfo::getDirect(ResType);
5408 }
5409
John McCalla1dee5302010-08-22 10:59:02 +00005410 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005411 // Treat an enum type as its underlying type.
5412 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5413 RetTy = EnumTy->getDecl()->getIntegerType();
5414
Tim Northover5a1558e2014-11-07 22:30:50 +00005415 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5416 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005417 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005418
5419 // Are we following APCS?
5420 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005421 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005422 return ABIArgInfo::getIgnore();
5423
Daniel Dunbareedf1512010-02-01 23:31:19 +00005424 // Complex types are all returned as packed integers.
5425 //
5426 // FIXME: Consider using 2 x vector types if the back end handles them
5427 // correctly.
5428 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005429 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5430 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005431
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005432 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005433 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005434 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005435 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005436 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005437 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005438 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005439 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5440 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005441 }
5442
5443 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005444 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005445 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005446
5447 // Otherwise this is an AAPCS variant.
5448
Chris Lattner458b2aa2010-07-29 02:16:43 +00005449 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005450 return ABIArgInfo::getIgnore();
5451
Bob Wilson1d9269a2011-11-02 04:51:36 +00005452 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005453 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005454 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005455 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005456 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005457 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005458 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005459 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005460 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005461 }
5462
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005463 // Aggregates <= 4 bytes are returned in r0; other aggregates
5464 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005465 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005466 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005467 if (getDataLayout().isBigEndian())
5468 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005469 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005470
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005471 // Return in the smallest viable integer type.
5472 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005473 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005474 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005475 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5476 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005477 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5478 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5479 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005480 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005481 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005482 }
5483
John McCall7f416cc2015-09-08 08:05:57 +00005484 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005485}
5486
Manman Renfef9e312012-10-16 19:18:39 +00005487/// isIllegalVector - check whether Ty is an illegal vector type.
5488bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005489 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5490 if (isAndroid()) {
5491 // Android shipped using Clang 3.1, which supported a slightly different
5492 // vector ABI. The primary differences were that 3-element vector types
5493 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5494 // accepts that legacy behavior for Android only.
5495 // Check whether VT is legal.
5496 unsigned NumElements = VT->getNumElements();
5497 // NumElements should be power of 2 or equal to 3.
5498 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5499 return true;
5500 } else {
5501 // Check whether VT is legal.
5502 unsigned NumElements = VT->getNumElements();
5503 uint64_t Size = getContext().getTypeSize(VT);
5504 // NumElements should be power of 2.
5505 if (!llvm::isPowerOf2_32(NumElements))
5506 return true;
5507 // Size should be greater than 32 bits.
5508 return Size <= 32;
5509 }
Manman Renfef9e312012-10-16 19:18:39 +00005510 }
5511 return false;
5512}
5513
Reid Klecknere9f6a712014-10-31 17:10:41 +00005514bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5515 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5516 // double, or 64-bit or 128-bit vectors.
5517 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5518 if (BT->getKind() == BuiltinType::Float ||
5519 BT->getKind() == BuiltinType::Double ||
5520 BT->getKind() == BuiltinType::LongDouble)
5521 return true;
5522 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5523 unsigned VecSize = getContext().getTypeSize(VT);
5524 if (VecSize == 64 || VecSize == 128)
5525 return true;
5526 }
5527 return false;
5528}
5529
5530bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5531 uint64_t Members) const {
5532 return Members <= 4;
5533}
5534
John McCall7f416cc2015-09-08 08:05:57 +00005535Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5536 QualType Ty) const {
5537 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005538
John McCall7f416cc2015-09-08 08:05:57 +00005539 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005540 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005541 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5542 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5543 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005544 }
5545
John McCall7f416cc2015-09-08 08:05:57 +00005546 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5547 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005548
John McCall7f416cc2015-09-08 08:05:57 +00005549 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5550 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005551 const Type *Base = nullptr;
5552 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005553 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5554 IsIndirect = true;
5555
Tim Northover5627d392015-10-30 16:30:45 +00005556 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5557 // allocated by the caller.
5558 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5559 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5560 !isHomogeneousAggregate(Ty, Base, Members)) {
5561 IsIndirect = true;
5562
John McCall7f416cc2015-09-08 08:05:57 +00005563 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005564 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5565 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005566 // Our callers should be prepared to handle an under-aligned address.
5567 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5568 getABIKind() == ARMABIInfo::AAPCS) {
5569 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5570 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005571 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5572 // ARMv7k allows type alignment up to 16 bytes.
5573 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5574 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005575 } else {
5576 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005577 }
John McCall7f416cc2015-09-08 08:05:57 +00005578 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005579
John McCall7f416cc2015-09-08 08:05:57 +00005580 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5581 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005582}
5583
Chris Lattner0cf24192010-06-28 20:05:43 +00005584//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005585// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005586//===----------------------------------------------------------------------===//
5587
5588namespace {
5589
Justin Holewinski83e96682012-05-24 17:43:12 +00005590class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005591public:
Justin Holewinski36837432013-03-30 14:38:24 +00005592 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005593
5594 ABIArgInfo classifyReturnType(QualType RetTy) const;
5595 ABIArgInfo classifyArgumentType(QualType Ty) const;
5596
Craig Topper4f12f102014-03-12 06:41:41 +00005597 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005598 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5599 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005600};
5601
Justin Holewinski83e96682012-05-24 17:43:12 +00005602class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005603public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005604 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5605 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005606
Eric Christopher162c91c2015-06-05 22:03:00 +00005607 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005608 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005609private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005610 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5611 // resulting MDNode to the nvvm.annotations MDNode.
5612 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005613};
5614
Justin Holewinski83e96682012-05-24 17:43:12 +00005615ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005616 if (RetTy->isVoidType())
5617 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005618
5619 // note: this is different from default ABI
5620 if (!RetTy->isScalarType())
5621 return ABIArgInfo::getDirect();
5622
5623 // Treat an enum type as its underlying type.
5624 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5625 RetTy = EnumTy->getDecl()->getIntegerType();
5626
5627 return (RetTy->isPromotableIntegerType() ?
5628 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005629}
5630
Justin Holewinski83e96682012-05-24 17:43:12 +00005631ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005632 // Treat an enum type as its underlying type.
5633 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5634 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005635
Eli Bendersky95338a02014-10-29 13:43:21 +00005636 // Return aggregates type as indirect by value
5637 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005638 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005639
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005640 return (Ty->isPromotableIntegerType() ?
5641 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005642}
5643
Justin Holewinski83e96682012-05-24 17:43:12 +00005644void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005645 if (!getCXXABI().classifyReturnType(FI))
5646 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005647 for (auto &I : FI.arguments())
5648 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005649
5650 // Always honor user-specified calling convention.
5651 if (FI.getCallingConvention() != llvm::CallingConv::C)
5652 return;
5653
John McCall882987f2013-02-28 19:01:20 +00005654 FI.setEffectiveCallingConvention(getRuntimeCC());
5655}
5656
John McCall7f416cc2015-09-08 08:05:57 +00005657Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5658 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005659 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005660}
5661
Justin Holewinski83e96682012-05-24 17:43:12 +00005662void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005663setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005664 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005665 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005666 if (!FD) return;
5667
5668 llvm::Function *F = cast<llvm::Function>(GV);
5669
5670 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005671 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005672 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005673 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005674 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005675 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005676 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5677 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005678 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005679 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005680 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005681 }
Justin Holewinski38031972011-10-05 17:58:44 +00005682
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005683 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005684 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005685 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005686 // __global__ functions cannot be called from the device, we do not
5687 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005688 if (FD->hasAttr<CUDAGlobalAttr>()) {
5689 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5690 addNVVMMetadata(F, "kernel", 1);
5691 }
Artem Belevich7093e402015-04-21 22:55:54 +00005692 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005693 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005694 llvm::APSInt MaxThreads(32);
5695 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5696 if (MaxThreads > 0)
5697 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5698
5699 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5700 // not specified in __launch_bounds__ or if the user specified a 0 value,
5701 // we don't have to add a PTX directive.
5702 if (Attr->getMinBlocks()) {
5703 llvm::APSInt MinBlocks(32);
5704 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5705 if (MinBlocks > 0)
5706 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5707 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005708 }
5709 }
Justin Holewinski38031972011-10-05 17:58:44 +00005710 }
5711}
5712
Eli Benderskye06a2c42014-04-15 16:57:05 +00005713void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5714 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005715 llvm::Module *M = F->getParent();
5716 llvm::LLVMContext &Ctx = M->getContext();
5717
5718 // Get "nvvm.annotations" metadata node
5719 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5720
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005721 llvm::Metadata *MDVals[] = {
5722 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5723 llvm::ConstantAsMetadata::get(
5724 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005725 // Append metadata to nvvm.annotations
5726 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5727}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005728}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005729
5730//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005731// SystemZ ABI Implementation
5732//===----------------------------------------------------------------------===//
5733
5734namespace {
5735
Bryan Chane3f1ed52016-04-28 13:56:43 +00005736class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005737 bool HasVector;
5738
Ulrich Weigand47445072013-05-06 16:26:41 +00005739public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005740 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005741 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005742
5743 bool isPromotableIntegerType(QualType Ty) const;
5744 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005745 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005746 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005747 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005748
5749 ABIArgInfo classifyReturnType(QualType RetTy) const;
5750 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5751
Craig Topper4f12f102014-03-12 06:41:41 +00005752 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005753 if (!getCXXABI().classifyReturnType(FI))
5754 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005755 for (auto &I : FI.arguments())
5756 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005757 }
5758
John McCall7f416cc2015-09-08 08:05:57 +00005759 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5760 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005761
5762 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5763 ArrayRef<llvm::Type*> scalars,
5764 bool asReturnValue) const override {
5765 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5766 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005767};
5768
5769class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5770public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005771 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5772 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005773};
5774
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005775}
Ulrich Weigand47445072013-05-06 16:26:41 +00005776
5777bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5778 // Treat an enum type as its underlying type.
5779 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5780 Ty = EnumTy->getDecl()->getIntegerType();
5781
5782 // Promotable integer types are required to be promoted by the ABI.
5783 if (Ty->isPromotableIntegerType())
5784 return true;
5785
5786 // 32-bit values must also be promoted.
5787 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5788 switch (BT->getKind()) {
5789 case BuiltinType::Int:
5790 case BuiltinType::UInt:
5791 return true;
5792 default:
5793 return false;
5794 }
5795 return false;
5796}
5797
5798bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005799 return (Ty->isAnyComplexType() ||
5800 Ty->isVectorType() ||
5801 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005802}
5803
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005804bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5805 return (HasVector &&
5806 Ty->isVectorType() &&
5807 getContext().getTypeSize(Ty) <= 128);
5808}
5809
Ulrich Weigand47445072013-05-06 16:26:41 +00005810bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5811 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5812 switch (BT->getKind()) {
5813 case BuiltinType::Float:
5814 case BuiltinType::Double:
5815 return true;
5816 default:
5817 return false;
5818 }
5819
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005820 return false;
5821}
5822
5823QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005824 if (const RecordType *RT = Ty->getAsStructureType()) {
5825 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005826 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005827
5828 // If this is a C++ record, check the bases first.
5829 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005830 for (const auto &I : CXXRD->bases()) {
5831 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005832
5833 // Empty bases don't affect things either way.
5834 if (isEmptyRecord(getContext(), Base, true))
5835 continue;
5836
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005837 if (!Found.isNull())
5838 return Ty;
5839 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005840 }
5841
5842 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005843 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005844 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005845 // Unlike isSingleElementStruct(), empty structure and array fields
5846 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005847 if (getContext().getLangOpts().CPlusPlus &&
5848 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5849 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005850
5851 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005852 // Nested structures still do though.
5853 if (!Found.isNull())
5854 return Ty;
5855 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005856 }
5857
5858 // Unlike isSingleElementStruct(), trailing padding is allowed.
5859 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005860 if (!Found.isNull())
5861 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005862 }
5863
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005864 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005865}
5866
John McCall7f416cc2015-09-08 08:05:57 +00005867Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5868 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005869 // Assume that va_list type is correct; should be pointer to LLVM type:
5870 // struct {
5871 // i64 __gpr;
5872 // i64 __fpr;
5873 // i8 *__overflow_arg_area;
5874 // i8 *__reg_save_area;
5875 // };
5876
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005877 // Every non-vector argument occupies 8 bytes and is passed by preference
5878 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5879 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005880 Ty = getContext().getCanonicalType(Ty);
5881 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005882 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005883 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005884 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005885 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005886 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005887 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005888 CharUnits UnpaddedSize;
5889 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005890 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005891 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5892 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005893 } else {
5894 if (AI.getCoerceToType())
5895 ArgTy = AI.getCoerceToType();
5896 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005897 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005898 UnpaddedSize = TyInfo.first;
5899 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005900 }
John McCall7f416cc2015-09-08 08:05:57 +00005901 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5902 if (IsVector && UnpaddedSize > PaddedSize)
5903 PaddedSize = CharUnits::fromQuantity(16);
5904 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005905
John McCall7f416cc2015-09-08 08:05:57 +00005906 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005907
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005908 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005909 llvm::Value *PaddedSizeV =
5910 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005911
5912 if (IsVector) {
5913 // Work out the address of a vector argument on the stack.
5914 // Vector arguments are always passed in the high bits of a
5915 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005916 Address OverflowArgAreaPtr =
5917 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005918 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005919 Address OverflowArgArea =
5920 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5921 TyInfo.second);
5922 Address MemAddr =
5923 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005924
5925 // Update overflow_arg_area_ptr pointer
5926 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005927 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5928 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005929 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5930
5931 return MemAddr;
5932 }
5933
John McCall7f416cc2015-09-08 08:05:57 +00005934 assert(PaddedSize.getQuantity() == 8);
5935
5936 unsigned MaxRegs, RegCountField, RegSaveIndex;
5937 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005938 if (InFPRs) {
5939 MaxRegs = 4; // Maximum of 4 FPR arguments
5940 RegCountField = 1; // __fpr
5941 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005942 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005943 } else {
5944 MaxRegs = 5; // Maximum of 5 GPR arguments
5945 RegCountField = 0; // __gpr
5946 RegSaveIndex = 2; // save offset for r2
5947 RegPadding = Padding; // values are passed in the low bits of a GPR
5948 }
5949
John McCall7f416cc2015-09-08 08:05:57 +00005950 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5951 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5952 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005953 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005954 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5955 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005956 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005957
5958 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5959 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5960 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5961 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5962
5963 // Emit code to load the value if it was passed in registers.
5964 CGF.EmitBlock(InRegBlock);
5965
5966 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005967 llvm::Value *ScaledRegCount =
5968 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5969 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005970 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5971 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005972 llvm::Value *RegOffset =
5973 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005974 Address RegSaveAreaPtr =
5975 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5976 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005977 llvm::Value *RegSaveArea =
5978 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005979 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5980 "raw_reg_addr"),
5981 PaddedSize);
5982 Address RegAddr =
5983 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005984
5985 // Update the register count
5986 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5987 llvm::Value *NewRegCount =
5988 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5989 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5990 CGF.EmitBranch(ContBlock);
5991
5992 // Emit code to load the value if it was passed in memory.
5993 CGF.EmitBlock(InMemBlock);
5994
5995 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005996 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5997 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5998 Address OverflowArgArea =
5999 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6000 PaddedSize);
6001 Address RawMemAddr =
6002 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6003 Address MemAddr =
6004 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006005
6006 // Update overflow_arg_area_ptr pointer
6007 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006008 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6009 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006010 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6011 CGF.EmitBranch(ContBlock);
6012
6013 // Return the appropriate result.
6014 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006015 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6016 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006017
6018 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006019 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6020 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006021
6022 return ResAddr;
6023}
6024
Ulrich Weigand47445072013-05-06 16:26:41 +00006025ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6026 if (RetTy->isVoidType())
6027 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006028 if (isVectorArgumentType(RetTy))
6029 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006030 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006031 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006032 return (isPromotableIntegerType(RetTy) ?
6033 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6034}
6035
6036ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6037 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006038 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006039 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006040
6041 // Integers and enums are extended to full register width.
6042 if (isPromotableIntegerType(Ty))
6043 return ABIArgInfo::getExtend();
6044
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006045 // Handle vector types and vector-like structure types. Note that
6046 // as opposed to float-like structure types, we do not allow any
6047 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006048 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006049 QualType SingleElementTy = GetSingleElementType(Ty);
6050 if (isVectorArgumentType(SingleElementTy) &&
6051 getContext().getTypeSize(SingleElementTy) == Size)
6052 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6053
6054 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006055 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006056 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006057
6058 // Handle small structures.
6059 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6060 // Structures with flexible arrays have variable length, so really
6061 // fail the size test above.
6062 const RecordDecl *RD = RT->getDecl();
6063 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006064 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006065
6066 // The structure is passed as an unextended integer, a float, or a double.
6067 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006068 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006069 assert(Size == 32 || Size == 64);
6070 if (Size == 32)
6071 PassTy = llvm::Type::getFloatTy(getVMContext());
6072 else
6073 PassTy = llvm::Type::getDoubleTy(getVMContext());
6074 } else
6075 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6076 return ABIArgInfo::getDirect(PassTy);
6077 }
6078
6079 // Non-structure compounds are passed indirectly.
6080 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006081 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006082
Craig Topper8a13c412014-05-21 05:09:00 +00006083 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006084}
6085
6086//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006087// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006088//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006089
6090namespace {
6091
6092class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6093public:
Chris Lattner2b037972010-07-29 02:01:43 +00006094 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6095 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006096 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006097 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006098};
6099
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006100}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006101
Eric Christopher162c91c2015-06-05 22:03:00 +00006102void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006103 llvm::GlobalValue *GV,
6104 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006105 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006106 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6107 // Handle 'interrupt' attribute:
6108 llvm::Function *F = cast<llvm::Function>(GV);
6109
6110 // Step 1: Set ISR calling convention.
6111 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6112
6113 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006114 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006115
6116 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006117 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006118 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6119 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006120 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006121 }
6122}
6123
Chris Lattner0cf24192010-06-28 20:05:43 +00006124//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006125// MIPS ABI Implementation. This works for both little-endian and
6126// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006127//===----------------------------------------------------------------------===//
6128
John McCall943fae92010-05-27 06:19:26 +00006129namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006130class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006131 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006132 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6133 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006134 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006135 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006136 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006137 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006138public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006139 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006140 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006141 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006142
6143 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006144 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006145 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006146 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6147 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006148 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006149};
6150
John McCall943fae92010-05-27 06:19:26 +00006151class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006152 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006153public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006154 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6155 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006156 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006157
Craig Topper4f12f102014-03-12 06:41:41 +00006158 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006159 return 29;
6160 }
6161
Eric Christopher162c91c2015-06-05 22:03:00 +00006162 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006163 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006164 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006165 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006166 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006167 if (FD->hasAttr<Mips16Attr>()) {
6168 Fn->addFnAttr("mips16");
6169 }
6170 else if (FD->hasAttr<NoMips16Attr>()) {
6171 Fn->addFnAttr("nomips16");
6172 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006173
6174 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6175 if (!Attr)
6176 return;
6177
6178 const char *Kind;
6179 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006180 case MipsInterruptAttr::eic: Kind = "eic"; break;
6181 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6182 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6183 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6184 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6185 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6186 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6187 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6188 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6189 }
6190
6191 Fn->addFnAttr("interrupt", Kind);
6192
Reed Kotler373feca2013-01-16 17:10:28 +00006193 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006194
John McCall943fae92010-05-27 06:19:26 +00006195 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006196 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006197
Craig Topper4f12f102014-03-12 06:41:41 +00006198 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006199 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006200 }
John McCall943fae92010-05-27 06:19:26 +00006201};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006202}
John McCall943fae92010-05-27 06:19:26 +00006203
Eric Christopher7565e0d2015-05-29 23:09:49 +00006204void MipsABIInfo::CoerceToIntArgs(
6205 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006206 llvm::IntegerType *IntTy =
6207 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006208
6209 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6210 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6211 ArgList.push_back(IntTy);
6212
6213 // If necessary, add one more integer type to ArgList.
6214 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6215
6216 if (R)
6217 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006218}
6219
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006220// In N32/64, an aligned double precision floating point field is passed in
6221// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006222llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006223 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6224
6225 if (IsO32) {
6226 CoerceToIntArgs(TySize, ArgList);
6227 return llvm::StructType::get(getVMContext(), ArgList);
6228 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006229
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006230 if (Ty->isComplexType())
6231 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006232
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006233 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006234
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006235 // Unions/vectors are passed in integer registers.
6236 if (!RT || !RT->isStructureOrClassType()) {
6237 CoerceToIntArgs(TySize, ArgList);
6238 return llvm::StructType::get(getVMContext(), ArgList);
6239 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006240
6241 const RecordDecl *RD = RT->getDecl();
6242 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006243 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006244
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006245 uint64_t LastOffset = 0;
6246 unsigned idx = 0;
6247 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6248
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006249 // Iterate over fields in the struct/class and check if there are any aligned
6250 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006251 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6252 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006253 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006254 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6255
6256 if (!BT || BT->getKind() != BuiltinType::Double)
6257 continue;
6258
6259 uint64_t Offset = Layout.getFieldOffset(idx);
6260 if (Offset % 64) // Ignore doubles that are not aligned.
6261 continue;
6262
6263 // Add ((Offset - LastOffset) / 64) args of type i64.
6264 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6265 ArgList.push_back(I64);
6266
6267 // Add double type.
6268 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6269 LastOffset = Offset + 64;
6270 }
6271
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006272 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6273 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006274
6275 return llvm::StructType::get(getVMContext(), ArgList);
6276}
6277
Akira Hatanakaddd66342013-10-29 18:41:15 +00006278llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6279 uint64_t Offset) const {
6280 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006281 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006282
Akira Hatanakaddd66342013-10-29 18:41:15 +00006283 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006284}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006285
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006286ABIArgInfo
6287MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006288 Ty = useFirstFieldIfTransparentUnion(Ty);
6289
Akira Hatanaka1632af62012-01-09 19:31:25 +00006290 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006291 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006292 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006293
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006294 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6295 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006296 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6297 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006298
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006299 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006300 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006301 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006302 return ABIArgInfo::getIgnore();
6303
Mark Lacey3825e832013-10-06 01:33:34 +00006304 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006305 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006306 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006307 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006308
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006309 // If we have reached here, aggregates are passed directly by coercing to
6310 // another structure type. Padding is inserted if the offset of the
6311 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006312 ABIArgInfo ArgInfo =
6313 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6314 getPaddingType(OrigOffset, CurrOffset));
6315 ArgInfo.setInReg(true);
6316 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006317 }
6318
6319 // Treat an enum type as its underlying type.
6320 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6321 Ty = EnumTy->getDecl()->getIntegerType();
6322
Daniel Sanders5b445b32014-10-24 14:42:42 +00006323 // All integral types are promoted to the GPR width.
6324 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006325 return ABIArgInfo::getExtend();
6326
Akira Hatanakaddd66342013-10-29 18:41:15 +00006327 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006328 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006329}
6330
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006331llvm::Type*
6332MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006333 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006334 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006335
Akira Hatanakab6f74432012-02-09 18:49:26 +00006336 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006337 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006338 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6339 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006340
Akira Hatanakab6f74432012-02-09 18:49:26 +00006341 // N32/64 returns struct/classes in floating point registers if the
6342 // following conditions are met:
6343 // 1. The size of the struct/class is no larger than 128-bit.
6344 // 2. The struct/class has one or two fields all of which are floating
6345 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006346 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006347 //
6348 // Any other composite results are returned in integer registers.
6349 //
6350 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6351 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6352 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006353 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006354
Akira Hatanakab6f74432012-02-09 18:49:26 +00006355 if (!BT || !BT->isFloatingPoint())
6356 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006357
David Blaikie2d7c57e2012-04-30 02:36:29 +00006358 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006359 }
6360
6361 if (b == e)
6362 return llvm::StructType::get(getVMContext(), RTList,
6363 RD->hasAttr<PackedAttr>());
6364
6365 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006366 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006367 }
6368
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006369 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006370 return llvm::StructType::get(getVMContext(), RTList);
6371}
6372
Akira Hatanakab579fe52011-06-02 00:09:17 +00006373ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006374 uint64_t Size = getContext().getTypeSize(RetTy);
6375
Daniel Sandersed39f582014-09-04 13:28:14 +00006376 if (RetTy->isVoidType())
6377 return ABIArgInfo::getIgnore();
6378
6379 // O32 doesn't treat zero-sized structs differently from other structs.
6380 // However, N32/N64 ignores zero sized return values.
6381 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006382 return ABIArgInfo::getIgnore();
6383
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006384 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006385 if (Size <= 128) {
6386 if (RetTy->isAnyComplexType())
6387 return ABIArgInfo::getDirect();
6388
Daniel Sanderse5018b62014-09-04 15:05:39 +00006389 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006390 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006391 if (!IsO32 ||
6392 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6393 ABIArgInfo ArgInfo =
6394 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6395 ArgInfo.setInReg(true);
6396 return ArgInfo;
6397 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006398 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006399
John McCall7f416cc2015-09-08 08:05:57 +00006400 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006401 }
6402
6403 // Treat an enum type as its underlying type.
6404 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6405 RetTy = EnumTy->getDecl()->getIntegerType();
6406
6407 return (RetTy->isPromotableIntegerType() ?
6408 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6409}
6410
6411void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006412 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006413 if (!getCXXABI().classifyReturnType(FI))
6414 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006415
Eric Christopher7565e0d2015-05-29 23:09:49 +00006416 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006417 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006418
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006419 for (auto &I : FI.arguments())
6420 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006421}
6422
John McCall7f416cc2015-09-08 08:05:57 +00006423Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6424 QualType OrigTy) const {
6425 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006426
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006427 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6428 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006429 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006430 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006431 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006432 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006433 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006434 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006435 DidPromote = true;
6436 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6437 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006438 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006439
John McCall7f416cc2015-09-08 08:05:57 +00006440 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006441
John McCall7f416cc2015-09-08 08:05:57 +00006442 // The alignment of things in the argument area is never larger than
6443 // StackAlignInBytes.
6444 TyInfo.second =
6445 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6446
6447 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6448 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6449
6450 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6451 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6452
6453
6454 // If there was a promotion, "unpromote" into a temporary.
6455 // TODO: can we just use a pointer into a subset of the original slot?
6456 if (DidPromote) {
6457 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6458 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6459
6460 // Truncate down to the right width.
6461 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6462 : CGF.IntPtrTy);
6463 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6464 if (OrigTy->isPointerType())
6465 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6466
6467 CGF.Builder.CreateStore(V, Temp);
6468 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006469 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006470
John McCall7f416cc2015-09-08 08:05:57 +00006471 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006472}
6473
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006474bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6475 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006476
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006477 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6478 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6479 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006480
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006481 return false;
6482}
6483
John McCall943fae92010-05-27 06:19:26 +00006484bool
6485MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6486 llvm::Value *Address) const {
6487 // This information comes from gcc's implementation, which seems to
6488 // as canonical as it gets.
6489
John McCall943fae92010-05-27 06:19:26 +00006490 // Everything on MIPS is 4 bytes. Double-precision FP registers
6491 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006492 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006493
6494 // 0-31 are the general purpose registers, $0 - $31.
6495 // 32-63 are the floating-point registers, $f0 - $f31.
6496 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6497 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006498 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006499
6500 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6501 // They are one bit wide and ignored here.
6502
6503 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6504 // (coprocessor 1 is the FP unit)
6505 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6506 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6507 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006508 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006509 return false;
6510}
6511
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006512//===----------------------------------------------------------------------===//
6513// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006514// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006515// handling.
6516//===----------------------------------------------------------------------===//
6517
6518namespace {
6519
6520class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6521public:
6522 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6523 : DefaultTargetCodeGenInfo(CGT) {}
6524
Eric Christopher162c91c2015-06-05 22:03:00 +00006525 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006526 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006527};
6528
Eric Christopher162c91c2015-06-05 22:03:00 +00006529void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006530 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006531 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006532 if (!FD) return;
6533
6534 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006535
David Blaikiebbafb8a2012-03-11 07:00:24 +00006536 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006537 if (FD->hasAttr<OpenCLKernelAttr>()) {
6538 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006539 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006540 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6541 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006542 // Convert the reqd_work_group_size() attributes to metadata.
6543 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006544 llvm::NamedMDNode *OpenCLMetadata =
6545 M.getModule().getOrInsertNamedMetadata(
6546 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006547
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006548 SmallVector<llvm::Metadata *, 5> Operands;
6549 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006550
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006551 Operands.push_back(
6552 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6553 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6554 Operands.push_back(
6555 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6556 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6557 Operands.push_back(
6558 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6559 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006560
Eric Christopher7565e0d2015-05-29 23:09:49 +00006561 // Add a boolean constant operand for "required" (true) or "hint"
6562 // (false) for implementing the work_group_size_hint attr later.
6563 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006564 Operands.push_back(
6565 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006566 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6567 }
6568 }
6569 }
6570}
6571
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006572}
John McCall943fae92010-05-27 06:19:26 +00006573
Tony Linthicum76329bf2011-12-12 21:14:55 +00006574//===----------------------------------------------------------------------===//
6575// Hexagon ABI Implementation
6576//===----------------------------------------------------------------------===//
6577
6578namespace {
6579
6580class HexagonABIInfo : public ABIInfo {
6581
6582
6583public:
6584 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6585
6586private:
6587
6588 ABIArgInfo classifyReturnType(QualType RetTy) const;
6589 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6590
Craig Topper4f12f102014-03-12 06:41:41 +00006591 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006592
John McCall7f416cc2015-09-08 08:05:57 +00006593 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6594 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006595};
6596
6597class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6598public:
6599 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6600 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6601
Craig Topper4f12f102014-03-12 06:41:41 +00006602 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006603 return 29;
6604 }
6605};
6606
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006607}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006608
6609void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006610 if (!getCXXABI().classifyReturnType(FI))
6611 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006612 for (auto &I : FI.arguments())
6613 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006614}
6615
6616ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6617 if (!isAggregateTypeForABI(Ty)) {
6618 // Treat an enum type as its underlying type.
6619 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6620 Ty = EnumTy->getDecl()->getIntegerType();
6621
6622 return (Ty->isPromotableIntegerType() ?
6623 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6624 }
6625
6626 // Ignore empty records.
6627 if (isEmptyRecord(getContext(), Ty, true))
6628 return ABIArgInfo::getIgnore();
6629
Mark Lacey3825e832013-10-06 01:33:34 +00006630 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006631 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006632
6633 uint64_t Size = getContext().getTypeSize(Ty);
6634 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006635 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006636 // Pass in the smallest viable integer type.
6637 else if (Size > 32)
6638 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6639 else if (Size > 16)
6640 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6641 else if (Size > 8)
6642 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6643 else
6644 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6645}
6646
6647ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6648 if (RetTy->isVoidType())
6649 return ABIArgInfo::getIgnore();
6650
6651 // Large vector types should be returned via memory.
6652 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006653 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006654
6655 if (!isAggregateTypeForABI(RetTy)) {
6656 // Treat an enum type as its underlying type.
6657 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6658 RetTy = EnumTy->getDecl()->getIntegerType();
6659
6660 return (RetTy->isPromotableIntegerType() ?
6661 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6662 }
6663
Tony Linthicum76329bf2011-12-12 21:14:55 +00006664 if (isEmptyRecord(getContext(), RetTy, true))
6665 return ABIArgInfo::getIgnore();
6666
6667 // Aggregates <= 8 bytes are returned in r0; other aggregates
6668 // are returned indirectly.
6669 uint64_t Size = getContext().getTypeSize(RetTy);
6670 if (Size <= 64) {
6671 // Return in the smallest viable integer type.
6672 if (Size <= 8)
6673 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6674 if (Size <= 16)
6675 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6676 if (Size <= 32)
6677 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6678 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6679 }
6680
John McCall7f416cc2015-09-08 08:05:57 +00006681 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006682}
6683
John McCall7f416cc2015-09-08 08:05:57 +00006684Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6685 QualType Ty) const {
6686 // FIXME: Someone needs to audit that this handle alignment correctly.
6687 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6688 getContext().getTypeInfoInChars(Ty),
6689 CharUnits::fromQuantity(4),
6690 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006691}
6692
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006693//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006694// Lanai ABI Implementation
6695//===----------------------------------------------------------------------===//
6696
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006697namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006698class LanaiABIInfo : public DefaultABIInfo {
6699public:
6700 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6701
6702 bool shouldUseInReg(QualType Ty, CCState &State) const;
6703
6704 void computeInfo(CGFunctionInfo &FI) const override {
6705 CCState State(FI.getCallingConvention());
6706 // Lanai uses 4 registers to pass arguments unless the function has the
6707 // regparm attribute set.
6708 if (FI.getHasRegParm()) {
6709 State.FreeRegs = FI.getRegParm();
6710 } else {
6711 State.FreeRegs = 4;
6712 }
6713
6714 if (!getCXXABI().classifyReturnType(FI))
6715 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6716 for (auto &I : FI.arguments())
6717 I.info = classifyArgumentType(I.type, State);
6718 }
6719
Jacques Pienaare74d9132016-04-26 00:09:29 +00006720 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006721 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6722};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006723} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006724
6725bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6726 unsigned Size = getContext().getTypeSize(Ty);
6727 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6728
6729 if (SizeInRegs == 0)
6730 return false;
6731
6732 if (SizeInRegs > State.FreeRegs) {
6733 State.FreeRegs = 0;
6734 return false;
6735 }
6736
6737 State.FreeRegs -= SizeInRegs;
6738
6739 return true;
6740}
6741
Jacques Pienaare74d9132016-04-26 00:09:29 +00006742ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6743 CCState &State) const {
6744 if (!ByVal) {
6745 if (State.FreeRegs) {
6746 --State.FreeRegs; // Non-byval indirects just use one pointer.
6747 return getNaturalAlignIndirectInReg(Ty);
6748 }
6749 return getNaturalAlignIndirect(Ty, false);
6750 }
6751
6752 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006753 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006754 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6755 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6756 /*Realign=*/TypeAlign >
6757 MinABIStackAlignInBytes);
6758}
6759
Jacques Pienaard964cc22016-03-28 21:02:54 +00006760ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6761 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006762 // Check with the C++ ABI first.
6763 const RecordType *RT = Ty->getAs<RecordType>();
6764 if (RT) {
6765 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6766 if (RAA == CGCXXABI::RAA_Indirect) {
6767 return getIndirectResult(Ty, /*ByVal=*/false, State);
6768 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6769 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6770 }
6771 }
6772
6773 if (isAggregateTypeForABI(Ty)) {
6774 // Structures with flexible arrays are always indirect.
6775 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6776 return getIndirectResult(Ty, /*ByVal=*/true, State);
6777
6778 // Ignore empty structs/unions.
6779 if (isEmptyRecord(getContext(), Ty, true))
6780 return ABIArgInfo::getIgnore();
6781
6782 llvm::LLVMContext &LLVMContext = getVMContext();
6783 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6784 if (SizeInRegs <= State.FreeRegs) {
6785 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6786 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6787 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6788 State.FreeRegs -= SizeInRegs;
6789 return ABIArgInfo::getDirectInReg(Result);
6790 } else {
6791 State.FreeRegs = 0;
6792 }
6793 return getIndirectResult(Ty, true, State);
6794 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006795
6796 // Treat an enum type as its underlying type.
6797 if (const auto *EnumTy = Ty->getAs<EnumType>())
6798 Ty = EnumTy->getDecl()->getIntegerType();
6799
Jacques Pienaare74d9132016-04-26 00:09:29 +00006800 bool InReg = shouldUseInReg(Ty, State);
6801 if (Ty->isPromotableIntegerType()) {
6802 if (InReg)
6803 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006804 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006805 }
6806 if (InReg)
6807 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006808 return ABIArgInfo::getDirect();
6809}
6810
6811namespace {
6812class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6813public:
6814 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6815 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6816};
6817}
6818
6819//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006820// AMDGPU ABI Implementation
6821//===----------------------------------------------------------------------===//
6822
6823namespace {
6824
6825class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6826public:
6827 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6828 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006829 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006830 CodeGen::CodeGenModule &M) const override;
6831};
6832
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006833}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006834
Eric Christopher162c91c2015-06-05 22:03:00 +00006835void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006836 const Decl *D,
6837 llvm::GlobalValue *GV,
6838 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006839 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006840 if (!FD)
6841 return;
6842
6843 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6844 llvm::Function *F = cast<llvm::Function>(GV);
6845 uint32_t NumVGPR = Attr->getNumVGPR();
6846 if (NumVGPR != 0)
6847 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6848 }
6849
6850 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6851 llvm::Function *F = cast<llvm::Function>(GV);
6852 unsigned NumSGPR = Attr->getNumSGPR();
6853 if (NumSGPR != 0)
6854 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6855 }
6856}
6857
Tony Linthicum76329bf2011-12-12 21:14:55 +00006858
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006859//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00006860// SPARC v8 ABI Implementation.
6861// Based on the SPARC Compliance Definition version 2.4.1.
6862//
6863// Ensures that complex values are passed in registers.
6864//
6865namespace {
6866class SparcV8ABIInfo : public DefaultABIInfo {
6867public:
6868 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6869
6870private:
6871 ABIArgInfo classifyReturnType(QualType RetTy) const;
6872 void computeInfo(CGFunctionInfo &FI) const override;
6873};
6874} // end anonymous namespace
6875
6876
6877ABIArgInfo
6878SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
6879 if (Ty->isAnyComplexType()) {
6880 return ABIArgInfo::getDirect();
6881 }
6882 else {
6883 return DefaultABIInfo::classifyReturnType(Ty);
6884 }
6885}
6886
6887void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6888
6889 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6890 for (auto &Arg : FI.arguments())
6891 Arg.info = classifyArgumentType(Arg.type);
6892}
6893
6894namespace {
6895class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
6896public:
6897 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
6898 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
6899};
6900} // end anonymous namespace
6901
6902//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006903// SPARC v9 ABI Implementation.
6904// Based on the SPARC Compliance Definition version 2.4.1.
6905//
6906// Function arguments a mapped to a nominal "parameter array" and promoted to
6907// registers depending on their type. Each argument occupies 8 or 16 bytes in
6908// the array, structs larger than 16 bytes are passed indirectly.
6909//
6910// One case requires special care:
6911//
6912// struct mixed {
6913// int i;
6914// float f;
6915// };
6916//
6917// When a struct mixed is passed by value, it only occupies 8 bytes in the
6918// parameter array, but the int is passed in an integer register, and the float
6919// is passed in a floating point register. This is represented as two arguments
6920// with the LLVM IR inreg attribute:
6921//
6922// declare void f(i32 inreg %i, float inreg %f)
6923//
6924// The code generator will only allocate 4 bytes from the parameter array for
6925// the inreg arguments. All other arguments are allocated a multiple of 8
6926// bytes.
6927//
6928namespace {
6929class SparcV9ABIInfo : public ABIInfo {
6930public:
6931 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6932
6933private:
6934 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006935 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006936 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6937 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006938
6939 // Coercion type builder for structs passed in registers. The coercion type
6940 // serves two purposes:
6941 //
6942 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6943 // in registers.
6944 // 2. Expose aligned floating point elements as first-level elements, so the
6945 // code generator knows to pass them in floating point registers.
6946 //
6947 // We also compute the InReg flag which indicates that the struct contains
6948 // aligned 32-bit floats.
6949 //
6950 struct CoerceBuilder {
6951 llvm::LLVMContext &Context;
6952 const llvm::DataLayout &DL;
6953 SmallVector<llvm::Type*, 8> Elems;
6954 uint64_t Size;
6955 bool InReg;
6956
6957 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6958 : Context(c), DL(dl), Size(0), InReg(false) {}
6959
6960 // Pad Elems with integers until Size is ToSize.
6961 void pad(uint64_t ToSize) {
6962 assert(ToSize >= Size && "Cannot remove elements");
6963 if (ToSize == Size)
6964 return;
6965
6966 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006967 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006968 if (Aligned > Size && Aligned <= ToSize) {
6969 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6970 Size = Aligned;
6971 }
6972
6973 // Add whole 64-bit words.
6974 while (Size + 64 <= ToSize) {
6975 Elems.push_back(llvm::Type::getInt64Ty(Context));
6976 Size += 64;
6977 }
6978
6979 // Final in-word padding.
6980 if (Size < ToSize) {
6981 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6982 Size = ToSize;
6983 }
6984 }
6985
6986 // Add a floating point element at Offset.
6987 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6988 // Unaligned floats are treated as integers.
6989 if (Offset % Bits)
6990 return;
6991 // The InReg flag is only required if there are any floats < 64 bits.
6992 if (Bits < 64)
6993 InReg = true;
6994 pad(Offset);
6995 Elems.push_back(Ty);
6996 Size = Offset + Bits;
6997 }
6998
6999 // Add a struct type to the coercion type, starting at Offset (in bits).
7000 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7001 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7002 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7003 llvm::Type *ElemTy = StrTy->getElementType(i);
7004 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7005 switch (ElemTy->getTypeID()) {
7006 case llvm::Type::StructTyID:
7007 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7008 break;
7009 case llvm::Type::FloatTyID:
7010 addFloat(ElemOffset, ElemTy, 32);
7011 break;
7012 case llvm::Type::DoubleTyID:
7013 addFloat(ElemOffset, ElemTy, 64);
7014 break;
7015 case llvm::Type::FP128TyID:
7016 addFloat(ElemOffset, ElemTy, 128);
7017 break;
7018 case llvm::Type::PointerTyID:
7019 if (ElemOffset % 64 == 0) {
7020 pad(ElemOffset);
7021 Elems.push_back(ElemTy);
7022 Size += 64;
7023 }
7024 break;
7025 default:
7026 break;
7027 }
7028 }
7029 }
7030
7031 // Check if Ty is a usable substitute for the coercion type.
7032 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007033 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007034 }
7035
7036 // Get the coercion type as a literal struct type.
7037 llvm::Type *getType() const {
7038 if (Elems.size() == 1)
7039 return Elems.front();
7040 else
7041 return llvm::StructType::get(Context, Elems);
7042 }
7043 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007044};
7045} // end anonymous namespace
7046
7047ABIArgInfo
7048SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7049 if (Ty->isVoidType())
7050 return ABIArgInfo::getIgnore();
7051
7052 uint64_t Size = getContext().getTypeSize(Ty);
7053
7054 // Anything too big to fit in registers is passed with an explicit indirect
7055 // pointer / sret pointer.
7056 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007057 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007058
7059 // Treat an enum type as its underlying type.
7060 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7061 Ty = EnumTy->getDecl()->getIntegerType();
7062
7063 // Integer types smaller than a register are extended.
7064 if (Size < 64 && Ty->isIntegerType())
7065 return ABIArgInfo::getExtend();
7066
7067 // Other non-aggregates go in registers.
7068 if (!isAggregateTypeForABI(Ty))
7069 return ABIArgInfo::getDirect();
7070
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007071 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7072 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7073 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007074 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007075
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007076 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007077 // Build a coercion type from the LLVM struct type.
7078 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7079 if (!StrTy)
7080 return ABIArgInfo::getDirect();
7081
7082 CoerceBuilder CB(getVMContext(), getDataLayout());
7083 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007084 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007085
7086 // Try to use the original type for coercion.
7087 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7088
7089 if (CB.InReg)
7090 return ABIArgInfo::getDirectInReg(CoerceTy);
7091 else
7092 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007093}
7094
John McCall7f416cc2015-09-08 08:05:57 +00007095Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7096 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007097 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7098 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7099 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7100 AI.setCoerceToType(ArgTy);
7101
John McCall7f416cc2015-09-08 08:05:57 +00007102 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007103
John McCall7f416cc2015-09-08 08:05:57 +00007104 CGBuilderTy &Builder = CGF.Builder;
7105 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7106 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7107
7108 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7109
7110 Address ArgAddr = Address::invalid();
7111 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007112 switch (AI.getKind()) {
7113 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007114 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007115 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007116 llvm_unreachable("Unsupported ABI kind for va_arg");
7117
John McCall7f416cc2015-09-08 08:05:57 +00007118 case ABIArgInfo::Extend: {
7119 Stride = SlotSize;
7120 CharUnits Offset = SlotSize - TypeInfo.first;
7121 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007122 break;
John McCall7f416cc2015-09-08 08:05:57 +00007123 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007124
John McCall7f416cc2015-09-08 08:05:57 +00007125 case ABIArgInfo::Direct: {
7126 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007127 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007128 ArgAddr = Addr;
7129 break;
John McCall7f416cc2015-09-08 08:05:57 +00007130 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007131
7132 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007133 Stride = SlotSize;
7134 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7135 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7136 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007137 break;
7138
7139 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007140 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007141 }
7142
7143 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007144 llvm::Value *NextPtr =
7145 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7146 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007147
John McCall7f416cc2015-09-08 08:05:57 +00007148 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007149}
7150
7151void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7152 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007153 for (auto &I : FI.arguments())
7154 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007155}
7156
7157namespace {
7158class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7159public:
7160 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7161 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007162
Craig Topper4f12f102014-03-12 06:41:41 +00007163 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007164 return 14;
7165 }
7166
7167 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007168 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007169};
7170} // end anonymous namespace
7171
Roman Divackyf02c9942014-02-24 18:46:27 +00007172bool
7173SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7174 llvm::Value *Address) const {
7175 // This is calculated from the LLVM and GCC tables and verified
7176 // against gcc output. AFAIK all ABIs use the same encoding.
7177
7178 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7179
7180 llvm::IntegerType *i8 = CGF.Int8Ty;
7181 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7182 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7183
7184 // 0-31: the 8-byte general-purpose registers
7185 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7186
7187 // 32-63: f0-31, the 4-byte floating-point registers
7188 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7189
7190 // Y = 64
7191 // PSR = 65
7192 // WIM = 66
7193 // TBR = 67
7194 // PC = 68
7195 // NPC = 69
7196 // FSR = 70
7197 // CSR = 71
7198 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007199
Roman Divackyf02c9942014-02-24 18:46:27 +00007200 // 72-87: d0-15, the 8-byte floating-point registers
7201 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7202
7203 return false;
7204}
7205
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007206
Robert Lytton0e076492013-08-13 09:43:10 +00007207//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007208// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007209//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007210
Robert Lytton0e076492013-08-13 09:43:10 +00007211namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007212
7213/// A SmallStringEnc instance is used to build up the TypeString by passing
7214/// it by reference between functions that append to it.
7215typedef llvm::SmallString<128> SmallStringEnc;
7216
7217/// TypeStringCache caches the meta encodings of Types.
7218///
7219/// The reason for caching TypeStrings is two fold:
7220/// 1. To cache a type's encoding for later uses;
7221/// 2. As a means to break recursive member type inclusion.
7222///
7223/// A cache Entry can have a Status of:
7224/// NonRecursive: The type encoding is not recursive;
7225/// Recursive: The type encoding is recursive;
7226/// Incomplete: An incomplete TypeString;
7227/// IncompleteUsed: An incomplete TypeString that has been used in a
7228/// Recursive type encoding.
7229///
7230/// A NonRecursive entry will have all of its sub-members expanded as fully
7231/// as possible. Whilst it may contain types which are recursive, the type
7232/// itself is not recursive and thus its encoding may be safely used whenever
7233/// the type is encountered.
7234///
7235/// A Recursive entry will have all of its sub-members expanded as fully as
7236/// possible. The type itself is recursive and it may contain other types which
7237/// are recursive. The Recursive encoding must not be used during the expansion
7238/// of a recursive type's recursive branch. For simplicity the code uses
7239/// IncompleteCount to reject all usage of Recursive encodings for member types.
7240///
7241/// An Incomplete entry is always a RecordType and only encodes its
7242/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7243/// are placed into the cache during type expansion as a means to identify and
7244/// handle recursive inclusion of types as sub-members. If there is recursion
7245/// the entry becomes IncompleteUsed.
7246///
7247/// During the expansion of a RecordType's members:
7248///
7249/// If the cache contains a NonRecursive encoding for the member type, the
7250/// cached encoding is used;
7251///
7252/// If the cache contains a Recursive encoding for the member type, the
7253/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7254///
7255/// If the member is a RecordType, an Incomplete encoding is placed into the
7256/// cache to break potential recursive inclusion of itself as a sub-member;
7257///
7258/// Once a member RecordType has been expanded, its temporary incomplete
7259/// entry is removed from the cache. If a Recursive encoding was swapped out
7260/// it is swapped back in;
7261///
7262/// If an incomplete entry is used to expand a sub-member, the incomplete
7263/// entry is marked as IncompleteUsed. The cache keeps count of how many
7264/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7265///
7266/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7267/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7268/// Else the member is part of a recursive type and thus the recursion has
7269/// been exited too soon for the encoding to be correct for the member.
7270///
7271class TypeStringCache {
7272 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7273 struct Entry {
7274 std::string Str; // The encoded TypeString for the type.
7275 enum Status State; // Information about the encoding in 'Str'.
7276 std::string Swapped; // A temporary place holder for a Recursive encoding
7277 // during the expansion of RecordType's members.
7278 };
7279 std::map<const IdentifierInfo *, struct Entry> Map;
7280 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7281 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7282public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007283 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007284 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7285 bool removeIncomplete(const IdentifierInfo *ID);
7286 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7287 bool IsRecursive);
7288 StringRef lookupStr(const IdentifierInfo *ID);
7289};
7290
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007291/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007292/// FieldEncoding is a helper for this ordering process.
7293class FieldEncoding {
7294 bool HasName;
7295 std::string Enc;
7296public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007297 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7298 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007299 bool operator<(const FieldEncoding &rhs) const {
7300 if (HasName != rhs.HasName) return HasName;
7301 return Enc < rhs.Enc;
7302 }
7303};
7304
Robert Lytton7d1db152013-08-19 09:46:39 +00007305class XCoreABIInfo : public DefaultABIInfo {
7306public:
7307 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007308 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7309 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007310};
7311
Robert Lyttond21e2d72014-03-03 13:45:29 +00007312class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007313 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007314public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007315 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007316 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007317 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7318 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007319};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007320
Robert Lytton2d196952013-10-11 10:29:34 +00007321} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007322
James Y Knight29b5f082016-02-24 02:59:33 +00007323// TODO: this implementation is likely now redundant with the default
7324// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007325Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7326 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007327 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007328
Robert Lytton2d196952013-10-11 10:29:34 +00007329 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007330 CharUnits SlotSize = CharUnits::fromQuantity(4);
7331 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007332
Robert Lytton2d196952013-10-11 10:29:34 +00007333 // Handle the argument.
7334 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007335 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007336 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7337 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7338 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007339 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007340
7341 Address Val = Address::invalid();
7342 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007343 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007344 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007345 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007346 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007347 llvm_unreachable("Unsupported ABI kind for va_arg");
7348 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007349 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7350 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007351 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007352 case ABIArgInfo::Extend:
7353 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007354 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7355 ArgSize = CharUnits::fromQuantity(
7356 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007357 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007358 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007359 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007360 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7361 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7362 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007363 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007364 }
Robert Lytton2d196952013-10-11 10:29:34 +00007365
7366 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007367 if (!ArgSize.isZero()) {
7368 llvm::Value *APN =
7369 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7370 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007371 }
John McCall7f416cc2015-09-08 08:05:57 +00007372
Robert Lytton2d196952013-10-11 10:29:34 +00007373 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007374}
Robert Lytton0e076492013-08-13 09:43:10 +00007375
Robert Lytton844aeeb2014-05-02 09:33:20 +00007376/// During the expansion of a RecordType, an incomplete TypeString is placed
7377/// into the cache as a means to identify and break recursion.
7378/// If there is a Recursive encoding in the cache, it is swapped out and will
7379/// be reinserted by removeIncomplete().
7380/// All other types of encoding should have been used rather than arriving here.
7381void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7382 std::string StubEnc) {
7383 if (!ID)
7384 return;
7385 Entry &E = Map[ID];
7386 assert( (E.Str.empty() || E.State == Recursive) &&
7387 "Incorrectly use of addIncomplete");
7388 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7389 E.Swapped.swap(E.Str); // swap out the Recursive
7390 E.Str.swap(StubEnc);
7391 E.State = Incomplete;
7392 ++IncompleteCount;
7393}
7394
7395/// Once the RecordType has been expanded, the temporary incomplete TypeString
7396/// must be removed from the cache.
7397/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7398/// Returns true if the RecordType was defined recursively.
7399bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7400 if (!ID)
7401 return false;
7402 auto I = Map.find(ID);
7403 assert(I != Map.end() && "Entry not present");
7404 Entry &E = I->second;
7405 assert( (E.State == Incomplete ||
7406 E.State == IncompleteUsed) &&
7407 "Entry must be an incomplete type");
7408 bool IsRecursive = false;
7409 if (E.State == IncompleteUsed) {
7410 // We made use of our Incomplete encoding, thus we are recursive.
7411 IsRecursive = true;
7412 --IncompleteUsedCount;
7413 }
7414 if (E.Swapped.empty())
7415 Map.erase(I);
7416 else {
7417 // Swap the Recursive back.
7418 E.Swapped.swap(E.Str);
7419 E.Swapped.clear();
7420 E.State = Recursive;
7421 }
7422 --IncompleteCount;
7423 return IsRecursive;
7424}
7425
7426/// Add the encoded TypeString to the cache only if it is NonRecursive or
7427/// Recursive (viz: all sub-members were expanded as fully as possible).
7428void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7429 bool IsRecursive) {
7430 if (!ID || IncompleteUsedCount)
7431 return; // No key or it is is an incomplete sub-type so don't add.
7432 Entry &E = Map[ID];
7433 if (IsRecursive && !E.Str.empty()) {
7434 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7435 "This is not the same Recursive entry");
7436 // The parent container was not recursive after all, so we could have used
7437 // this Recursive sub-member entry after all, but we assumed the worse when
7438 // we started viz: IncompleteCount!=0.
7439 return;
7440 }
7441 assert(E.Str.empty() && "Entry already present");
7442 E.Str = Str.str();
7443 E.State = IsRecursive? Recursive : NonRecursive;
7444}
7445
7446/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7447/// are recursively expanding a type (IncompleteCount != 0) and the cached
7448/// encoding is Recursive, return an empty StringRef.
7449StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7450 if (!ID)
7451 return StringRef(); // We have no key.
7452 auto I = Map.find(ID);
7453 if (I == Map.end())
7454 return StringRef(); // We have no encoding.
7455 Entry &E = I->second;
7456 if (E.State == Recursive && IncompleteCount)
7457 return StringRef(); // We don't use Recursive encodings for member types.
7458
7459 if (E.State == Incomplete) {
7460 // The incomplete type is being used to break out of recursion.
7461 E.State = IncompleteUsed;
7462 ++IncompleteUsedCount;
7463 }
7464 return E.Str.c_str();
7465}
7466
7467/// The XCore ABI includes a type information section that communicates symbol
7468/// type information to the linker. The linker uses this information to verify
7469/// safety/correctness of things such as array bound and pointers et al.
7470/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7471/// This type information (TypeString) is emitted into meta data for all global
7472/// symbols: definitions, declarations, functions & variables.
7473///
7474/// The TypeString carries type, qualifier, name, size & value details.
7475/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007476/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007477/// The output is tested by test/CodeGen/xcore-stringtype.c.
7478///
7479static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7480 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7481
7482/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7483void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7484 CodeGen::CodeGenModule &CGM) const {
7485 SmallStringEnc Enc;
7486 if (getTypeString(Enc, D, CGM, TSC)) {
7487 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007488 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7489 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007490 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7491 llvm::NamedMDNode *MD =
7492 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7493 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7494 }
7495}
7496
Xiuli Pan972bea82016-03-24 03:57:17 +00007497//===----------------------------------------------------------------------===//
7498// SPIR ABI Implementation
7499//===----------------------------------------------------------------------===//
7500
7501namespace {
7502class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7503public:
7504 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7505 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7506 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7507 CodeGen::CodeGenModule &M) const override;
7508};
7509} // End anonymous namespace.
7510
7511/// Emit SPIR specific metadata: OpenCL and SPIR version.
7512void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7513 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007514 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7515 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7516 llvm::Module &M = CGM.getModule();
7517 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7518 // opencl.spir.version named metadata.
7519 llvm::Metadata *SPIRVerElts[] = {
7520 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7521 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7522 llvm::NamedMDNode *SPIRVerMD =
7523 M.getOrInsertNamedMetadata("opencl.spir.version");
7524 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7525 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7526 // opencl.ocl.version named metadata node.
7527 llvm::Metadata *OCLVerElts[] = {
7528 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7529 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7530 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7531 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7532 llvm::NamedMDNode *OCLVerMD =
7533 M.getOrInsertNamedMetadata("opencl.ocl.version");
7534 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7535}
7536
Robert Lytton844aeeb2014-05-02 09:33:20 +00007537static bool appendType(SmallStringEnc &Enc, QualType QType,
7538 const CodeGen::CodeGenModule &CGM,
7539 TypeStringCache &TSC);
7540
7541/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007542/// Builds a SmallVector containing the encoded field types in declaration
7543/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007544static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7545 const RecordDecl *RD,
7546 const CodeGen::CodeGenModule &CGM,
7547 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007548 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007549 SmallStringEnc Enc;
7550 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007551 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007552 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007553 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007554 Enc += "b(";
7555 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007556 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007557 Enc += ':';
7558 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007559 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007560 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007561 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007562 Enc += ')';
7563 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007564 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007565 }
7566 return true;
7567}
7568
7569/// Appends structure and union types to Enc and adds encoding to cache.
7570/// Recursively calls appendType (via extractFieldType) for each field.
7571/// Union types have their fields ordered according to the ABI.
7572static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7573 const CodeGen::CodeGenModule &CGM,
7574 TypeStringCache &TSC, const IdentifierInfo *ID) {
7575 // Append the cached TypeString if we have one.
7576 StringRef TypeString = TSC.lookupStr(ID);
7577 if (!TypeString.empty()) {
7578 Enc += TypeString;
7579 return true;
7580 }
7581
7582 // Start to emit an incomplete TypeString.
7583 size_t Start = Enc.size();
7584 Enc += (RT->isUnionType()? 'u' : 's');
7585 Enc += '(';
7586 if (ID)
7587 Enc += ID->getName();
7588 Enc += "){";
7589
7590 // We collect all encoded fields and order as necessary.
7591 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007592 const RecordDecl *RD = RT->getDecl()->getDefinition();
7593 if (RD && !RD->field_empty()) {
7594 // An incomplete TypeString stub is placed in the cache for this RecordType
7595 // so that recursive calls to this RecordType will use it whilst building a
7596 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007597 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007598 std::string StubEnc(Enc.substr(Start).str());
7599 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7600 TSC.addIncomplete(ID, std::move(StubEnc));
7601 if (!extractFieldType(FE, RD, CGM, TSC)) {
7602 (void) TSC.removeIncomplete(ID);
7603 return false;
7604 }
7605 IsRecursive = TSC.removeIncomplete(ID);
7606 // The ABI requires unions to be sorted but not structures.
7607 // See FieldEncoding::operator< for sort algorithm.
7608 if (RT->isUnionType())
7609 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007610 // We can now complete the TypeString.
7611 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007612 for (unsigned I = 0; I != E; ++I) {
7613 if (I)
7614 Enc += ',';
7615 Enc += FE[I].str();
7616 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007617 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007618 Enc += '}';
7619 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7620 return true;
7621}
7622
7623/// Appends enum types to Enc and adds the encoding to the cache.
7624static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7625 TypeStringCache &TSC,
7626 const IdentifierInfo *ID) {
7627 // Append the cached TypeString if we have one.
7628 StringRef TypeString = TSC.lookupStr(ID);
7629 if (!TypeString.empty()) {
7630 Enc += TypeString;
7631 return true;
7632 }
7633
7634 size_t Start = Enc.size();
7635 Enc += "e(";
7636 if (ID)
7637 Enc += ID->getName();
7638 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007639
7640 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007641 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007642 SmallVector<FieldEncoding, 16> FE;
7643 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7644 ++I) {
7645 SmallStringEnc EnumEnc;
7646 EnumEnc += "m(";
7647 EnumEnc += I->getName();
7648 EnumEnc += "){";
7649 I->getInitVal().toString(EnumEnc);
7650 EnumEnc += '}';
7651 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7652 }
7653 std::sort(FE.begin(), FE.end());
7654 unsigned E = FE.size();
7655 for (unsigned I = 0; I != E; ++I) {
7656 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007657 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007658 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007659 }
7660 }
7661 Enc += '}';
7662 TSC.addIfComplete(ID, Enc.substr(Start), false);
7663 return true;
7664}
7665
7666/// Appends type's qualifier to Enc.
7667/// This is done prior to appending the type's encoding.
7668static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7669 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007670 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007671 int Lookup = 0;
7672 if (QT.isConstQualified())
7673 Lookup += 1<<0;
7674 if (QT.isRestrictQualified())
7675 Lookup += 1<<1;
7676 if (QT.isVolatileQualified())
7677 Lookup += 1<<2;
7678 Enc += Table[Lookup];
7679}
7680
7681/// Appends built-in types to Enc.
7682static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7683 const char *EncType;
7684 switch (BT->getKind()) {
7685 case BuiltinType::Void:
7686 EncType = "0";
7687 break;
7688 case BuiltinType::Bool:
7689 EncType = "b";
7690 break;
7691 case BuiltinType::Char_U:
7692 EncType = "uc";
7693 break;
7694 case BuiltinType::UChar:
7695 EncType = "uc";
7696 break;
7697 case BuiltinType::SChar:
7698 EncType = "sc";
7699 break;
7700 case BuiltinType::UShort:
7701 EncType = "us";
7702 break;
7703 case BuiltinType::Short:
7704 EncType = "ss";
7705 break;
7706 case BuiltinType::UInt:
7707 EncType = "ui";
7708 break;
7709 case BuiltinType::Int:
7710 EncType = "si";
7711 break;
7712 case BuiltinType::ULong:
7713 EncType = "ul";
7714 break;
7715 case BuiltinType::Long:
7716 EncType = "sl";
7717 break;
7718 case BuiltinType::ULongLong:
7719 EncType = "ull";
7720 break;
7721 case BuiltinType::LongLong:
7722 EncType = "sll";
7723 break;
7724 case BuiltinType::Float:
7725 EncType = "ft";
7726 break;
7727 case BuiltinType::Double:
7728 EncType = "d";
7729 break;
7730 case BuiltinType::LongDouble:
7731 EncType = "ld";
7732 break;
7733 default:
7734 return false;
7735 }
7736 Enc += EncType;
7737 return true;
7738}
7739
7740/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7741static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7742 const CodeGen::CodeGenModule &CGM,
7743 TypeStringCache &TSC) {
7744 Enc += "p(";
7745 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7746 return false;
7747 Enc += ')';
7748 return true;
7749}
7750
7751/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007752static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7753 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007754 const CodeGen::CodeGenModule &CGM,
7755 TypeStringCache &TSC, StringRef NoSizeEnc) {
7756 if (AT->getSizeModifier() != ArrayType::Normal)
7757 return false;
7758 Enc += "a(";
7759 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7760 CAT->getSize().toStringUnsigned(Enc);
7761 else
7762 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7763 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007764 // The Qualifiers should be attached to the type rather than the array.
7765 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007766 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7767 return false;
7768 Enc += ')';
7769 return true;
7770}
7771
7772/// Appends a function encoding to Enc, calling appendType for the return type
7773/// and the arguments.
7774static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7775 const CodeGen::CodeGenModule &CGM,
7776 TypeStringCache &TSC) {
7777 Enc += "f{";
7778 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7779 return false;
7780 Enc += "}(";
7781 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7782 // N.B. we are only interested in the adjusted param types.
7783 auto I = FPT->param_type_begin();
7784 auto E = FPT->param_type_end();
7785 if (I != E) {
7786 do {
7787 if (!appendType(Enc, *I, CGM, TSC))
7788 return false;
7789 ++I;
7790 if (I != E)
7791 Enc += ',';
7792 } while (I != E);
7793 if (FPT->isVariadic())
7794 Enc += ",va";
7795 } else {
7796 if (FPT->isVariadic())
7797 Enc += "va";
7798 else
7799 Enc += '0';
7800 }
7801 }
7802 Enc += ')';
7803 return true;
7804}
7805
7806/// Handles the type's qualifier before dispatching a call to handle specific
7807/// type encodings.
7808static bool appendType(SmallStringEnc &Enc, QualType QType,
7809 const CodeGen::CodeGenModule &CGM,
7810 TypeStringCache &TSC) {
7811
7812 QualType QT = QType.getCanonicalType();
7813
Robert Lytton6adb20f2014-06-05 09:06:21 +00007814 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7815 // The Qualifiers should be attached to the type rather than the array.
7816 // Thus we don't call appendQualifier() here.
7817 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7818
Robert Lytton844aeeb2014-05-02 09:33:20 +00007819 appendQualifier(Enc, QT);
7820
7821 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7822 return appendBuiltinType(Enc, BT);
7823
Robert Lytton844aeeb2014-05-02 09:33:20 +00007824 if (const PointerType *PT = QT->getAs<PointerType>())
7825 return appendPointerType(Enc, PT, CGM, TSC);
7826
7827 if (const EnumType *ET = QT->getAs<EnumType>())
7828 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7829
7830 if (const RecordType *RT = QT->getAsStructureType())
7831 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7832
7833 if (const RecordType *RT = QT->getAsUnionType())
7834 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7835
7836 if (const FunctionType *FT = QT->getAs<FunctionType>())
7837 return appendFunctionType(Enc, FT, CGM, TSC);
7838
7839 return false;
7840}
7841
7842static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7843 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7844 if (!D)
7845 return false;
7846
7847 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7848 if (FD->getLanguageLinkage() != CLanguageLinkage)
7849 return false;
7850 return appendType(Enc, FD->getType(), CGM, TSC);
7851 }
7852
7853 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7854 if (VD->getLanguageLinkage() != CLanguageLinkage)
7855 return false;
7856 QualType QT = VD->getType().getCanonicalType();
7857 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7858 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007859 // The Qualifiers should be attached to the type rather than the array.
7860 // Thus we don't call appendQualifier() here.
7861 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007862 }
7863 return appendType(Enc, QT, CGM, TSC);
7864 }
7865 return false;
7866}
7867
7868
Robert Lytton0e076492013-08-13 09:43:10 +00007869//===----------------------------------------------------------------------===//
7870// Driver code
7871//===----------------------------------------------------------------------===//
7872
Rafael Espindola9f834732014-09-19 01:54:22 +00007873const llvm::Triple &CodeGenModule::getTriple() const {
7874 return getTarget().getTriple();
7875}
7876
7877bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00007878 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00007879}
7880
Chris Lattner2b037972010-07-29 02:01:43 +00007881const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007882 if (TheTargetCodeGenInfo)
7883 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007884
Reid Kleckner9305fd12016-04-13 23:37:17 +00007885 // Helper to set the unique_ptr while still keeping the return value.
7886 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
7887 this->TheTargetCodeGenInfo.reset(P);
7888 return *P;
7889 };
7890
John McCallc8e01702013-04-16 22:48:15 +00007891 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007892 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007893 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007894 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007895
Derek Schuff09338a22012-09-06 17:37:28 +00007896 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007897 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007898 case llvm::Triple::mips:
7899 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007900 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00007901 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
7902 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007903
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007904 case llvm::Triple::mips64:
7905 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007906 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007907
Tim Northover25e8a672014-05-24 12:51:25 +00007908 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007909 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007910 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007911 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007912 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007913
Reid Kleckner9305fd12016-04-13 23:37:17 +00007914 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007915 }
7916
Dan Gohmanc2853072015-09-03 22:51:53 +00007917 case llvm::Triple::wasm32:
7918 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007919 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00007920
Daniel Dunbard59655c2009-09-12 00:59:49 +00007921 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007922 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007923 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007924 case llvm::Triple::thumbeb: {
7925 if (Triple.getOS() == llvm::Triple::Win32) {
7926 return SetCGInfo(
7927 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007928 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007929
Reid Kleckner9305fd12016-04-13 23:37:17 +00007930 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
7931 StringRef ABIStr = getTarget().getABI();
7932 if (ABIStr == "apcs-gnu")
7933 Kind = ARMABIInfo::APCS;
7934 else if (ABIStr == "aapcs16")
7935 Kind = ARMABIInfo::AAPCS16_VFP;
7936 else if (CodeGenOpts.FloatABI == "hard" ||
7937 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007938 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00007939 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007940 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00007941 Kind = ARMABIInfo::AAPCS_VFP;
7942
7943 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
7944 }
7945
John McCallea8d8bb2010-03-11 00:10:12 +00007946 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007947 return SetCGInfo(
7948 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007949 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007950 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007951 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007952 if (getTarget().getABI() == "elfv2")
7953 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007954 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007955
Reid Kleckner9305fd12016-04-13 23:37:17 +00007956 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007957 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00007958 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007959 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007960 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007961 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007962 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007963 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007964 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007965
Reid Kleckner9305fd12016-04-13 23:37:17 +00007966 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007967 }
John McCallea8d8bb2010-03-11 00:10:12 +00007968
Peter Collingbournec947aae2012-05-20 23:28:41 +00007969 case llvm::Triple::nvptx:
7970 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007971 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007972
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007973 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007974 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007975
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007976 case llvm::Triple::systemz: {
7977 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00007978 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007979 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007980
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007981 case llvm::Triple::tce:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007982 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007983
Eli Friedman33465822011-07-08 23:31:17 +00007984 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007985 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007986 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007987 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007988 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007989
John McCall1fe2a8c2013-06-18 02:46:29 +00007990 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007991 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
7992 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7993 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007994 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00007995 return SetCGInfo(new X86_32TargetCodeGenInfo(
7996 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
7997 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7998 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007999 }
Eli Friedman33465822011-07-08 23:31:17 +00008000 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008001
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008002 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008003 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008004 X86AVXABILevel AVXLevel =
8005 (ABI == "avx512"
8006 ? X86AVXABILevel::AVX512
8007 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008008
Chris Lattner04dc9572010-08-31 16:44:54 +00008009 switch (Triple.getOS()) {
8010 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008011 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008012 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008013 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008014 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008015 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008016 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008017 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008018 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008019 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008020 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008021 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008022 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008023 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008024 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008025 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008026 case llvm::Triple::sparc:
8027 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008028 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008029 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008030 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008031 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008032 case llvm::Triple::spir:
8033 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008034 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008035 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008036}