blob: aa67e71284aea45cb7aa55e9c7b0a40f89615beb [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
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000375unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
376 return llvm::CallingConv::C;
377}
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000378static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000379
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000380/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000381/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000382static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
383 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000384 if (FD->isUnnamedBitfield())
385 return true;
386
387 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000388
Eli Friedman0b3f2012011-11-18 03:47:20 +0000389 // Constant arrays of empty records count as empty, strip them off.
390 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000391 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000392 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
393 if (AT->getSize() == 0)
394 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000395 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000396 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000397
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000398 const RecordType *RT = FT->getAs<RecordType>();
399 if (!RT)
400 return false;
401
402 // C++ record fields are never empty, at least in the Itanium ABI.
403 //
404 // FIXME: We should use a predicate for whether this behavior is true in the
405 // current ABI.
406 if (isa<CXXRecordDecl>(RT->getDecl()))
407 return false;
408
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000409 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000410}
411
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000412/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000413/// fields. Note that a structure with a flexible array member is not
414/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000415static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000416 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000417 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000418 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000419 const RecordDecl *RD = RT->getDecl();
420 if (RD->hasFlexibleArrayMember())
421 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000422
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000423 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000424 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000425 for (const auto &I : CXXRD->bases())
426 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000427 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000428
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000429 for (const auto *I : RD->fields())
430 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000431 return false;
432 return true;
433}
434
435/// isSingleElementStruct - Determine if a structure is a "single
436/// element struct", i.e. it has exactly one non-empty field or
437/// exactly one field which is itself a single element
438/// struct. Structures with flexible array members are never
439/// considered single element structs.
440///
441/// \return The field declaration for the single non-empty field, if
442/// it exists.
443static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000444 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000445 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000446 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000447
448 const RecordDecl *RD = RT->getDecl();
449 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000450 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000451
Craig Topper8a13c412014-05-21 05:09:00 +0000452 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000453
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000454 // If this is a C++ record, check the bases first.
455 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000456 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000457 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000458 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000459 continue;
460
461 // If we already found an element then this isn't a single-element struct.
462 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000463 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000464
465 // If this is non-empty and not a single element struct, the composite
466 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000467 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000468 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000469 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000470 }
471 }
472
473 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000474 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000475 QualType FT = FD->getType();
476
477 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000478 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000479 continue;
480
481 // If we already found an element then this isn't a single-element
482 // struct.
483 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000484 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000485
486 // Treat single element arrays as the element.
487 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
488 if (AT->getSize().getZExtValue() != 1)
489 break;
490 FT = AT->getElementType();
491 }
492
John McCalla1dee5302010-08-22 10:59:02 +0000493 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000494 Found = FT.getTypePtr();
495 } else {
496 Found = isSingleElementStruct(FT, Context);
497 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000498 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000499 }
500 }
501
Eli Friedmanee945342011-11-18 01:25:50 +0000502 // We don't consider a struct a single-element struct if it has
503 // padding beyond the element type.
504 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000505 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000506
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000507 return Found;
508}
509
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000510namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000511Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
512 const ABIArgInfo &AI) {
513 // This default implementation defers to the llvm backend's va_arg
514 // instruction. It can handle only passing arguments directly
515 // (typically only handled in the backend for primitive types), or
516 // aggregates passed indirectly by pointer (NOTE: if the "byval"
517 // flag has ABI impact in the callee, this implementation cannot
518 // work.)
519
520 // Only a few cases are covered here at the moment -- those needed
521 // by the default abi.
522 llvm::Value *Val;
523
524 if (AI.isIndirect()) {
525 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000526 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000527 assert(
528 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000529 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000530
531 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
532 CharUnits TyAlignForABI = TyInfo.second;
533
534 llvm::Type *BaseTy =
535 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
536 llvm::Value *Addr =
537 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
538 return Address(Addr, TyAlignForABI);
539 } else {
540 assert((AI.isDirect() || AI.isExtend()) &&
541 "Unexpected ArgInfo Kind in generic VAArg emitter!");
542
543 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000544 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000545 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000546 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000547 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000548 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000549 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000550 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000551
552 Address Temp = CGF.CreateMemTemp(Ty, "varet");
553 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
554 CGF.Builder.CreateStore(Val, Temp);
555 return Temp;
556 }
557}
558
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000559/// DefaultABIInfo - The default implementation for ABI specific
560/// details. This implementation provides information which results in
561/// self-consistent and sensible LLVM IR generation, but does not
562/// conform to any particular ABI.
563class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000564public:
565 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000566
Chris Lattner458b2aa2010-07-29 02:16:43 +0000567 ABIArgInfo classifyReturnType(QualType RetTy) const;
568 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000569
Craig Topper4f12f102014-03-12 06:41:41 +0000570 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000571 if (!getCXXABI().classifyReturnType(FI))
572 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000573 for (auto &I : FI.arguments())
574 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000575 }
576
John McCall7f416cc2015-09-08 08:05:57 +0000577 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000578 QualType Ty) const override {
579 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
580 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000581};
582
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000583class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
584public:
Chris Lattner2b037972010-07-29 02:01:43 +0000585 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
586 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000587};
588
Chris Lattner458b2aa2010-07-29 02:16:43 +0000589ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000590 Ty = useFirstFieldIfTransparentUnion(Ty);
591
592 if (isAggregateTypeForABI(Ty)) {
593 // Records with non-trivial destructors/copy-constructors should not be
594 // passed by value.
595 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000596 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000597
John McCall7f416cc2015-09-08 08:05:57 +0000598 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000599 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000600
Chris Lattner9723d6c2010-03-11 18:19:55 +0000601 // Treat an enum type as its underlying type.
602 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
603 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000604
Chris Lattner9723d6c2010-03-11 18:19:55 +0000605 return (Ty->isPromotableIntegerType() ?
606 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000607}
608
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000609ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
610 if (RetTy->isVoidType())
611 return ABIArgInfo::getIgnore();
612
613 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000614 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000615
616 // Treat an enum type as its underlying type.
617 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
618 RetTy = EnumTy->getDecl()->getIntegerType();
619
620 return (RetTy->isPromotableIntegerType() ?
621 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
622}
623
Derek Schuff09338a22012-09-06 17:37:28 +0000624//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000625// WebAssembly ABI Implementation
626//
627// This is a very simple ABI that relies a lot on DefaultABIInfo.
628//===----------------------------------------------------------------------===//
629
630class WebAssemblyABIInfo final : public DefaultABIInfo {
631public:
632 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
633 : DefaultABIInfo(CGT) {}
634
635private:
636 ABIArgInfo classifyReturnType(QualType RetTy) const;
637 ABIArgInfo classifyArgumentType(QualType Ty) const;
638
639 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000640 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000641 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000642 void computeInfo(CGFunctionInfo &FI) const override {
643 if (!getCXXABI().classifyReturnType(FI))
644 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
645 for (auto &Arg : FI.arguments())
646 Arg.info = classifyArgumentType(Arg.type);
647 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000648
649 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
650 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000651};
652
653class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
654public:
655 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
656 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
657};
658
659/// \brief Classify argument of given type \p Ty.
660ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
661 Ty = useFirstFieldIfTransparentUnion(Ty);
662
663 if (isAggregateTypeForABI(Ty)) {
664 // Records with non-trivial destructors/copy-constructors should not be
665 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000666 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000667 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000668 // Ignore empty structs/unions.
669 if (isEmptyRecord(getContext(), Ty, true))
670 return ABIArgInfo::getIgnore();
671 // Lower single-element structs to just pass a regular value. TODO: We
672 // could do reasonable-size multiple-element structs too, using getExpand(),
673 // though watch out for things like bitfields.
674 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
675 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000676 }
677
678 // Otherwise just do the default thing.
679 return DefaultABIInfo::classifyArgumentType(Ty);
680}
681
682ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
683 if (isAggregateTypeForABI(RetTy)) {
684 // Records with non-trivial destructors/copy-constructors should not be
685 // returned by value.
686 if (!getRecordArgABI(RetTy, getCXXABI())) {
687 // Ignore empty structs/unions.
688 if (isEmptyRecord(getContext(), RetTy, true))
689 return ABIArgInfo::getIgnore();
690 // Lower single-element structs to just return a regular value. TODO: We
691 // could do reasonable-size multiple-element structs too, using
692 // ABIArgInfo::getDirect().
693 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
694 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
695 }
696 }
697
698 // Otherwise just do the default thing.
699 return DefaultABIInfo::classifyReturnType(RetTy);
700}
701
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000702Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
703 QualType Ty) const {
704 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
705 getContext().getTypeInfoInChars(Ty),
706 CharUnits::fromQuantity(4),
707 /*AllowHigherAlign=*/ true);
708}
709
Dan Gohmanc2853072015-09-03 22:51:53 +0000710//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000711// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000712//
713// This is a simplified version of the x86_32 ABI. Arguments and return values
714// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000715//===----------------------------------------------------------------------===//
716
717class PNaClABIInfo : public ABIInfo {
718 public:
719 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
720
721 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000722 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000723
Craig Topper4f12f102014-03-12 06:41:41 +0000724 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000725 Address EmitVAArg(CodeGenFunction &CGF,
726 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000727};
728
729class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
730 public:
731 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
732 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
733};
734
735void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000736 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000737 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
738
Reid Kleckner40ca9132014-05-13 22:05:45 +0000739 for (auto &I : FI.arguments())
740 I.info = classifyArgumentType(I.type);
741}
Derek Schuff09338a22012-09-06 17:37:28 +0000742
John McCall7f416cc2015-09-08 08:05:57 +0000743Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
744 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000745 // The PNaCL ABI is a bit odd, in that varargs don't use normal
746 // function classification. Structs get passed directly for varargs
747 // functions, through a rewriting transform in
748 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
749 // this target to actually support a va_arg instructions with an
750 // aggregate type, unlike other targets.
751 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000752}
753
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000754/// \brief Classify argument of given type \p Ty.
755ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000756 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000757 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000758 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
759 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000760 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
761 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000762 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000763 } else if (Ty->isFloatingType()) {
764 // Floating-point types don't go inreg.
765 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000766 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000767
768 return (Ty->isPromotableIntegerType() ?
769 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000770}
771
772ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
773 if (RetTy->isVoidType())
774 return ABIArgInfo::getIgnore();
775
Eli Benderskye20dad62013-04-04 22:49:35 +0000776 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000777 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000778 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000779
780 // Treat an enum type as its underlying type.
781 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
782 RetTy = EnumTy->getDecl()->getIntegerType();
783
784 return (RetTy->isPromotableIntegerType() ?
785 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
786}
787
Chad Rosier651c1832013-03-25 21:00:27 +0000788/// IsX86_MMXType - Return true if this is an MMX type.
789bool IsX86_MMXType(llvm::Type *IRType) {
790 // 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 +0000791 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
792 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
793 IRType->getScalarSizeInBits() != 64;
794}
795
Jay Foad7c57be32011-07-11 09:56:20 +0000796static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000797 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000798 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000799 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
800 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
801 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000802 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000803 }
804
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000805 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000806 }
807
808 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000809 return Ty;
810}
811
Reid Kleckner80944df2014-10-31 22:00:51 +0000812/// Returns true if this type can be passed in SSE registers with the
813/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
814static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
815 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
816 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
817 return true;
818 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
819 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
820 // registers specially.
821 unsigned VecSize = Context.getTypeSize(VT);
822 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
823 return true;
824 }
825 return false;
826}
827
828/// Returns true if this aggregate is small enough to be passed in SSE registers
829/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
830static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
831 return NumMembers <= 4;
832}
833
Chris Lattner0cf24192010-06-28 20:05:43 +0000834//===----------------------------------------------------------------------===//
835// X86-32 ABI Implementation
836//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000837
Reid Kleckner661f35b2014-01-18 01:12:41 +0000838/// \brief Similar to llvm::CCState, but for Clang.
839struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000840 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000841
842 unsigned CC;
843 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000844 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000845};
846
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000847/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000848class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000849 enum Class {
850 Integer,
851 Float
852 };
853
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000854 static const unsigned MinABIStackAlignInBytes = 4;
855
David Chisnallde3a0692009-08-17 23:08:21 +0000856 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000857 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000858 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000859 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000860 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000861 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000862
863 static bool isRegisterSize(unsigned Size) {
864 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
865 }
866
Reid Kleckner80944df2014-10-31 22:00:51 +0000867 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
868 // FIXME: Assumes vectorcall is in use.
869 return isX86VectorTypeForVectorCall(getContext(), Ty);
870 }
871
872 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
873 uint64_t NumMembers) const override {
874 // FIXME: Assumes vectorcall is in use.
875 return isX86VectorCallAggregateSmallEnough(NumMembers);
876 }
877
Reid Kleckner40ca9132014-05-13 22:05:45 +0000878 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000879
Daniel Dunbar557893d2010-04-21 19:10:51 +0000880 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
881 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000882 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
883
John McCall7f416cc2015-09-08 08:05:57 +0000884 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000885
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000886 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000887 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000888
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000889 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000890 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000891 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000892 /// \brief Updates the number of available free registers, returns
893 /// true if any registers were allocated.
894 bool updateFreeRegs(QualType Ty, CCState &State) const;
895
896 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
897 bool &NeedsPadding) const;
898 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000899
Reid Kleckner04046052016-05-02 17:41:07 +0000900 bool canExpandIndirectArgument(QualType Ty) const;
901
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000902 /// \brief Rewrite the function info so that all memory arguments use
903 /// inalloca.
904 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
905
906 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000907 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000908 QualType Type) const;
909
Rafael Espindola75419dc2012-07-23 23:30:29 +0000910public:
911
Craig Topper4f12f102014-03-12 06:41:41 +0000912 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000913 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
914 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000915
Michael Kupersteindc745202015-10-19 07:52:25 +0000916 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
917 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000918 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000919 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000920 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
921 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000922 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000923 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000924 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000925
926 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
927 ArrayRef<llvm::Type*> scalars,
928 bool asReturnValue) const override {
929 // LLVM's x86-32 lowering currently only assigns up to three
930 // integer registers and three fp registers. Oddly, it'll use up to
931 // four vector registers for vectors, but those can overlap with the
932 // scalar registers.
933 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
934 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000935};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000936
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000937class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
938public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000939 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
940 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000941 unsigned NumRegisterParameters, bool SoftFloatABI)
942 : TargetCodeGenInfo(new X86_32ABIInfo(
943 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
944 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000945
John McCall1fe2a8c2013-06-18 02:46:29 +0000946 static bool isStructReturnInRegABI(
947 const llvm::Triple &Triple, const CodeGenOptions &Opts);
948
Eric Christopher162c91c2015-06-05 22:03:00 +0000949 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000950 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000951
Craig Topper4f12f102014-03-12 06:41:41 +0000952 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000953 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000954 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000955 return 4;
956 }
957
958 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000959 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000960
Jay Foad7c57be32011-07-11 09:56:20 +0000961 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000962 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000963 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000964 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
965 }
966
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000967 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
968 std::string &Constraints,
969 std::vector<llvm::Type *> &ResultRegTypes,
970 std::vector<llvm::Type *> &ResultTruncRegTypes,
971 std::vector<LValue> &ResultRegDests,
972 std::string &AsmString,
973 unsigned NumOutputs) const override;
974
Craig Topper4f12f102014-03-12 06:41:41 +0000975 llvm::Constant *
976 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000977 unsigned Sig = (0xeb << 0) | // jmp rel8
978 (0x06 << 8) | // .+0x08
979 ('F' << 16) |
980 ('T' << 24);
981 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
982 }
John McCall01391782016-02-05 21:37:38 +0000983
984 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
985 return "movl\t%ebp, %ebp"
986 "\t\t## marker for objc_retainAutoreleaseReturnValue";
987 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000988};
989
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000990}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000991
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000992/// Rewrite input constraint references after adding some output constraints.
993/// In the case where there is one output and one input and we add one output,
994/// we need to replace all operand references greater than or equal to 1:
995/// mov $0, $1
996/// mov eax, $1
997/// The result will be:
998/// mov $0, $2
999/// mov eax, $2
1000static void rewriteInputConstraintReferences(unsigned FirstIn,
1001 unsigned NumNewOuts,
1002 std::string &AsmString) {
1003 std::string Buf;
1004 llvm::raw_string_ostream OS(Buf);
1005 size_t Pos = 0;
1006 while (Pos < AsmString.size()) {
1007 size_t DollarStart = AsmString.find('$', Pos);
1008 if (DollarStart == std::string::npos)
1009 DollarStart = AsmString.size();
1010 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1011 if (DollarEnd == std::string::npos)
1012 DollarEnd = AsmString.size();
1013 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1014 Pos = DollarEnd;
1015 size_t NumDollars = DollarEnd - DollarStart;
1016 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1017 // We have an operand reference.
1018 size_t DigitStart = Pos;
1019 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1020 if (DigitEnd == std::string::npos)
1021 DigitEnd = AsmString.size();
1022 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1023 unsigned OperandIndex;
1024 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1025 if (OperandIndex >= FirstIn)
1026 OperandIndex += NumNewOuts;
1027 OS << OperandIndex;
1028 } else {
1029 OS << OperandStr;
1030 }
1031 Pos = DigitEnd;
1032 }
1033 }
1034 AsmString = std::move(OS.str());
1035}
1036
1037/// Add output constraints for EAX:EDX because they are return registers.
1038void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1039 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1040 std::vector<llvm::Type *> &ResultRegTypes,
1041 std::vector<llvm::Type *> &ResultTruncRegTypes,
1042 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1043 unsigned NumOutputs) const {
1044 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1045
1046 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1047 // larger.
1048 if (!Constraints.empty())
1049 Constraints += ',';
1050 if (RetWidth <= 32) {
1051 Constraints += "={eax}";
1052 ResultRegTypes.push_back(CGF.Int32Ty);
1053 } else {
1054 // Use the 'A' constraint for EAX:EDX.
1055 Constraints += "=A";
1056 ResultRegTypes.push_back(CGF.Int64Ty);
1057 }
1058
1059 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1060 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1061 ResultTruncRegTypes.push_back(CoerceTy);
1062
1063 // Coerce the integer by bitcasting the return slot pointer.
1064 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1065 CoerceTy->getPointerTo()));
1066 ResultRegDests.push_back(ReturnSlot);
1067
1068 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1069}
1070
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001071/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001072/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001073bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1074 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001075 uint64_t Size = Context.getTypeSize(Ty);
1076
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001077 // For i386, type must be register sized.
1078 // For the MCU ABI, it only needs to be <= 8-byte
1079 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1080 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001081
1082 if (Ty->isVectorType()) {
1083 // 64- and 128- bit vectors inside structures are not returned in
1084 // registers.
1085 if (Size == 64 || Size == 128)
1086 return false;
1087
1088 return true;
1089 }
1090
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001091 // If this is a builtin, pointer, enum, complex type, member pointer, or
1092 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001093 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001094 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001095 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001096 return true;
1097
1098 // Arrays are treated like records.
1099 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001100 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101
1102 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001103 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001104 if (!RT) return false;
1105
Anders Carlsson40446e82010-01-27 03:25:19 +00001106 // FIXME: Traverse bases here too.
1107
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001108 // Structure types are passed in register if all fields would be
1109 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001110 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001111 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001112 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001113 continue;
1114
1115 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001116 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001117 return false;
1118 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001119 return true;
1120}
1121
Reid Kleckner04046052016-05-02 17:41:07 +00001122static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1123 // Treat complex types as the element type.
1124 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1125 Ty = CTy->getElementType();
1126
1127 // Check for a type which we know has a simple scalar argument-passing
1128 // convention without any padding. (We're specifically looking for 32
1129 // and 64-bit integer and integer-equivalents, float, and double.)
1130 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1131 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1132 return false;
1133
1134 uint64_t Size = Context.getTypeSize(Ty);
1135 return Size == 32 || Size == 64;
1136}
1137
1138/// Test whether an argument type which is to be passed indirectly (on the
1139/// stack) would have the equivalent layout if it was expanded into separate
1140/// arguments. If so, we prefer to do the latter to avoid inhibiting
1141/// optimizations.
1142bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1143 // We can only expand structure types.
1144 const RecordType *RT = Ty->getAs<RecordType>();
1145 if (!RT)
1146 return false;
1147 const RecordDecl *RD = RT->getDecl();
1148 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1149 if (!IsWin32StructABI ) {
1150 // On non-Windows, we have to conservatively match our old bitcode
1151 // prototypes in order to be ABI-compatible at the bitcode level.
1152 if (!CXXRD->isCLike())
1153 return false;
1154 } else {
1155 // Don't do this for dynamic classes.
1156 if (CXXRD->isDynamicClass())
1157 return false;
1158 // Don't do this if there are any non-empty bases.
1159 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1160 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1161 return false;
1162 }
1163 }
1164 }
1165
1166 uint64_t Size = 0;
1167
1168 for (const auto *FD : RD->fields()) {
1169 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1170 // argument is smaller than 32-bits, expanding the struct will create
1171 // alignment padding.
1172 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1173 return false;
1174
1175 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1176 // how to expand them yet, and the predicate for telling if a bitfield still
1177 // counts as "basic" is more complicated than what we were doing previously.
1178 if (FD->isBitField())
1179 return false;
1180
1181 Size += getContext().getTypeSize(FD->getType());
1182 }
1183
1184 // We can do this if there was no alignment padding.
1185 return Size == getContext().getTypeSize(Ty);
1186}
1187
John McCall7f416cc2015-09-08 08:05:57 +00001188ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001189 // If the return value is indirect, then the hidden argument is consuming one
1190 // integer register.
1191 if (State.FreeRegs) {
1192 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001193 if (!IsMCUABI)
1194 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001195 }
John McCall7f416cc2015-09-08 08:05:57 +00001196 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001197}
1198
Eric Christopher7565e0d2015-05-29 23:09:49 +00001199ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1200 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001201 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001202 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001203
Reid Kleckner80944df2014-10-31 22:00:51 +00001204 const Type *Base = nullptr;
1205 uint64_t NumElts = 0;
1206 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1207 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1208 // The LLVM struct type for such an aggregate should lower properly.
1209 return ABIArgInfo::getDirect();
1210 }
1211
Chris Lattner458b2aa2010-07-29 02:16:43 +00001212 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001213 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001214 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001215 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001216
1217 // 128-bit vectors are a special case; they are returned in
1218 // registers and we need to make sure to pick a type the LLVM
1219 // backend will like.
1220 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001221 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001222 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223
1224 // Always return in register if it fits in a general purpose
1225 // register, or if it is 64 bits and has a single element.
1226 if ((Size == 8 || Size == 16 || Size == 32) ||
1227 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001228 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001229 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001230
John McCall7f416cc2015-09-08 08:05:57 +00001231 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001232 }
1233
1234 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001235 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001236
John McCalla1dee5302010-08-22 10:59:02 +00001237 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001238 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001239 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001240 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001241 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001242 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001243
David Chisnallde3a0692009-08-17 23:08:21 +00001244 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001245 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001246 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247
Denis Zobnin380b2242016-02-11 11:26:03 +00001248 // Ignore empty structs/unions.
1249 if (isEmptyRecord(getContext(), RetTy, true))
1250 return ABIArgInfo::getIgnore();
1251
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001252 // Small structures which are register sized are generally returned
1253 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001254 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001255 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001256
1257 // As a special-case, if the struct is a "single-element" struct, and
1258 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001259 // floating-point register. (MSVC does not apply this special case.)
1260 // We apply a similar transformation for pointer types to improve the
1261 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001262 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001263 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001264 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001265 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1266
1267 // FIXME: We should be able to narrow this integer in cases with dead
1268 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001269 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001270 }
1271
John McCall7f416cc2015-09-08 08:05:57 +00001272 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001273 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001274
Chris Lattner458b2aa2010-07-29 02:16:43 +00001275 // Treat an enum type as its underlying type.
1276 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1277 RetTy = EnumTy->getDecl()->getIntegerType();
1278
1279 return (RetTy->isPromotableIntegerType() ?
1280 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001281}
1282
Eli Friedman7919bea2012-06-05 19:40:46 +00001283static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1284 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1285}
1286
Daniel Dunbared23de32010-09-16 20:42:00 +00001287static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1288 const RecordType *RT = Ty->getAs<RecordType>();
1289 if (!RT)
1290 return 0;
1291 const RecordDecl *RD = RT->getDecl();
1292
1293 // If this is a C++ record, check the bases first.
1294 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001295 for (const auto &I : CXXRD->bases())
1296 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001297 return false;
1298
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001299 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001300 QualType FT = i->getType();
1301
Eli Friedman7919bea2012-06-05 19:40:46 +00001302 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001303 return true;
1304
1305 if (isRecordWithSSEVectorType(Context, FT))
1306 return true;
1307 }
1308
1309 return false;
1310}
1311
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001312unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1313 unsigned Align) const {
1314 // Otherwise, if the alignment is less than or equal to the minimum ABI
1315 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001316 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001317 return 0; // Use default alignment.
1318
1319 // On non-Darwin, the stack type alignment is always 4.
1320 if (!IsDarwinVectorABI) {
1321 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001322 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001323 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001324
Daniel Dunbared23de32010-09-16 20:42:00 +00001325 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001326 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1327 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001328 return 16;
1329
1330 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001331}
1332
Rafael Espindola703c47f2012-10-19 05:04:37 +00001333ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001334 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001335 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001336 if (State.FreeRegs) {
1337 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001338 if (!IsMCUABI)
1339 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001340 }
John McCall7f416cc2015-09-08 08:05:57 +00001341 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001342 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001343
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001344 // Compute the byval alignment.
1345 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1346 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1347 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001348 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001349
1350 // If the stack alignment is less than the type alignment, realign the
1351 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001352 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001353 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1354 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001355}
1356
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001357X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1358 const Type *T = isSingleElementStruct(Ty, getContext());
1359 if (!T)
1360 T = Ty.getTypePtr();
1361
1362 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1363 BuiltinType::Kind K = BT->getKind();
1364 if (K == BuiltinType::Float || K == BuiltinType::Double)
1365 return Float;
1366 }
1367 return Integer;
1368}
1369
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001370bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001371 if (!IsSoftFloatABI) {
1372 Class C = classify(Ty);
1373 if (C == Float)
1374 return false;
1375 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001376
Rafael Espindola077dd592012-10-24 01:58:58 +00001377 unsigned Size = getContext().getTypeSize(Ty);
1378 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001379
1380 if (SizeInRegs == 0)
1381 return false;
1382
Michael Kuperstein68901882015-10-25 08:18:20 +00001383 if (!IsMCUABI) {
1384 if (SizeInRegs > State.FreeRegs) {
1385 State.FreeRegs = 0;
1386 return false;
1387 }
1388 } else {
1389 // The MCU psABI allows passing parameters in-reg even if there are
1390 // earlier parameters that are passed on the stack. Also,
1391 // it does not allow passing >8-byte structs in-register,
1392 // even if there are 3 free registers available.
1393 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1394 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001395 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001396
Reid Kleckner661f35b2014-01-18 01:12:41 +00001397 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001398 return true;
1399}
1400
1401bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1402 bool &InReg,
1403 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001404 // On Windows, aggregates other than HFAs are never passed in registers, and
1405 // they do not consume register slots. Homogenous floating-point aggregates
1406 // (HFAs) have already been dealt with at this point.
1407 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1408 return false;
1409
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001410 NeedsPadding = false;
1411 InReg = !IsMCUABI;
1412
1413 if (!updateFreeRegs(Ty, State))
1414 return false;
1415
1416 if (IsMCUABI)
1417 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001418
Reid Kleckner80944df2014-10-31 22:00:51 +00001419 if (State.CC == llvm::CallingConv::X86_FastCall ||
1420 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001421 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001422 NeedsPadding = true;
1423
Rafael Espindola077dd592012-10-24 01:58:58 +00001424 return false;
1425 }
1426
Rafael Espindola703c47f2012-10-19 05:04:37 +00001427 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001428}
1429
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001430bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1431 if (!updateFreeRegs(Ty, State))
1432 return false;
1433
1434 if (IsMCUABI)
1435 return false;
1436
1437 if (State.CC == llvm::CallingConv::X86_FastCall ||
1438 State.CC == llvm::CallingConv::X86_VectorCall) {
1439 if (getContext().getTypeSize(Ty) > 32)
1440 return false;
1441
1442 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1443 Ty->isReferenceType());
1444 }
1445
1446 return true;
1447}
1448
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001449ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1450 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001451 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001452
Reid Klecknerb1be6832014-11-15 01:41:41 +00001453 Ty = useFirstFieldIfTransparentUnion(Ty);
1454
Reid Kleckner80944df2014-10-31 22:00:51 +00001455 // Check with the C++ ABI first.
1456 const RecordType *RT = Ty->getAs<RecordType>();
1457 if (RT) {
1458 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1459 if (RAA == CGCXXABI::RAA_Indirect) {
1460 return getIndirectResult(Ty, false, State);
1461 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1462 // The field index doesn't matter, we'll fix it up later.
1463 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1464 }
1465 }
1466
1467 // vectorcall adds the concept of a homogenous vector aggregate, similar
1468 // to other targets.
1469 const Type *Base = nullptr;
1470 uint64_t NumElts = 0;
1471 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1472 isHomogeneousAggregate(Ty, Base, NumElts)) {
1473 if (State.FreeSSERegs >= NumElts) {
1474 State.FreeSSERegs -= NumElts;
1475 if (Ty->isBuiltinType() || Ty->isVectorType())
1476 return ABIArgInfo::getDirect();
1477 return ABIArgInfo::getExpand();
1478 }
1479 return getIndirectResult(Ty, /*ByVal=*/false, State);
1480 }
1481
1482 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001483 // Structures with flexible arrays are always indirect.
1484 // FIXME: This should not be byval!
1485 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1486 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001487
Reid Kleckner04046052016-05-02 17:41:07 +00001488 // Ignore empty structs/unions on non-Windows.
1489 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001490 return ABIArgInfo::getIgnore();
1491
Rafael Espindolafad28de2012-10-24 01:59:00 +00001492 llvm::LLVMContext &LLVMContext = getVMContext();
1493 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001494 bool NeedsPadding = false;
1495 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001496 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001497 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001498 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001499 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001500 if (InReg)
1501 return ABIArgInfo::getDirectInReg(Result);
1502 else
1503 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001504 }
Craig Topper8a13c412014-05-21 05:09:00 +00001505 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001506
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001507 // Expand small (<= 128-bit) record types when we know that the stack layout
1508 // of those arguments will match the struct. This is important because the
1509 // LLVM backend isn't smart enough to remove byval, which inhibits many
1510 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001511 // Don't do this for the MCU if there are still free integer registers
1512 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001513 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1514 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001515 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001516 State.CC == llvm::CallingConv::X86_FastCall ||
1517 State.CC == llvm::CallingConv::X86_VectorCall,
1518 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001519
Reid Kleckner661f35b2014-01-18 01:12:41 +00001520 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001521 }
1522
Chris Lattnerd774ae92010-08-26 20:05:13 +00001523 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001524 // On Darwin, some vectors are passed in memory, we handle this by passing
1525 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001526 if (IsDarwinVectorABI) {
1527 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001528 if ((Size == 8 || Size == 16 || Size == 32) ||
1529 (Size == 64 && VT->getNumElements() == 1))
1530 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1531 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001532 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001533
Chad Rosier651c1832013-03-25 21:00:27 +00001534 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1535 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001536
Chris Lattnerd774ae92010-08-26 20:05:13 +00001537 return ABIArgInfo::getDirect();
1538 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001539
1540
Chris Lattner458b2aa2010-07-29 02:16:43 +00001541 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1542 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001543
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001544 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001545
1546 if (Ty->isPromotableIntegerType()) {
1547 if (InReg)
1548 return ABIArgInfo::getExtendInReg();
1549 return ABIArgInfo::getExtend();
1550 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001551
Rafael Espindola703c47f2012-10-19 05:04:37 +00001552 if (InReg)
1553 return ABIArgInfo::getDirectInReg();
1554 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001555}
1556
Rafael Espindolaa6472962012-07-24 00:01:07 +00001557void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001558 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001559 if (IsMCUABI)
1560 State.FreeRegs = 3;
1561 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001562 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001563 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1564 State.FreeRegs = 2;
1565 State.FreeSSERegs = 6;
1566 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001567 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001568 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001569 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001570
Reid Kleckner677539d2014-07-10 01:58:55 +00001571 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001572 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001573 } else if (FI.getReturnInfo().isIndirect()) {
1574 // The C++ ABI is not aware of register usage, so we have to check if the
1575 // return value was sret and put it in a register ourselves if appropriate.
1576 if (State.FreeRegs) {
1577 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001578 if (!IsMCUABI)
1579 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001580 }
1581 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001582
Peter Collingbournef7706832014-12-12 23:41:25 +00001583 // The chain argument effectively gives us another free register.
1584 if (FI.isChainCall())
1585 ++State.FreeRegs;
1586
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001587 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001588 for (auto &I : FI.arguments()) {
1589 I.info = classifyArgumentType(I.type, State);
1590 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001591 }
1592
1593 // If we needed to use inalloca for any argument, do a second pass and rewrite
1594 // all the memory arguments to use inalloca.
1595 if (UsedInAlloca)
1596 rewriteWithInAlloca(FI);
1597}
1598
1599void
1600X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001601 CharUnits &StackOffset, ABIArgInfo &Info,
1602 QualType Type) const {
1603 // Arguments are always 4-byte-aligned.
1604 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1605
1606 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001607 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1608 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001609 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001610
John McCall7f416cc2015-09-08 08:05:57 +00001611 // Insert padding bytes to respect alignment.
1612 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001613 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001614 if (StackOffset != FieldEnd) {
1615 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001616 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001617 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001618 FrameFields.push_back(Ty);
1619 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001620}
1621
Reid Kleckner852361d2014-07-26 00:12:26 +00001622static bool isArgInAlloca(const ABIArgInfo &Info) {
1623 // Leave ignored and inreg arguments alone.
1624 switch (Info.getKind()) {
1625 case ABIArgInfo::InAlloca:
1626 return true;
1627 case ABIArgInfo::Indirect:
1628 assert(Info.getIndirectByVal());
1629 return true;
1630 case ABIArgInfo::Ignore:
1631 return false;
1632 case ABIArgInfo::Direct:
1633 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001634 if (Info.getInReg())
1635 return false;
1636 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001637 case ABIArgInfo::Expand:
1638 case ABIArgInfo::CoerceAndExpand:
1639 // These are aggregate types which are never passed in registers when
1640 // inalloca is involved.
1641 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001642 }
1643 llvm_unreachable("invalid enum");
1644}
1645
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001646void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1647 assert(IsWin32StructABI && "inalloca only supported on win32");
1648
1649 // Build a packed struct type for all of the arguments in memory.
1650 SmallVector<llvm::Type *, 6> FrameFields;
1651
John McCall7f416cc2015-09-08 08:05:57 +00001652 // The stack alignment is always 4.
1653 CharUnits StackAlign = CharUnits::fromQuantity(4);
1654
1655 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001656 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1657
1658 // Put 'this' into the struct before 'sret', if necessary.
1659 bool IsThisCall =
1660 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1661 ABIArgInfo &Ret = FI.getReturnInfo();
1662 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1663 isArgInAlloca(I->info)) {
1664 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1665 ++I;
1666 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001667
1668 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001669 if (Ret.isIndirect() && !Ret.getInReg()) {
1670 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1671 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001672 // On Windows, the hidden sret parameter is always returned in eax.
1673 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001674 }
1675
1676 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001677 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001678 ++I;
1679
1680 // Put arguments passed in memory into the struct.
1681 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001682 if (isArgInAlloca(I->info))
1683 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001684 }
1685
1686 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001687 /*isPacked=*/true),
1688 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001689}
1690
John McCall7f416cc2015-09-08 08:05:57 +00001691Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1692 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001693
John McCall7f416cc2015-09-08 08:05:57 +00001694 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001695
John McCall7f416cc2015-09-08 08:05:57 +00001696 // x86-32 changes the alignment of certain arguments on the stack.
1697 //
1698 // Just messing with TypeInfo like this works because we never pass
1699 // anything indirectly.
1700 TypeInfo.second = CharUnits::fromQuantity(
1701 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001702
John McCall7f416cc2015-09-08 08:05:57 +00001703 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1704 TypeInfo, CharUnits::fromQuantity(4),
1705 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001706}
1707
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001708bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1709 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1710 assert(Triple.getArch() == llvm::Triple::x86);
1711
1712 switch (Opts.getStructReturnConvention()) {
1713 case CodeGenOptions::SRCK_Default:
1714 break;
1715 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1716 return false;
1717 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1718 return true;
1719 }
1720
Michael Kupersteind749f232015-10-27 07:46:22 +00001721 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001722 return true;
1723
1724 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001725 case llvm::Triple::DragonFly:
1726 case llvm::Triple::FreeBSD:
1727 case llvm::Triple::OpenBSD:
1728 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001729 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001730 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001731 default:
1732 return false;
1733 }
1734}
1735
Eric Christopher162c91c2015-06-05 22:03:00 +00001736void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001737 llvm::GlobalValue *GV,
1738 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001739 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001740 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1741 // Get the LLVM function.
1742 llvm::Function *Fn = cast<llvm::Function>(GV);
1743
1744 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001745 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001746 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001747 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1748 llvm::AttributeSet::get(CGM.getLLVMContext(),
1749 llvm::AttributeSet::FunctionIndex,
1750 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001751 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001752 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1753 llvm::Function *Fn = cast<llvm::Function>(GV);
1754 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1755 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001756 }
1757}
1758
John McCallbeec5a02010-03-06 00:35:14 +00001759bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1760 CodeGen::CodeGenFunction &CGF,
1761 llvm::Value *Address) const {
1762 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001763
Chris Lattnerece04092012-02-07 00:39:47 +00001764 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001765
John McCallbeec5a02010-03-06 00:35:14 +00001766 // 0-7 are the eight integer registers; the order is different
1767 // on Darwin (for EH), but the range is the same.
1768 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001769 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001770
John McCallc8e01702013-04-16 22:48:15 +00001771 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001772 // 12-16 are st(0..4). Not sure why we stop at 4.
1773 // These have size 16, which is sizeof(long double) on
1774 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001775 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001776 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001777
John McCallbeec5a02010-03-06 00:35:14 +00001778 } else {
1779 // 9 is %eflags, which doesn't get a size on Darwin for some
1780 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001781 Builder.CreateAlignedStore(
1782 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1783 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001784
1785 // 11-16 are st(0..5). Not sure why we stop at 5.
1786 // These have size 12, which is sizeof(long double) on
1787 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001788 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001789 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1790 }
John McCallbeec5a02010-03-06 00:35:14 +00001791
1792 return false;
1793}
1794
Chris Lattner0cf24192010-06-28 20:05:43 +00001795//===----------------------------------------------------------------------===//
1796// X86-64 ABI Implementation
1797//===----------------------------------------------------------------------===//
1798
1799
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001800namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001801/// The AVX ABI level for X86 targets.
1802enum class X86AVXABILevel {
1803 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001804 AVX,
1805 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001806};
1807
1808/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1809static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1810 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001811 case X86AVXABILevel::AVX512:
1812 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001813 case X86AVXABILevel::AVX:
1814 return 256;
1815 case X86AVXABILevel::None:
1816 return 128;
1817 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001818 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001819}
1820
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001821/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001822class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001823 enum Class {
1824 Integer = 0,
1825 SSE,
1826 SSEUp,
1827 X87,
1828 X87Up,
1829 ComplexX87,
1830 NoClass,
1831 Memory
1832 };
1833
1834 /// merge - Implement the X86_64 ABI merging algorithm.
1835 ///
1836 /// Merge an accumulating classification \arg Accum with a field
1837 /// classification \arg Field.
1838 ///
1839 /// \param Accum - The accumulating classification. This should
1840 /// always be either NoClass or the result of a previous merge
1841 /// call. In addition, this should never be Memory (the caller
1842 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001843 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001844
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001845 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1846 ///
1847 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1848 /// final MEMORY or SSE classes when necessary.
1849 ///
1850 /// \param AggregateSize - The size of the current aggregate in
1851 /// the classification process.
1852 ///
1853 /// \param Lo - The classification for the parts of the type
1854 /// residing in the low word of the containing object.
1855 ///
1856 /// \param Hi - The classification for the parts of the type
1857 /// residing in the higher words of the containing object.
1858 ///
1859 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1860
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001861 /// classify - Determine the x86_64 register classes in which the
1862 /// given type T should be passed.
1863 ///
1864 /// \param Lo - The classification for the parts of the type
1865 /// residing in the low word of the containing object.
1866 ///
1867 /// \param Hi - The classification for the parts of the type
1868 /// residing in the high word of the containing object.
1869 ///
1870 /// \param OffsetBase - The bit offset of this type in the
1871 /// containing object. Some parameters are classified different
1872 /// depending on whether they straddle an eightbyte boundary.
1873 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001874 /// \param isNamedArg - Whether the argument in question is a "named"
1875 /// argument, as used in AMD64-ABI 3.5.7.
1876 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001877 /// If a word is unused its result will be NoClass; if a type should
1878 /// be passed in Memory then at least the classification of \arg Lo
1879 /// will be Memory.
1880 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001881 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001882 ///
1883 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1884 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001885 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1886 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001887
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001888 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001889 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1890 unsigned IROffset, QualType SourceTy,
1891 unsigned SourceOffset) const;
1892 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1893 unsigned IROffset, QualType SourceTy,
1894 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001895
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001896 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001897 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001898 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001899
1900 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001901 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001902 ///
1903 /// \param freeIntRegs - The number of free integer registers remaining
1904 /// available.
1905 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001906
Chris Lattner458b2aa2010-07-29 02:16:43 +00001907 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001908
Bill Wendling5cd41c42010-10-18 03:41:31 +00001909 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001910 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001911 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001912 unsigned &neededSSE,
1913 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001914
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001915 bool IsIllegalVectorType(QualType Ty) const;
1916
John McCalle0fda732011-04-21 01:20:55 +00001917 /// The 0.98 ABI revision clarified a lot of ambiguities,
1918 /// unfortunately in ways that were not always consistent with
1919 /// certain previous compilers. In particular, platforms which
1920 /// required strict binary compatibility with older versions of GCC
1921 /// may need to exempt themselves.
1922 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001923 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001924 }
1925
David Majnemere2ae2282016-03-04 05:26:16 +00001926 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1927 // compilers require us to classify it as INTEGER.
1928 bool classifyIntegerMMXAsSSE() const {
1929 const llvm::Triple &Triple = getTarget().getTriple();
1930 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1931 return false;
1932 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1933 return false;
1934 return true;
1935 }
1936
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001937 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001938 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1939 // 64-bit hardware.
1940 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001941
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001942public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001943 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001944 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001945 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001946 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001947
John McCalla729c622012-02-17 03:33:10 +00001948 bool isPassedUsingAVXType(QualType type) const {
1949 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001950 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001951 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1952 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001953 if (info.isDirect()) {
1954 llvm::Type *ty = info.getCoerceToType();
1955 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1956 return (vectorTy->getBitWidth() > 128);
1957 }
1958 return false;
1959 }
1960
Craig Topper4f12f102014-03-12 06:41:41 +00001961 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001962
John McCall7f416cc2015-09-08 08:05:57 +00001963 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1964 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001965 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1966 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001967
1968 bool has64BitPointers() const {
1969 return Has64BitPointers;
1970 }
John McCall12f23522016-04-04 18:33:08 +00001971
1972 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1973 ArrayRef<llvm::Type*> scalars,
1974 bool asReturnValue) const override {
1975 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
1976 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001977};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001978
Chris Lattner04dc9572010-08-31 16:44:54 +00001979/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001980class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001981public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001982 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1983 : ABIInfo(CGT),
1984 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001985
Craig Topper4f12f102014-03-12 06:41:41 +00001986 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001987
John McCall7f416cc2015-09-08 08:05:57 +00001988 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1989 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001990
1991 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1992 // FIXME: Assumes vectorcall is in use.
1993 return isX86VectorTypeForVectorCall(getContext(), Ty);
1994 }
1995
1996 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1997 uint64_t NumMembers) const override {
1998 // FIXME: Assumes vectorcall is in use.
1999 return isX86VectorCallAggregateSmallEnough(NumMembers);
2000 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002001
2002private:
2003 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2004 bool IsReturnType) const;
2005
2006 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002007};
2008
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002009class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2010public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002011 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002012 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002013
John McCalla729c622012-02-17 03:33:10 +00002014 const X86_64ABIInfo &getABIInfo() const {
2015 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2016 }
2017
Craig Topper4f12f102014-03-12 06:41:41 +00002018 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002019 return 7;
2020 }
2021
2022 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002023 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002024 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002025
John McCall943fae92010-05-27 06:19:26 +00002026 // 0-15 are the 16 integer registers.
2027 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002028 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002029 return false;
2030 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002031
Jay Foad7c57be32011-07-11 09:56:20 +00002032 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002033 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002034 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002035 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2036 }
2037
John McCalla729c622012-02-17 03:33:10 +00002038 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002039 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002040 // The default CC on x86-64 sets %al to the number of SSA
2041 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002042 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002043 // that when AVX types are involved: the ABI explicitly states it is
2044 // undefined, and it doesn't work in practice because of how the ABI
2045 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002046 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002047 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002048 for (CallArgList::const_iterator
2049 it = args.begin(), ie = args.end(); it != ie; ++it) {
2050 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2051 HasAVXType = true;
2052 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002053 }
2054 }
John McCalla729c622012-02-17 03:33:10 +00002055
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002056 if (!HasAVXType)
2057 return true;
2058 }
John McCallcbc038a2011-09-21 08:08:30 +00002059
John McCalla729c622012-02-17 03:33:10 +00002060 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002061 }
2062
Craig Topper4f12f102014-03-12 06:41:41 +00002063 llvm::Constant *
2064 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002065 unsigned Sig;
2066 if (getABIInfo().has64BitPointers())
2067 Sig = (0xeb << 0) | // jmp rel8
2068 (0x0a << 8) | // .+0x0c
2069 ('F' << 16) |
2070 ('T' << 24);
2071 else
2072 Sig = (0xeb << 0) | // jmp rel8
2073 (0x06 << 8) | // .+0x08
2074 ('F' << 16) |
2075 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002076 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2077 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002078
2079 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2080 CodeGen::CodeGenModule &CGM) const override {
2081 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2082 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2083 llvm::Function *Fn = cast<llvm::Function>(GV);
2084 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2085 }
2086 }
2087 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002088};
2089
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002090class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2091public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002092 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2093 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002094
2095 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002096 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002097 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002098 // If the argument contains a space, enclose it in quotes.
2099 if (Lib.find(" ") != StringRef::npos)
2100 Opt += "\"" + Lib.str() + "\"";
2101 else
2102 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002103 }
2104};
2105
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002106static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002107 // If the argument does not end in .lib, automatically add the suffix.
2108 // If the argument contains a space, enclose it in quotes.
2109 // This matches the behavior of MSVC.
2110 bool Quote = (Lib.find(" ") != StringRef::npos);
2111 std::string ArgStr = Quote ? "\"" : "";
2112 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002113 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002114 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002115 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002116 return ArgStr;
2117}
2118
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002119class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2120public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002121 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002122 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2123 unsigned NumRegisterParameters)
2124 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002125 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002126
Eric Christopher162c91c2015-06-05 22:03:00 +00002127 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002128 CodeGen::CodeGenModule &CGM) const override;
2129
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002130 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002131 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002132 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002133 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002134 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002135
2136 void getDetectMismatchOption(llvm::StringRef Name,
2137 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002138 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002139 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002140 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002141};
2142
Hans Wennborg77dc2362015-01-20 19:45:50 +00002143static void addStackProbeSizeTargetAttribute(const Decl *D,
2144 llvm::GlobalValue *GV,
2145 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002146 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002147 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2148 llvm::Function *Fn = cast<llvm::Function>(GV);
2149
Eric Christopher7565e0d2015-05-29 23:09:49 +00002150 Fn->addFnAttr("stack-probe-size",
2151 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002152 }
2153 }
2154}
2155
Eric Christopher162c91c2015-06-05 22:03:00 +00002156void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002157 llvm::GlobalValue *GV,
2158 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002159 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002160
2161 addStackProbeSizeTargetAttribute(D, GV, CGM);
2162}
2163
Chris Lattner04dc9572010-08-31 16:44:54 +00002164class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2165public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002166 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2167 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002168 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002169
Eric Christopher162c91c2015-06-05 22:03:00 +00002170 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002171 CodeGen::CodeGenModule &CGM) const override;
2172
Craig Topper4f12f102014-03-12 06:41:41 +00002173 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002174 return 7;
2175 }
2176
2177 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002178 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002179 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002180
Chris Lattner04dc9572010-08-31 16:44:54 +00002181 // 0-15 are the 16 integer registers.
2182 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002183 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002184 return false;
2185 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002186
2187 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002188 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002189 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002190 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002191 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002192
2193 void getDetectMismatchOption(llvm::StringRef Name,
2194 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002195 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002196 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002197 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002198};
2199
Eric Christopher162c91c2015-06-05 22:03:00 +00002200void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002201 llvm::GlobalValue *GV,
2202 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002203 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002204
Alexey Bataevd51e9932016-01-15 04:06:31 +00002205 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2206 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2207 llvm::Function *Fn = cast<llvm::Function>(GV);
2208 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2209 }
2210 }
2211
Hans Wennborg77dc2362015-01-20 19:45:50 +00002212 addStackProbeSizeTargetAttribute(D, GV, CGM);
2213}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002214}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002215
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002216void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2217 Class &Hi) const {
2218 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2219 //
2220 // (a) If one of the classes is Memory, the whole argument is passed in
2221 // memory.
2222 //
2223 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2224 // memory.
2225 //
2226 // (c) If the size of the aggregate exceeds two eightbytes and the first
2227 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2228 // argument is passed in memory. NOTE: This is necessary to keep the
2229 // ABI working for processors that don't support the __m256 type.
2230 //
2231 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2232 //
2233 // Some of these are enforced by the merging logic. Others can arise
2234 // only with unions; for example:
2235 // union { _Complex double; unsigned; }
2236 //
2237 // Note that clauses (b) and (c) were added in 0.98.
2238 //
2239 if (Hi == Memory)
2240 Lo = Memory;
2241 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2242 Lo = Memory;
2243 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2244 Lo = Memory;
2245 if (Hi == SSEUp && Lo != SSE)
2246 Hi = SSE;
2247}
2248
Chris Lattnerd776fb12010-06-28 21:43:59 +00002249X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002250 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2251 // classified recursively so that always two fields are
2252 // considered. The resulting class is calculated according to
2253 // the classes of the fields in the eightbyte:
2254 //
2255 // (a) If both classes are equal, this is the resulting class.
2256 //
2257 // (b) If one of the classes is NO_CLASS, the resulting class is
2258 // the other class.
2259 //
2260 // (c) If one of the classes is MEMORY, the result is the MEMORY
2261 // class.
2262 //
2263 // (d) If one of the classes is INTEGER, the result is the
2264 // INTEGER.
2265 //
2266 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2267 // MEMORY is used as class.
2268 //
2269 // (f) Otherwise class SSE is used.
2270
2271 // Accum should never be memory (we should have returned) or
2272 // ComplexX87 (because this cannot be passed in a structure).
2273 assert((Accum != Memory && Accum != ComplexX87) &&
2274 "Invalid accumulated classification during merge.");
2275 if (Accum == Field || Field == NoClass)
2276 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002277 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002278 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002279 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002280 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002281 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002282 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002283 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2284 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002285 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002286 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002287}
2288
Chris Lattner5c740f12010-06-30 19:14:05 +00002289void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002290 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002291 // FIXME: This code can be simplified by introducing a simple value class for
2292 // Class pairs with appropriate constructor methods for the various
2293 // situations.
2294
2295 // FIXME: Some of the split computations are wrong; unaligned vectors
2296 // shouldn't be passed in registers for example, so there is no chance they
2297 // can straddle an eightbyte. Verify & simplify.
2298
2299 Lo = Hi = NoClass;
2300
2301 Class &Current = OffsetBase < 64 ? Lo : Hi;
2302 Current = Memory;
2303
John McCall9dd450b2009-09-21 23:43:11 +00002304 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002305 BuiltinType::Kind k = BT->getKind();
2306
2307 if (k == BuiltinType::Void) {
2308 Current = NoClass;
2309 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2310 Lo = Integer;
2311 Hi = Integer;
2312 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2313 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002314 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002315 Current = SSE;
2316 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002317 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2318 if (LDF == &llvm::APFloat::IEEEquad) {
2319 Lo = SSE;
2320 Hi = SSEUp;
2321 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2322 Lo = X87;
2323 Hi = X87Up;
2324 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2325 Current = SSE;
2326 } else
2327 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002328 }
2329 // FIXME: _Decimal32 and _Decimal64 are SSE.
2330 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002331 return;
2332 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002333
Chris Lattnerd776fb12010-06-28 21:43:59 +00002334 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002335 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002336 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002337 return;
2338 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002339
Chris Lattnerd776fb12010-06-28 21:43:59 +00002340 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002341 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002342 return;
2343 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002344
Chris Lattnerd776fb12010-06-28 21:43:59 +00002345 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002346 if (Ty->isMemberFunctionPointerType()) {
2347 if (Has64BitPointers) {
2348 // If Has64BitPointers, this is an {i64, i64}, so classify both
2349 // Lo and Hi now.
2350 Lo = Hi = Integer;
2351 } else {
2352 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2353 // straddles an eightbyte boundary, Hi should be classified as well.
2354 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2355 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2356 if (EB_FuncPtr != EB_ThisAdj) {
2357 Lo = Hi = Integer;
2358 } else {
2359 Current = Integer;
2360 }
2361 }
2362 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002363 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002364 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002365 return;
2366 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002367
Chris Lattnerd776fb12010-06-28 21:43:59 +00002368 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002369 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002370 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2371 // gcc passes the following as integer:
2372 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2373 // 2 bytes - <2 x char>, <1 x short>
2374 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002375 Current = Integer;
2376
2377 // If this type crosses an eightbyte boundary, it should be
2378 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002379 uint64_t EB_Lo = (OffsetBase) / 64;
2380 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2381 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002382 Hi = Lo;
2383 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002384 QualType ElementType = VT->getElementType();
2385
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002386 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002387 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002388 return;
2389
David Majnemere2ae2282016-03-04 05:26:16 +00002390 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2391 // pass them as integer. For platforms where clang is the de facto
2392 // platform compiler, we must continue to use integer.
2393 if (!classifyIntegerMMXAsSSE() &&
2394 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2395 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2396 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2397 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002398 Current = Integer;
2399 else
2400 Current = SSE;
2401
2402 // If this type crosses an eightbyte boundary, it should be
2403 // split.
2404 if (OffsetBase && OffsetBase != 64)
2405 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002406 } else if (Size == 128 ||
2407 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002408 // Arguments of 256-bits are split into four eightbyte chunks. The
2409 // least significant one belongs to class SSE and all the others to class
2410 // SSEUP. The original Lo and Hi design considers that types can't be
2411 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2412 // This design isn't correct for 256-bits, but since there're no cases
2413 // where the upper parts would need to be inspected, avoid adding
2414 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002415 //
2416 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2417 // registers if they are "named", i.e. not part of the "..." of a
2418 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002419 //
2420 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2421 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002422 Lo = SSE;
2423 Hi = SSEUp;
2424 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002425 return;
2426 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002427
Chris Lattnerd776fb12010-06-28 21:43:59 +00002428 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002429 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002430
Chris Lattner2b037972010-07-29 02:01:43 +00002431 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002432 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002433 if (Size <= 64)
2434 Current = Integer;
2435 else if (Size <= 128)
2436 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002437 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002438 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002439 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002440 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002441 } else if (ET == getContext().LongDoubleTy) {
2442 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2443 if (LDF == &llvm::APFloat::IEEEquad)
2444 Current = Memory;
2445 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2446 Current = ComplexX87;
2447 else if (LDF == &llvm::APFloat::IEEEdouble)
2448 Lo = Hi = SSE;
2449 else
2450 llvm_unreachable("unexpected long double representation!");
2451 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002452
2453 // If this complex type crosses an eightbyte boundary then it
2454 // should be split.
2455 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002456 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002457 if (Hi == NoClass && EB_Real != EB_Imag)
2458 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002459
Chris Lattnerd776fb12010-06-28 21:43:59 +00002460 return;
2461 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002462
Chris Lattner2b037972010-07-29 02:01:43 +00002463 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002464 // Arrays are treated like structures.
2465
Chris Lattner2b037972010-07-29 02:01:43 +00002466 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002467
2468 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002469 // than four eightbytes, ..., it has class MEMORY.
2470 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002471 return;
2472
2473 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2474 // fields, it has class MEMORY.
2475 //
2476 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002477 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002478 return;
2479
2480 // Otherwise implement simplified merge. We could be smarter about
2481 // this, but it isn't worth it and would be harder to verify.
2482 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002483 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002484 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002485
2486 // The only case a 256-bit wide vector could be used is when the array
2487 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2488 // to work for sizes wider than 128, early check and fallback to memory.
2489 if (Size > 128 && EltSize != 256)
2490 return;
2491
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002492 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2493 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002494 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002495 Lo = merge(Lo, FieldLo);
2496 Hi = merge(Hi, FieldHi);
2497 if (Lo == Memory || Hi == Memory)
2498 break;
2499 }
2500
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002501 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002502 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002503 return;
2504 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002505
Chris Lattnerd776fb12010-06-28 21:43:59 +00002506 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002507 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002508
2509 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002510 // than four eightbytes, ..., it has class MEMORY.
2511 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002512 return;
2513
Anders Carlsson20759ad2009-09-16 15:53:40 +00002514 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2515 // copy constructor or a non-trivial destructor, it is passed by invisible
2516 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002517 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002518 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002519
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002520 const RecordDecl *RD = RT->getDecl();
2521
2522 // Assume variable sized types are passed in memory.
2523 if (RD->hasFlexibleArrayMember())
2524 return;
2525
Chris Lattner2b037972010-07-29 02:01:43 +00002526 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527
2528 // Reset Lo class, this will be recomputed.
2529 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002530
2531 // If this is a C++ record, classify the bases first.
2532 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002533 for (const auto &I : CXXRD->bases()) {
2534 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002535 "Unexpected base class!");
2536 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002537 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002538
2539 // Classify this field.
2540 //
2541 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2542 // single eightbyte, each is classified separately. Each eightbyte gets
2543 // initialized to class NO_CLASS.
2544 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002545 uint64_t Offset =
2546 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002547 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002548 Lo = merge(Lo, FieldLo);
2549 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002550 if (Lo == Memory || Hi == Memory) {
2551 postMerge(Size, Lo, Hi);
2552 return;
2553 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002554 }
2555 }
2556
2557 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002559 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002560 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002561 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2562 bool BitField = i->isBitField();
2563
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002564 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2565 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002567 // The only case a 256-bit wide vector could be used is when the struct
2568 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2569 // to work for sizes wider than 128, early check and fallback to memory.
2570 //
2571 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2572 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002573 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002574 return;
2575 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002576 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002577 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002578 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002579 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002580 return;
2581 }
2582
2583 // Classify this field.
2584 //
2585 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2586 // exceeds a single eightbyte, each is classified
2587 // separately. Each eightbyte gets initialized to class
2588 // NO_CLASS.
2589 Class FieldLo, FieldHi;
2590
2591 // Bit-fields require special handling, they do not force the
2592 // structure to be passed in memory even if unaligned, and
2593 // therefore they can straddle an eightbyte.
2594 if (BitField) {
2595 // Ignore padding bit-fields.
2596 if (i->isUnnamedBitfield())
2597 continue;
2598
2599 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002600 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002601
2602 uint64_t EB_Lo = Offset / 64;
2603 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002604
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002605 if (EB_Lo) {
2606 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2607 FieldLo = NoClass;
2608 FieldHi = Integer;
2609 } else {
2610 FieldLo = Integer;
2611 FieldHi = EB_Hi ? Integer : NoClass;
2612 }
2613 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002614 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002615 Lo = merge(Lo, FieldLo);
2616 Hi = merge(Hi, FieldHi);
2617 if (Lo == Memory || Hi == Memory)
2618 break;
2619 }
2620
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002621 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 }
2623}
2624
Chris Lattner22a931e2010-06-29 06:01:59 +00002625ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002626 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2627 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002628 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002629 // Treat an enum type as its underlying type.
2630 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2631 Ty = EnumTy->getDecl()->getIntegerType();
2632
2633 return (Ty->isPromotableIntegerType() ?
2634 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2635 }
2636
John McCall7f416cc2015-09-08 08:05:57 +00002637 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002638}
2639
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002640bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2641 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2642 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002643 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002644 if (Size <= 64 || Size > LargestVector)
2645 return true;
2646 }
2647
2648 return false;
2649}
2650
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002651ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2652 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2654 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002655 //
2656 // This assumption is optimistic, as there could be free registers available
2657 // when we need to pass this argument in memory, and LLVM could try to pass
2658 // the argument in the free register. This does not seem to happen currently,
2659 // but this code would be much safer if we could mark the argument with
2660 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002661 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002662 // Treat an enum type as its underlying type.
2663 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2664 Ty = EnumTy->getDecl()->getIntegerType();
2665
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002666 return (Ty->isPromotableIntegerType() ?
2667 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002668 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002669
Mark Lacey3825e832013-10-06 01:33:34 +00002670 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002671 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002672
Chris Lattner44c2b902011-05-22 23:21:23 +00002673 // Compute the byval alignment. We specify the alignment of the byval in all
2674 // cases so that the mid-level optimizer knows the alignment of the byval.
2675 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002676
2677 // Attempt to avoid passing indirect results using byval when possible. This
2678 // is important for good codegen.
2679 //
2680 // We do this by coercing the value into a scalar type which the backend can
2681 // handle naturally (i.e., without using byval).
2682 //
2683 // For simplicity, we currently only do this when we have exhausted all of the
2684 // free integer registers. Doing this when there are free integer registers
2685 // would require more care, as we would have to ensure that the coerced value
2686 // did not claim the unused register. That would require either reording the
2687 // arguments to the function (so that any subsequent inreg values came first),
2688 // or only doing this optimization when there were no following arguments that
2689 // might be inreg.
2690 //
2691 // We currently expect it to be rare (particularly in well written code) for
2692 // arguments to be passed on the stack when there are still free integer
2693 // registers available (this would typically imply large structs being passed
2694 // by value), so this seems like a fair tradeoff for now.
2695 //
2696 // We can revisit this if the backend grows support for 'onstack' parameter
2697 // attributes. See PR12193.
2698 if (freeIntRegs == 0) {
2699 uint64_t Size = getContext().getTypeSize(Ty);
2700
2701 // If this type fits in an eightbyte, coerce it into the matching integral
2702 // type, which will end up on the stack (with alignment 8).
2703 if (Align == 8 && Size <= 64)
2704 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2705 Size));
2706 }
2707
John McCall7f416cc2015-09-08 08:05:57 +00002708 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002709}
2710
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002711/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2712/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002713llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002714 // Wrapper structs/arrays that only contain vectors are passed just like
2715 // vectors; strip them off if present.
2716 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2717 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002718
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002719 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002720 if (isa<llvm::VectorType>(IRType) ||
2721 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002722 return IRType;
2723
2724 // We couldn't find the preferred IR vector type for 'Ty'.
2725 uint64_t Size = getContext().getTypeSize(Ty);
2726 assert((Size == 128 || Size == 256) && "Invalid type found!");
2727
2728 // Return a LLVM IR vector type based on the size of 'Ty'.
2729 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2730 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002731}
2732
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002733/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2734/// is known to either be off the end of the specified type or being in
2735/// alignment padding. The user type specified is known to be at most 128 bits
2736/// in size, and have passed through X86_64ABIInfo::classify with a successful
2737/// classification that put one of the two halves in the INTEGER class.
2738///
2739/// It is conservatively correct to return false.
2740static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2741 unsigned EndBit, ASTContext &Context) {
2742 // If the bytes being queried are off the end of the type, there is no user
2743 // data hiding here. This handles analysis of builtins, vectors and other
2744 // types that don't contain interesting padding.
2745 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2746 if (TySize <= StartBit)
2747 return true;
2748
Chris Lattner98076a22010-07-29 07:43:55 +00002749 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2750 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2751 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2752
2753 // Check each element to see if the element overlaps with the queried range.
2754 for (unsigned i = 0; i != NumElts; ++i) {
2755 // If the element is after the span we care about, then we're done..
2756 unsigned EltOffset = i*EltSize;
2757 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002758
Chris Lattner98076a22010-07-29 07:43:55 +00002759 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2760 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2761 EndBit-EltOffset, Context))
2762 return false;
2763 }
2764 // If it overlaps no elements, then it is safe to process as padding.
2765 return true;
2766 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002767
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002768 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2769 const RecordDecl *RD = RT->getDecl();
2770 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002771
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002772 // If this is a C++ record, check the bases first.
2773 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002774 for (const auto &I : CXXRD->bases()) {
2775 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002776 "Unexpected base class!");
2777 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002778 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002779
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002780 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002781 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002782 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002783
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002784 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002785 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002786 EndBit-BaseOffset, Context))
2787 return false;
2788 }
2789 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002790
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002791 // Verify that no field has data that overlaps the region of interest. Yes
2792 // this could be sped up a lot by being smarter about queried fields,
2793 // however we're only looking at structs up to 16 bytes, so we don't care
2794 // much.
2795 unsigned idx = 0;
2796 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2797 i != e; ++i, ++idx) {
2798 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002799
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002800 // If we found a field after the region we care about, then we're done.
2801 if (FieldOffset >= EndBit) break;
2802
2803 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2804 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2805 Context))
2806 return false;
2807 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002808
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002809 // If nothing in this record overlapped the area of interest, then we're
2810 // clean.
2811 return true;
2812 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002813
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002814 return false;
2815}
2816
Chris Lattnere556a712010-07-29 18:39:32 +00002817/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2818/// float member at the specified offset. For example, {int,{float}} has a
2819/// float at offset 4. It is conservatively correct for this routine to return
2820/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002821static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002822 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002823 // Base case if we find a float.
2824 if (IROffset == 0 && IRType->isFloatTy())
2825 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002826
Chris Lattnere556a712010-07-29 18:39:32 +00002827 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002828 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002829 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2830 unsigned Elt = SL->getElementContainingOffset(IROffset);
2831 IROffset -= SL->getElementOffset(Elt);
2832 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2833 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002834
Chris Lattnere556a712010-07-29 18:39:32 +00002835 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002836 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2837 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002838 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2839 IROffset -= IROffset/EltSize*EltSize;
2840 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2841 }
2842
2843 return false;
2844}
2845
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002846
2847/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2848/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002849llvm::Type *X86_64ABIInfo::
2850GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002851 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002852 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002853 // pass as float if the last 4 bytes is just padding. This happens for
2854 // structs that contain 3 floats.
2855 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2856 SourceOffset*8+64, getContext()))
2857 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002858
Chris Lattnere556a712010-07-29 18:39:32 +00002859 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2860 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2861 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002862 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2863 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002864 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002865
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002866 return llvm::Type::getDoubleTy(getVMContext());
2867}
2868
2869
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002870/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2871/// an 8-byte GPR. This means that we either have a scalar or we are talking
2872/// about the high or low part of an up-to-16-byte struct. This routine picks
2873/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002874/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2875/// etc).
2876///
2877/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2878/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2879/// the 8-byte value references. PrefType may be null.
2880///
Alp Toker9907f082014-07-09 14:06:35 +00002881/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002882/// an offset into this that we're processing (which is always either 0 or 8).
2883///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002884llvm::Type *X86_64ABIInfo::
2885GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002886 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002887 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2888 // returning an 8-byte unit starting with it. See if we can safely use it.
2889 if (IROffset == 0) {
2890 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002891 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2892 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002893 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002894
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002895 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2896 // goodness in the source type is just tail padding. This is allowed to
2897 // kick in for struct {double,int} on the int, but not on
2898 // struct{double,int,int} because we wouldn't return the second int. We
2899 // have to do this analysis on the source type because we can't depend on
2900 // unions being lowered a specific way etc.
2901 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002902 IRType->isIntegerTy(32) ||
2903 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2904 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2905 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002906
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002907 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2908 SourceOffset*8+64, getContext()))
2909 return IRType;
2910 }
2911 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002912
Chris Lattner2192fe52011-07-18 04:24:23 +00002913 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002914 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002915 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002916 if (IROffset < SL->getSizeInBytes()) {
2917 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2918 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002919
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002920 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2921 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002922 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002923 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002924
Chris Lattner2192fe52011-07-18 04:24:23 +00002925 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002926 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002927 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002928 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002929 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2930 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002931 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002932
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002933 // Okay, we don't have any better idea of what to pass, so we pass this in an
2934 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002935 unsigned TySizeInBytes =
2936 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002937
Chris Lattner3f763422010-07-29 17:34:39 +00002938 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002939
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002940 // It is always safe to classify this as an integer type up to i64 that
2941 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002942 return llvm::IntegerType::get(getVMContext(),
2943 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002944}
2945
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002946
2947/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2948/// be used as elements of a two register pair to pass or return, return a
2949/// first class aggregate to represent them. For example, if the low part of
2950/// a by-value argument should be passed as i32* and the high part as float,
2951/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002952static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002953GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002954 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002955 // In order to correctly satisfy the ABI, we need to the high part to start
2956 // at offset 8. If the high and low parts we inferred are both 4-byte types
2957 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2958 // the second element at offset 8. Check for this:
2959 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2960 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002961 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002962 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002963
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002964 // To handle this, we have to increase the size of the low part so that the
2965 // second element will start at an 8 byte offset. We can't increase the size
2966 // of the second element because it might make us access off the end of the
2967 // struct.
2968 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002969 // There are usually two sorts of types the ABI generation code can produce
2970 // for the low part of a pair that aren't 8 bytes in size: float or
2971 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2972 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002973 // Promote these to a larger type.
2974 if (Lo->isFloatTy())
2975 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2976 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002977 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2978 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002979 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2980 }
2981 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002982
Reid Kleckneree7cf842014-12-01 22:02:27 +00002983 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002984
2985
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002986 // Verify that the second element is at an 8-byte offset.
2987 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2988 "Invalid x86-64 argument pair!");
2989 return Result;
2990}
2991
Chris Lattner31faff52010-07-28 23:06:14 +00002992ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002993classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002994 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2995 // classification algorithm.
2996 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002997 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002998
2999 // Check some invariants.
3000 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003001 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3002
Craig Topper8a13c412014-05-21 05:09:00 +00003003 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003004 switch (Lo) {
3005 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003006 if (Hi == NoClass)
3007 return ABIArgInfo::getIgnore();
3008 // If the low part is just padding, it takes no register, leave ResType
3009 // null.
3010 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3011 "Unknown missing lo part");
3012 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003013
3014 case SSEUp:
3015 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003016 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003017
3018 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3019 // hidden argument.
3020 case Memory:
3021 return getIndirectReturnResult(RetTy);
3022
3023 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3024 // available register of the sequence %rax, %rdx is used.
3025 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003026 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003027
Chris Lattner1f3a0632010-07-29 21:42:50 +00003028 // If we have a sign or zero extended integer, make sure to return Extend
3029 // so that the parameter gets the right LLVM IR attributes.
3030 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3031 // Treat an enum type as its underlying type.
3032 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3033 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003034
Chris Lattner1f3a0632010-07-29 21:42:50 +00003035 if (RetTy->isIntegralOrEnumerationType() &&
3036 RetTy->isPromotableIntegerType())
3037 return ABIArgInfo::getExtend();
3038 }
Chris Lattner31faff52010-07-28 23:06:14 +00003039 break;
3040
3041 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3042 // available SSE register of the sequence %xmm0, %xmm1 is used.
3043 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003044 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003045 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003046
3047 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3048 // returned on the X87 stack in %st0 as 80-bit x87 number.
3049 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003050 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003051 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003052
3053 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3054 // part of the value is returned in %st0 and the imaginary part in
3055 // %st1.
3056 case ComplexX87:
3057 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003058 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003059 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003060 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003061 break;
3062 }
3063
Craig Topper8a13c412014-05-21 05:09:00 +00003064 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003065 switch (Hi) {
3066 // Memory was handled previously and X87 should
3067 // never occur as a hi class.
3068 case Memory:
3069 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003070 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003071
3072 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003073 case NoClass:
3074 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003075
Chris Lattner52b3c132010-09-01 00:20:33 +00003076 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003077 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003078 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3079 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003080 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003081 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003082 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003083 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3084 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003085 break;
3086
3087 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003088 // is passed in the next available eightbyte chunk if the last used
3089 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003090 //
Chris Lattner57540c52011-04-15 05:22:18 +00003091 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003092 case SSEUp:
3093 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003094 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003095 break;
3096
3097 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3098 // returned together with the previous X87 value in %st0.
3099 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003100 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003101 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003102 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003103 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003104 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003105 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003106 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3107 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003108 }
Chris Lattner31faff52010-07-28 23:06:14 +00003109 break;
3110 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003111
Chris Lattner52b3c132010-09-01 00:20:33 +00003112 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003113 // known to pass in the high eightbyte of the result. We do this by forming a
3114 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003115 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003116 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003117
Chris Lattner1f3a0632010-07-29 21:42:50 +00003118 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003119}
3120
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003121ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003122 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3123 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003124 const
3125{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003126 Ty = useFirstFieldIfTransparentUnion(Ty);
3127
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003128 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003129 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003130
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131 // Check some invariants.
3132 // FIXME: Enforce these by construction.
3133 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003134 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3135
3136 neededInt = 0;
3137 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003138 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003139 switch (Lo) {
3140 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003141 if (Hi == NoClass)
3142 return ABIArgInfo::getIgnore();
3143 // If the low part is just padding, it takes no register, leave ResType
3144 // null.
3145 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3146 "Unknown missing lo part");
3147 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003148
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003149 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3150 // on the stack.
3151 case Memory:
3152
3153 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3154 // COMPLEX_X87, it is passed in memory.
3155 case X87:
3156 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003157 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003158 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003159 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003160
3161 case SSEUp:
3162 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003163 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003164
3165 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3166 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3167 // and %r9 is used.
3168 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003169 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003170
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003171 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003172 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003173
3174 // If we have a sign or zero extended integer, make sure to return Extend
3175 // so that the parameter gets the right LLVM IR attributes.
3176 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3177 // Treat an enum type as its underlying type.
3178 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3179 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003180
Chris Lattner1f3a0632010-07-29 21:42:50 +00003181 if (Ty->isIntegralOrEnumerationType() &&
3182 Ty->isPromotableIntegerType())
3183 return ABIArgInfo::getExtend();
3184 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003185
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003186 break;
3187
3188 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3189 // available SSE register is used, the registers are taken in the
3190 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003191 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003192 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003193 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003194 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003195 break;
3196 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003197 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003198
Craig Topper8a13c412014-05-21 05:09:00 +00003199 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003200 switch (Hi) {
3201 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003202 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003203 // which is passed in memory.
3204 case Memory:
3205 case X87:
3206 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003207 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208
3209 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003210
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003211 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003212 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003213 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003214 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003215
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003216 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3217 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003218 break;
3219
3220 // X87Up generally doesn't occur here (long double is passed in
3221 // memory), except in situations involving unions.
3222 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003223 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003224 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003225
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003226 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3227 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003228
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003229 ++neededSSE;
3230 break;
3231
3232 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3233 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003234 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003235 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003236 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003237 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003238 break;
3239 }
3240
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003241 // If a high part was specified, merge it together with the low part. It is
3242 // known to pass in the high eightbyte of the result. We do this by forming a
3243 // first class struct aggregate with the high and low part: {low, high}
3244 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003245 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003246
Chris Lattner1f3a0632010-07-29 21:42:50 +00003247 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003248}
3249
Chris Lattner22326a12010-07-29 02:31:05 +00003250void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003251
Reid Kleckner40ca9132014-05-13 22:05:45 +00003252 if (!getCXXABI().classifyReturnType(FI))
3253 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003254
3255 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003256 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003257
3258 // If the return value is indirect, then the hidden argument is consuming one
3259 // integer register.
3260 if (FI.getReturnInfo().isIndirect())
3261 --freeIntRegs;
3262
Peter Collingbournef7706832014-12-12 23:41:25 +00003263 // The chain argument effectively gives us another free register.
3264 if (FI.isChainCall())
3265 ++freeIntRegs;
3266
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003267 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003268 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3269 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003270 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003271 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003272 it != ie; ++it, ++ArgNo) {
3273 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003274
Bill Wendling9987c0e2010-10-18 23:51:38 +00003275 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003276 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003277 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003278
3279 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3280 // eightbyte of an argument, the whole argument is passed on the
3281 // stack. If registers have already been assigned for some
3282 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003283 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003284 freeIntRegs -= neededInt;
3285 freeSSERegs -= neededSSE;
3286 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003287 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003288 }
3289 }
3290}
3291
John McCall7f416cc2015-09-08 08:05:57 +00003292static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3293 Address VAListAddr, QualType Ty) {
3294 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3295 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003296 llvm::Value *overflow_arg_area =
3297 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3298
3299 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3300 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003301 // It isn't stated explicitly in the standard, but in practice we use
3302 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003303 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3304 if (Align > CharUnits::fromQuantity(8)) {
3305 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3306 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003307 }
3308
3309 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003310 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003311 llvm::Value *Res =
3312 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003313 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003314
3315 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3316 // l->overflow_arg_area + sizeof(type).
3317 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3318 // an 8 byte boundary.
3319
3320 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003321 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003322 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003323 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3324 "overflow_arg_area.next");
3325 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3326
3327 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003328 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003329}
3330
John McCall7f416cc2015-09-08 08:05:57 +00003331Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3332 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003333 // Assume that va_list type is correct; should be pointer to LLVM type:
3334 // struct {
3335 // i32 gp_offset;
3336 // i32 fp_offset;
3337 // i8* overflow_arg_area;
3338 // i8* reg_save_area;
3339 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003340 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003341
John McCall7f416cc2015-09-08 08:05:57 +00003342 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003343 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003344 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003345
3346 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3347 // in the registers. If not go to step 7.
3348 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003349 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003350
3351 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3352 // general purpose registers needed to pass type and num_fp to hold
3353 // the number of floating point registers needed.
3354
3355 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3356 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3357 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3358 //
3359 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3360 // register save space).
3361
Craig Topper8a13c412014-05-21 05:09:00 +00003362 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003363 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3364 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003365 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003366 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003367 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3368 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003369 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003370 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3371 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003372 }
3373
3374 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003375 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003376 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3377 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003378 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3379 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003380 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3381 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003382 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3383 }
3384
3385 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3386 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3387 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3388 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3389
3390 // Emit code to load the value if it was passed in registers.
3391
3392 CGF.EmitBlock(InRegBlock);
3393
3394 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3395 // an offset of l->gp_offset and/or l->fp_offset. This may require
3396 // copying to a temporary location in case the parameter is passed
3397 // in different register classes or requires an alignment greater
3398 // than 8 for general purpose registers and 16 for XMM registers.
3399 //
3400 // FIXME: This really results in shameful code when we end up needing to
3401 // collect arguments from different places; often what should result in a
3402 // simple assembling of a structure from scattered addresses has many more
3403 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003404 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003405 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3406 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3407 "reg_save_area");
3408
3409 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003410 if (neededInt && neededSSE) {
3411 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003412 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003413 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003414 Address Tmp = CGF.CreateMemTemp(Ty);
3415 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003416 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003417 llvm::Type *TyLo = ST->getElementType(0);
3418 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003419 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003420 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003421 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3422 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003423 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3424 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003425 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3426 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003427
John McCall7f416cc2015-09-08 08:05:57 +00003428 // Copy the first element.
3429 llvm::Value *V =
3430 CGF.Builder.CreateDefaultAlignedLoad(
3431 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3432 CGF.Builder.CreateStore(V,
3433 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3434
3435 // Copy the second element.
3436 V = CGF.Builder.CreateDefaultAlignedLoad(
3437 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3438 CharUnits Offset = CharUnits::fromQuantity(
3439 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3440 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3441
3442 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003443 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003444 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3445 CharUnits::fromQuantity(8));
3446 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003447
3448 // Copy to a temporary if necessary to ensure the appropriate alignment.
3449 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003450 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003451 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003452 CharUnits TyAlign = SizeAlign.second;
3453
3454 // Copy into a temporary if the type is more aligned than the
3455 // register save area.
3456 if (TyAlign.getQuantity() > 8) {
3457 Address Tmp = CGF.CreateMemTemp(Ty);
3458 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003459 RegAddr = Tmp;
3460 }
John McCall7f416cc2015-09-08 08:05:57 +00003461
Chris Lattner0cf24192010-06-28 20:05:43 +00003462 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003463 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3464 CharUnits::fromQuantity(16));
3465 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003466 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003467 assert(neededSSE == 2 && "Invalid number of needed registers!");
3468 // SSE registers are spaced 16 bytes apart in the register save
3469 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003470 // The ABI isn't explicit about this, but it seems reasonable
3471 // to assume that the slots are 16-byte aligned, since the stack is
3472 // naturally 16-byte aligned and the prologue is expected to store
3473 // all the SSE registers to the RSA.
3474 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3475 CharUnits::fromQuantity(16));
3476 Address RegAddrHi =
3477 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3478 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003479 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003480 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003481 llvm::Value *V;
3482 Address Tmp = CGF.CreateMemTemp(Ty);
3483 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3484 V = CGF.Builder.CreateLoad(
3485 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3486 CGF.Builder.CreateStore(V,
3487 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3488 V = CGF.Builder.CreateLoad(
3489 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3490 CGF.Builder.CreateStore(V,
3491 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3492
3493 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003494 }
3495
3496 // AMD64-ABI 3.5.7p5: Step 5. Set:
3497 // l->gp_offset = l->gp_offset + num_gp * 8
3498 // l->fp_offset = l->fp_offset + num_fp * 16.
3499 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003500 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003501 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3502 gp_offset_p);
3503 }
3504 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003505 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003506 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3507 fp_offset_p);
3508 }
3509 CGF.EmitBranch(ContBlock);
3510
3511 // Emit code to load the value if it was passed in memory.
3512
3513 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003514 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003515
3516 // Return the appropriate result.
3517
3518 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003519 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3520 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003521 return ResAddr;
3522}
3523
Charles Davisc7d5c942015-09-17 20:55:33 +00003524Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3525 QualType Ty) const {
3526 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3527 CGF.getContext().getTypeInfoInChars(Ty),
3528 CharUnits::fromQuantity(8),
3529 /*allowHigherAlign*/ false);
3530}
3531
Reid Kleckner80944df2014-10-31 22:00:51 +00003532ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3533 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003534
3535 if (Ty->isVoidType())
3536 return ABIArgInfo::getIgnore();
3537
3538 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3539 Ty = EnumTy->getDecl()->getIntegerType();
3540
Reid Kleckner80944df2014-10-31 22:00:51 +00003541 TypeInfo Info = getContext().getTypeInfo(Ty);
3542 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003543 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003544
Reid Kleckner9005f412014-05-02 00:51:20 +00003545 const RecordType *RT = Ty->getAs<RecordType>();
3546 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003547 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003548 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003549 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003550 }
3551
3552 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003553 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003554
Reid Kleckner9005f412014-05-02 00:51:20 +00003555 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003556
Reid Kleckner80944df2014-10-31 22:00:51 +00003557 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3558 // other targets.
3559 const Type *Base = nullptr;
3560 uint64_t NumElts = 0;
3561 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3562 if (FreeSSERegs >= NumElts) {
3563 FreeSSERegs -= NumElts;
3564 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3565 return ABIArgInfo::getDirect();
3566 return ABIArgInfo::getExpand();
3567 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003568 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003569 }
3570
3571
Reid Klecknerec87fec2014-05-02 01:17:12 +00003572 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003573 // If the member pointer is represented by an LLVM int or ptr, pass it
3574 // directly.
3575 llvm::Type *LLTy = CGT.ConvertType(Ty);
3576 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3577 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003578 }
3579
Michael Kuperstein4f818702015-02-24 09:35:58 +00003580 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003581 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3582 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003583 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003584 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003585
Reid Kleckner9005f412014-05-02 00:51:20 +00003586 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003587 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003588 }
3589
Julien Lerouge10dcff82014-08-27 00:36:55 +00003590 // Bool type is always extended to the ABI, other builtin types are not
3591 // extended.
3592 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3593 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003594 return ABIArgInfo::getExtend();
3595
Reid Kleckner11a17192015-10-28 22:29:52 +00003596 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3597 // passes them indirectly through memory.
3598 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3599 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3600 if (LDF == &llvm::APFloat::x87DoubleExtended)
3601 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3602 }
3603
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003604 return ABIArgInfo::getDirect();
3605}
3606
3607void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003608 bool IsVectorCall =
3609 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003610
Reid Kleckner80944df2014-10-31 22:00:51 +00003611 // We can use up to 4 SSE return registers with vectorcall.
3612 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3613 if (!getCXXABI().classifyReturnType(FI))
3614 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3615
3616 // We can use up to 6 SSE register parameters with vectorcall.
3617 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003618 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003619 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003620}
3621
John McCall7f416cc2015-09-08 08:05:57 +00003622Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3623 QualType Ty) const {
3624 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3625 CGF.getContext().getTypeInfoInChars(Ty),
3626 CharUnits::fromQuantity(8),
3627 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003628}
Chris Lattner0cf24192010-06-28 20:05:43 +00003629
John McCallea8d8bb2010-03-11 00:10:12 +00003630// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003631namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003632/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3633class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003634bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003635public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003636 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3637 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003638
John McCall7f416cc2015-09-08 08:05:57 +00003639 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3640 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003641};
3642
3643class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3644public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003645 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3646 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003647
Craig Topper4f12f102014-03-12 06:41:41 +00003648 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003649 // This is recovered from gcc output.
3650 return 1; // r1 is the dedicated stack pointer
3651 }
3652
3653 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003654 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003655};
3656
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003657}
John McCallea8d8bb2010-03-11 00:10:12 +00003658
James Y Knight29b5f082016-02-24 02:59:33 +00003659// TODO: this implementation is now likely redundant with
3660// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003661Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3662 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003663 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003664 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3665 // TODO: Implement this. For now ignore.
3666 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003667 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003668 }
3669
John McCall7f416cc2015-09-08 08:05:57 +00003670 // struct __va_list_tag {
3671 // unsigned char gpr;
3672 // unsigned char fpr;
3673 // unsigned short reserved;
3674 // void *overflow_arg_area;
3675 // void *reg_save_area;
3676 // };
3677
Roman Divacky8a12d842014-11-03 18:32:54 +00003678 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003679 bool isInt =
3680 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003681 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003682
3683 // All aggregates are passed indirectly? That doesn't seem consistent
3684 // with the argument-lowering code.
3685 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003686
3687 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003688
3689 // The calling convention either uses 1-2 GPRs or 1 FPR.
3690 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003691 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003692 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3693 } else {
3694 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003695 }
John McCall7f416cc2015-09-08 08:05:57 +00003696
3697 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3698
3699 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003700 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003701 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3702 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3703 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003704
Eric Christopher7565e0d2015-05-29 23:09:49 +00003705 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003706 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003707
3708 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3709 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3710 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3711
3712 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3713
John McCall7f416cc2015-09-08 08:05:57 +00003714 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3715 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003716
John McCall7f416cc2015-09-08 08:05:57 +00003717 // Case 1: consume registers.
3718 Address RegAddr = Address::invalid();
3719 {
3720 CGF.EmitBlock(UsingRegs);
3721
3722 Address RegSaveAreaPtr =
3723 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3724 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3725 CharUnits::fromQuantity(8));
3726 assert(RegAddr.getElementType() == CGF.Int8Ty);
3727
3728 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003729 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003730 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3731 CharUnits::fromQuantity(32));
3732 }
3733
3734 // Get the address of the saved value by scaling the number of
3735 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003736 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003737 llvm::Value *RegOffset =
3738 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3739 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3740 RegAddr.getPointer(), RegOffset),
3741 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3742 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3743
3744 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003745 NumRegs =
3746 Builder.CreateAdd(NumRegs,
3747 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003748 Builder.CreateStore(NumRegs, NumRegsAddr);
3749
3750 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003751 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003752
John McCall7f416cc2015-09-08 08:05:57 +00003753 // Case 2: consume space in the overflow area.
3754 Address MemAddr = Address::invalid();
3755 {
3756 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003757
Roman Divacky039b9702016-02-20 08:31:24 +00003758 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3759
John McCall7f416cc2015-09-08 08:05:57 +00003760 // Everything in the overflow area is rounded up to a size of at least 4.
3761 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3762
3763 CharUnits Size;
3764 if (!isIndirect) {
3765 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003766 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003767 } else {
3768 Size = CGF.getPointerSize();
3769 }
3770
3771 Address OverflowAreaAddr =
3772 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003773 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003774 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003775 // Round up address of argument to alignment
3776 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3777 if (Align > OverflowAreaAlign) {
3778 llvm::Value *Ptr = OverflowArea.getPointer();
3779 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3780 Align);
3781 }
3782
John McCall7f416cc2015-09-08 08:05:57 +00003783 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3784
3785 // Increase the overflow area.
3786 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3787 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3788 CGF.EmitBranch(Cont);
3789 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003790
3791 CGF.EmitBlock(Cont);
3792
John McCall7f416cc2015-09-08 08:05:57 +00003793 // Merge the cases with a phi.
3794 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3795 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003796
John McCall7f416cc2015-09-08 08:05:57 +00003797 // Load the pointer if the argument was passed indirectly.
3798 if (isIndirect) {
3799 Result = Address(Builder.CreateLoad(Result, "aggr"),
3800 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003801 }
3802
3803 return Result;
3804}
3805
John McCallea8d8bb2010-03-11 00:10:12 +00003806bool
3807PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3808 llvm::Value *Address) const {
3809 // This is calculated from the LLVM and GCC tables and verified
3810 // against gcc output. AFAIK all ABIs use the same encoding.
3811
3812 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003813
Chris Lattnerece04092012-02-07 00:39:47 +00003814 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003815 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3816 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3817 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3818
3819 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003820 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003821
3822 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003823 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003824
3825 // 64-76 are various 4-byte special-purpose registers:
3826 // 64: mq
3827 // 65: lr
3828 // 66: ctr
3829 // 67: ap
3830 // 68-75 cr0-7
3831 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003832 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003833
3834 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003835 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003836
3837 // 109: vrsave
3838 // 110: vscr
3839 // 111: spe_acc
3840 // 112: spefscr
3841 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003842 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003843
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003844 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003845}
3846
Roman Divackyd966e722012-05-09 18:22:46 +00003847// PowerPC-64
3848
3849namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003850/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003851class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003852public:
3853 enum ABIKind {
3854 ELFv1 = 0,
3855 ELFv2
3856 };
3857
3858private:
3859 static const unsigned GPRBits = 64;
3860 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003861 bool HasQPX;
3862
3863 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3864 // will be passed in a QPX register.
3865 bool IsQPXVectorTy(const Type *Ty) const {
3866 if (!HasQPX)
3867 return false;
3868
3869 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3870 unsigned NumElements = VT->getNumElements();
3871 if (NumElements == 1)
3872 return false;
3873
3874 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3875 if (getContext().getTypeSize(Ty) <= 256)
3876 return true;
3877 } else if (VT->getElementType()->
3878 isSpecificBuiltinType(BuiltinType::Float)) {
3879 if (getContext().getTypeSize(Ty) <= 128)
3880 return true;
3881 }
3882 }
3883
3884 return false;
3885 }
3886
3887 bool IsQPXVectorTy(QualType Ty) const {
3888 return IsQPXVectorTy(Ty.getTypePtr());
3889 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003890
3891public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003892 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
James Y Knight29b5f082016-02-24 02:59:33 +00003893 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003894
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003895 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003896 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003897
3898 ABIArgInfo classifyReturnType(QualType RetTy) const;
3899 ABIArgInfo classifyArgumentType(QualType Ty) const;
3900
Reid Klecknere9f6a712014-10-31 17:10:41 +00003901 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3902 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3903 uint64_t Members) const override;
3904
Bill Schmidt84d37792012-10-12 19:26:17 +00003905 // TODO: We can add more logic to computeInfo to improve performance.
3906 // Example: For aggregate arguments that fit in a register, we could
3907 // use getDirectInReg (as is done below for structs containing a single
3908 // floating-point value) to avoid pushing them to memory on function
3909 // entry. This would require changing the logic in PPCISelLowering
3910 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003911 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003912 if (!getCXXABI().classifyReturnType(FI))
3913 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003914 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003915 // We rely on the default argument classification for the most part.
3916 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003917 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003918 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003919 if (T) {
3920 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003921 if (IsQPXVectorTy(T) ||
3922 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003923 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003924 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003925 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003926 continue;
3927 }
3928 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003929 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003930 }
3931 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003932
John McCall7f416cc2015-09-08 08:05:57 +00003933 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3934 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003935};
3936
3937class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003938
Bill Schmidt25cb3492012-10-03 19:18:57 +00003939public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003940 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003941 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003942 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003943
Craig Topper4f12f102014-03-12 06:41:41 +00003944 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003945 // This is recovered from gcc output.
3946 return 1; // r1 is the dedicated stack pointer
3947 }
3948
3949 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003950 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003951};
3952
Roman Divackyd966e722012-05-09 18:22:46 +00003953class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3954public:
3955 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3956
Craig Topper4f12f102014-03-12 06:41:41 +00003957 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003958 // This is recovered from gcc output.
3959 return 1; // r1 is the dedicated stack pointer
3960 }
3961
3962 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003963 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003964};
3965
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003966}
Roman Divackyd966e722012-05-09 18:22:46 +00003967
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003968// Return true if the ABI requires Ty to be passed sign- or zero-
3969// extended to 64 bits.
3970bool
3971PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3972 // Treat an enum type as its underlying type.
3973 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3974 Ty = EnumTy->getDecl()->getIntegerType();
3975
3976 // Promotable integer types are required to be promoted by the ABI.
3977 if (Ty->isPromotableIntegerType())
3978 return true;
3979
3980 // In addition to the usual promotable integer types, we also need to
3981 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3982 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3983 switch (BT->getKind()) {
3984 case BuiltinType::Int:
3985 case BuiltinType::UInt:
3986 return true;
3987 default:
3988 break;
3989 }
3990
3991 return false;
3992}
3993
John McCall7f416cc2015-09-08 08:05:57 +00003994/// isAlignedParamType - Determine whether a type requires 16-byte or
3995/// higher alignment in the parameter area. Always returns at least 8.
3996CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003997 // Complex types are passed just like their elements.
3998 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3999 Ty = CTy->getElementType();
4000
4001 // Only vector types of size 16 bytes need alignment (larger types are
4002 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004003 if (IsQPXVectorTy(Ty)) {
4004 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004005 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004006
John McCall7f416cc2015-09-08 08:05:57 +00004007 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004008 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004009 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004010 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004011
4012 // For single-element float/vector structs, we consider the whole type
4013 // to have the same alignment requirements as its single element.
4014 const Type *AlignAsType = nullptr;
4015 const Type *EltType = isSingleElementStruct(Ty, getContext());
4016 if (EltType) {
4017 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004018 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004019 getContext().getTypeSize(EltType) == 128) ||
4020 (BT && BT->isFloatingPoint()))
4021 AlignAsType = EltType;
4022 }
4023
Ulrich Weigandb7122372014-07-21 00:48:09 +00004024 // Likewise for ELFv2 homogeneous aggregates.
4025 const Type *Base = nullptr;
4026 uint64_t Members = 0;
4027 if (!AlignAsType && Kind == ELFv2 &&
4028 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4029 AlignAsType = Base;
4030
Ulrich Weigand581badc2014-07-10 17:20:07 +00004031 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004032 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4033 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004034 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004035
John McCall7f416cc2015-09-08 08:05:57 +00004036 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004037 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004038 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004039 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004040
4041 // Otherwise, we only need alignment for any aggregate type that
4042 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004043 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4044 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004045 return CharUnits::fromQuantity(32);
4046 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004047 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004048
John McCall7f416cc2015-09-08 08:05:57 +00004049 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004050}
4051
Ulrich Weigandb7122372014-07-21 00:48:09 +00004052/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4053/// aggregate. Base is set to the base element type, and Members is set
4054/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004055bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4056 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004057 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4058 uint64_t NElements = AT->getSize().getZExtValue();
4059 if (NElements == 0)
4060 return false;
4061 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4062 return false;
4063 Members *= NElements;
4064 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4065 const RecordDecl *RD = RT->getDecl();
4066 if (RD->hasFlexibleArrayMember())
4067 return false;
4068
4069 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004070
4071 // If this is a C++ record, check the bases first.
4072 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4073 for (const auto &I : CXXRD->bases()) {
4074 // Ignore empty records.
4075 if (isEmptyRecord(getContext(), I.getType(), true))
4076 continue;
4077
4078 uint64_t FldMembers;
4079 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4080 return false;
4081
4082 Members += FldMembers;
4083 }
4084 }
4085
Ulrich Weigandb7122372014-07-21 00:48:09 +00004086 for (const auto *FD : RD->fields()) {
4087 // Ignore (non-zero arrays of) empty records.
4088 QualType FT = FD->getType();
4089 while (const ConstantArrayType *AT =
4090 getContext().getAsConstantArrayType(FT)) {
4091 if (AT->getSize().getZExtValue() == 0)
4092 return false;
4093 FT = AT->getElementType();
4094 }
4095 if (isEmptyRecord(getContext(), FT, true))
4096 continue;
4097
4098 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4099 if (getContext().getLangOpts().CPlusPlus &&
4100 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4101 continue;
4102
4103 uint64_t FldMembers;
4104 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4105 return false;
4106
4107 Members = (RD->isUnion() ?
4108 std::max(Members, FldMembers) : Members + FldMembers);
4109 }
4110
4111 if (!Base)
4112 return false;
4113
4114 // Ensure there is no padding.
4115 if (getContext().getTypeSize(Base) * Members !=
4116 getContext().getTypeSize(Ty))
4117 return false;
4118 } else {
4119 Members = 1;
4120 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4121 Members = 2;
4122 Ty = CT->getElementType();
4123 }
4124
Reid Klecknere9f6a712014-10-31 17:10:41 +00004125 // Most ABIs only support float, double, and some vector type widths.
4126 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004127 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004128
4129 // The base type must be the same for all members. Types that
4130 // agree in both total size and mode (float vs. vector) are
4131 // treated as being equivalent here.
4132 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004133 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004134 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004135 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4136 // so make sure to widen it explicitly.
4137 if (const VectorType *VT = Base->getAs<VectorType>()) {
4138 QualType EltTy = VT->getElementType();
4139 unsigned NumElements =
4140 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4141 Base = getContext()
4142 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4143 .getTypePtr();
4144 }
4145 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004146
4147 if (Base->isVectorType() != TyPtr->isVectorType() ||
4148 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4149 return false;
4150 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004151 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4152}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004153
Reid Klecknere9f6a712014-10-31 17:10:41 +00004154bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4155 // Homogeneous aggregates for ELFv2 must have base types of float,
4156 // double, long double, or 128-bit vectors.
4157 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4158 if (BT->getKind() == BuiltinType::Float ||
4159 BT->getKind() == BuiltinType::Double ||
4160 BT->getKind() == BuiltinType::LongDouble)
4161 return true;
4162 }
4163 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004164 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004165 return true;
4166 }
4167 return false;
4168}
4169
4170bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4171 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004172 // Vector types require one register, floating point types require one
4173 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004174 uint32_t NumRegs =
4175 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004176
4177 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004178 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004179}
4180
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004181ABIArgInfo
4182PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004183 Ty = useFirstFieldIfTransparentUnion(Ty);
4184
Bill Schmidt90b22c92012-11-27 02:46:43 +00004185 if (Ty->isAnyComplexType())
4186 return ABIArgInfo::getDirect();
4187
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004188 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4189 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004190 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004191 uint64_t Size = getContext().getTypeSize(Ty);
4192 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004193 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004194 else if (Size < 128) {
4195 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4196 return ABIArgInfo::getDirect(CoerceTy);
4197 }
4198 }
4199
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004200 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004201 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004202 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004203
John McCall7f416cc2015-09-08 08:05:57 +00004204 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4205 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004206
4207 // ELFv2 homogeneous aggregates are passed as array types.
4208 const Type *Base = nullptr;
4209 uint64_t Members = 0;
4210 if (Kind == ELFv2 &&
4211 isHomogeneousAggregate(Ty, Base, Members)) {
4212 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4213 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4214 return ABIArgInfo::getDirect(CoerceTy);
4215 }
4216
Ulrich Weigand601957f2014-07-21 00:56:36 +00004217 // If an aggregate may end up fully in registers, we do not
4218 // use the ByVal method, but pass the aggregate as array.
4219 // This is usually beneficial since we avoid forcing the
4220 // back-end to store the argument to memory.
4221 uint64_t Bits = getContext().getTypeSize(Ty);
4222 if (Bits > 0 && Bits <= 8 * GPRBits) {
4223 llvm::Type *CoerceTy;
4224
4225 // Types up to 8 bytes are passed as integer type (which will be
4226 // properly aligned in the argument save area doubleword).
4227 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004228 CoerceTy =
4229 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004230 // Larger types are passed as arrays, with the base type selected
4231 // according to the required alignment in the save area.
4232 else {
4233 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004234 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004235 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4236 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4237 }
4238
4239 return ABIArgInfo::getDirect(CoerceTy);
4240 }
4241
Ulrich Weigandb7122372014-07-21 00:48:09 +00004242 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004243 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4244 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004245 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004246 }
4247
4248 return (isPromotableTypeForABI(Ty) ?
4249 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4250}
4251
4252ABIArgInfo
4253PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4254 if (RetTy->isVoidType())
4255 return ABIArgInfo::getIgnore();
4256
Bill Schmidta3d121c2012-12-17 04:20:17 +00004257 if (RetTy->isAnyComplexType())
4258 return ABIArgInfo::getDirect();
4259
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004260 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4261 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004262 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004263 uint64_t Size = getContext().getTypeSize(RetTy);
4264 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004265 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004266 else if (Size < 128) {
4267 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4268 return ABIArgInfo::getDirect(CoerceTy);
4269 }
4270 }
4271
Ulrich Weigandb7122372014-07-21 00:48:09 +00004272 if (isAggregateTypeForABI(RetTy)) {
4273 // ELFv2 homogeneous aggregates are returned as array types.
4274 const Type *Base = nullptr;
4275 uint64_t Members = 0;
4276 if (Kind == ELFv2 &&
4277 isHomogeneousAggregate(RetTy, Base, Members)) {
4278 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4279 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4280 return ABIArgInfo::getDirect(CoerceTy);
4281 }
4282
4283 // ELFv2 small aggregates are returned in up to two registers.
4284 uint64_t Bits = getContext().getTypeSize(RetTy);
4285 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4286 if (Bits == 0)
4287 return ABIArgInfo::getIgnore();
4288
4289 llvm::Type *CoerceTy;
4290 if (Bits > GPRBits) {
4291 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004292 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004293 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004294 CoerceTy =
4295 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004296 return ABIArgInfo::getDirect(CoerceTy);
4297 }
4298
4299 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004300 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004301 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004302
4303 return (isPromotableTypeForABI(RetTy) ?
4304 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4305}
4306
Bill Schmidt25cb3492012-10-03 19:18:57 +00004307// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004308Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4309 QualType Ty) const {
4310 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4311 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004312
John McCall7f416cc2015-09-08 08:05:57 +00004313 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004314
Bill Schmidt924c4782013-01-14 17:45:36 +00004315 // If we have a complex type and the base type is smaller than 8 bytes,
4316 // the ABI calls for the real and imaginary parts to be right-adjusted
4317 // in separate doublewords. However, Clang expects us to produce a
4318 // pointer to a structure with the two parts packed tightly. So generate
4319 // loads of the real and imaginary parts relative to the va_list pointer,
4320 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004321 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4322 CharUnits EltSize = TypeInfo.first / 2;
4323 if (EltSize < SlotSize) {
4324 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4325 SlotSize * 2, SlotSize,
4326 SlotSize, /*AllowHigher*/ true);
4327
4328 Address RealAddr = Addr;
4329 Address ImagAddr = RealAddr;
4330 if (CGF.CGM.getDataLayout().isBigEndian()) {
4331 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4332 SlotSize - EltSize);
4333 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4334 2 * SlotSize - EltSize);
4335 } else {
4336 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4337 }
4338
4339 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4340 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4341 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4342 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4343 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4344
4345 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4346 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4347 /*init*/ true);
4348 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004349 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004350 }
4351
John McCall7f416cc2015-09-08 08:05:57 +00004352 // Otherwise, just use the general rule.
4353 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4354 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004355}
4356
4357static bool
4358PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4359 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004360 // This is calculated from the LLVM and GCC tables and verified
4361 // against gcc output. AFAIK all ABIs use the same encoding.
4362
4363 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4364
4365 llvm::IntegerType *i8 = CGF.Int8Ty;
4366 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4367 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4368 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4369
4370 // 0-31: r0-31, the 8-byte general-purpose registers
4371 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4372
4373 // 32-63: fp0-31, the 8-byte floating-point registers
4374 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4375
4376 // 64-76 are various 4-byte special-purpose registers:
4377 // 64: mq
4378 // 65: lr
4379 // 66: ctr
4380 // 67: ap
4381 // 68-75 cr0-7
4382 // 76: xer
4383 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4384
4385 // 77-108: v0-31, the 16-byte vector registers
4386 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4387
4388 // 109: vrsave
4389 // 110: vscr
4390 // 111: spe_acc
4391 // 112: spefscr
4392 // 113: sfp
4393 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4394
4395 return false;
4396}
John McCallea8d8bb2010-03-11 00:10:12 +00004397
Bill Schmidt25cb3492012-10-03 19:18:57 +00004398bool
4399PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4400 CodeGen::CodeGenFunction &CGF,
4401 llvm::Value *Address) const {
4402
4403 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4404}
4405
4406bool
4407PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4408 llvm::Value *Address) const {
4409
4410 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4411}
4412
Chris Lattner0cf24192010-06-28 20:05:43 +00004413//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004414// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004415//===----------------------------------------------------------------------===//
4416
4417namespace {
4418
John McCall12f23522016-04-04 18:33:08 +00004419class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004420public:
4421 enum ABIKind {
4422 AAPCS = 0,
4423 DarwinPCS
4424 };
4425
4426private:
4427 ABIKind Kind;
4428
4429public:
John McCall12f23522016-04-04 18:33:08 +00004430 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4431 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004432
4433private:
4434 ABIKind getABIKind() const { return Kind; }
4435 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4436
4437 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004438 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004439 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4440 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4441 uint64_t Members) const override;
4442
Tim Northovera2ee4332014-03-29 15:09:45 +00004443 bool isIllegalVectorType(QualType Ty) const;
4444
David Blaikie1cbb9712014-11-14 19:09:44 +00004445 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004446 if (!getCXXABI().classifyReturnType(FI))
4447 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004448
Tim Northoverb047bfa2014-11-27 21:02:49 +00004449 for (auto &it : FI.arguments())
4450 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004451 }
4452
John McCall7f416cc2015-09-08 08:05:57 +00004453 Address EmitDarwinVAArg(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 EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4457 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004458
John McCall7f416cc2015-09-08 08:05:57 +00004459 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4460 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004461 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4462 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4463 }
John McCall12f23522016-04-04 18:33:08 +00004464
4465 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4466 ArrayRef<llvm::Type*> scalars,
4467 bool asReturnValue) const override {
4468 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4469 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004470};
4471
Tim Northover573cbee2014-05-24 12:52:07 +00004472class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004473public:
Tim Northover573cbee2014-05-24 12:52:07 +00004474 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4475 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004476
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004477 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004478 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4479 }
4480
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004481 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4482 return 31;
4483 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004484
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004485 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004486};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004487}
Tim Northovera2ee4332014-03-29 15:09:45 +00004488
Tim Northoverb047bfa2014-11-27 21:02:49 +00004489ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004490 Ty = useFirstFieldIfTransparentUnion(Ty);
4491
Tim Northovera2ee4332014-03-29 15:09:45 +00004492 // Handle illegal vector types here.
4493 if (isIllegalVectorType(Ty)) {
4494 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004495 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004496 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004497 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4498 return ABIArgInfo::getDirect(ResType);
4499 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004500 if (Size <= 32) {
4501 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004502 return ABIArgInfo::getDirect(ResType);
4503 }
4504 if (Size == 64) {
4505 llvm::Type *ResType =
4506 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004507 return ABIArgInfo::getDirect(ResType);
4508 }
4509 if (Size == 128) {
4510 llvm::Type *ResType =
4511 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004512 return ABIArgInfo::getDirect(ResType);
4513 }
John McCall7f416cc2015-09-08 08:05:57 +00004514 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004515 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004516
4517 if (!isAggregateTypeForABI(Ty)) {
4518 // Treat an enum type as its underlying type.
4519 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4520 Ty = EnumTy->getDecl()->getIntegerType();
4521
Tim Northovera2ee4332014-03-29 15:09:45 +00004522 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4523 ? ABIArgInfo::getExtend()
4524 : ABIArgInfo::getDirect());
4525 }
4526
4527 // Structures with either a non-trivial destructor or a non-trivial
4528 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004529 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004530 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4531 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004532 }
4533
4534 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4535 // elsewhere for GNU compatibility.
4536 if (isEmptyRecord(getContext(), Ty, true)) {
4537 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4538 return ABIArgInfo::getIgnore();
4539
Tim Northovera2ee4332014-03-29 15:09:45 +00004540 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4541 }
4542
4543 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004544 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004545 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004546 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004547 return ABIArgInfo::getDirect(
4548 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004549 }
4550
4551 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4552 uint64_t Size = getContext().getTypeSize(Ty);
4553 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004554 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004555 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004556
Tim Northovera2ee4332014-03-29 15:09:45 +00004557 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4558 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004559 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004560 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4561 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4562 }
4563 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4564 }
4565
John McCall7f416cc2015-09-08 08:05:57 +00004566 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004567}
4568
Tim Northover573cbee2014-05-24 12:52:07 +00004569ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004570 if (RetTy->isVoidType())
4571 return ABIArgInfo::getIgnore();
4572
4573 // Large vector types should be returned via memory.
4574 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004575 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004576
4577 if (!isAggregateTypeForABI(RetTy)) {
4578 // Treat an enum type as its underlying type.
4579 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4580 RetTy = EnumTy->getDecl()->getIntegerType();
4581
Tim Northover4dab6982014-04-18 13:46:08 +00004582 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4583 ? ABIArgInfo::getExtend()
4584 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004585 }
4586
Tim Northovera2ee4332014-03-29 15:09:45 +00004587 if (isEmptyRecord(getContext(), RetTy, true))
4588 return ABIArgInfo::getIgnore();
4589
Craig Topper8a13c412014-05-21 05:09:00 +00004590 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004591 uint64_t Members = 0;
4592 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004593 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4594 return ABIArgInfo::getDirect();
4595
4596 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4597 uint64_t Size = getContext().getTypeSize(RetTy);
4598 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004599 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004600 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004601
4602 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4603 // For aggregates with 16-byte alignment, we use i128.
4604 if (Alignment < 128 && Size == 128) {
4605 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4606 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4607 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004608 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4609 }
4610
John McCall7f416cc2015-09-08 08:05:57 +00004611 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004612}
4613
Tim Northover573cbee2014-05-24 12:52:07 +00004614/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4615bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004616 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4617 // Check whether VT is legal.
4618 unsigned NumElements = VT->getNumElements();
4619 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004620 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004621 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004622 return true;
4623 return Size != 64 && (Size != 128 || NumElements == 1);
4624 }
4625 return false;
4626}
4627
Reid Klecknere9f6a712014-10-31 17:10:41 +00004628bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4629 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4630 // point type or a short-vector type. This is the same as the 32-bit ABI,
4631 // but with the difference that any floating-point type is allowed,
4632 // including __fp16.
4633 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4634 if (BT->isFloatingPoint())
4635 return true;
4636 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4637 unsigned VecSize = getContext().getTypeSize(VT);
4638 if (VecSize == 64 || VecSize == 128)
4639 return true;
4640 }
4641 return false;
4642}
4643
4644bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4645 uint64_t Members) const {
4646 return Members <= 4;
4647}
4648
John McCall7f416cc2015-09-08 08:05:57 +00004649Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004650 QualType Ty,
4651 CodeGenFunction &CGF) const {
4652 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004653 bool IsIndirect = AI.isIndirect();
4654
Tim Northoverb047bfa2014-11-27 21:02:49 +00004655 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4656 if (IsIndirect)
4657 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4658 else if (AI.getCoerceToType())
4659 BaseTy = AI.getCoerceToType();
4660
4661 unsigned NumRegs = 1;
4662 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4663 BaseTy = ArrTy->getElementType();
4664 NumRegs = ArrTy->getNumElements();
4665 }
4666 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4667
Tim Northovera2ee4332014-03-29 15:09:45 +00004668 // The AArch64 va_list type and handling is specified in the Procedure Call
4669 // Standard, section B.4:
4670 //
4671 // struct {
4672 // void *__stack;
4673 // void *__gr_top;
4674 // void *__vr_top;
4675 // int __gr_offs;
4676 // int __vr_offs;
4677 // };
4678
4679 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4680 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4681 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4682 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004683
John McCall7f416cc2015-09-08 08:05:57 +00004684 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4685 CharUnits TyAlign = TyInfo.second;
4686
4687 Address reg_offs_p = Address::invalid();
4688 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004689 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004690 CharUnits reg_top_offset;
4691 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004692 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004693 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004694 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004695 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4696 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004697 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4698 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004699 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004700 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004701 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004702 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004703 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004704 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4705 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004706 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4707 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004708 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004709 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004710 }
4711
4712 //=======================================
4713 // Find out where argument was passed
4714 //=======================================
4715
4716 // If reg_offs >= 0 we're already using the stack for this type of
4717 // argument. We don't want to keep updating reg_offs (in case it overflows,
4718 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4719 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004720 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004721 UsingStack = CGF.Builder.CreateICmpSGE(
4722 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4723
4724 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4725
4726 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004727 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004728 CGF.EmitBlock(MaybeRegBlock);
4729
4730 // Integer arguments may need to correct register alignment (for example a
4731 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4732 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004733 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4734 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004735
4736 reg_offs = CGF.Builder.CreateAdd(
4737 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4738 "align_regoffs");
4739 reg_offs = CGF.Builder.CreateAnd(
4740 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4741 "aligned_regoffs");
4742 }
4743
4744 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004745 // The fact that this is done unconditionally reflects the fact that
4746 // allocating an argument to the stack also uses up all the remaining
4747 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004748 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004749 NewOffset = CGF.Builder.CreateAdd(
4750 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4751 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4752
4753 // Now we're in a position to decide whether this argument really was in
4754 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004755 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004756 InRegs = CGF.Builder.CreateICmpSLE(
4757 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4758
4759 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4760
4761 //=======================================
4762 // Argument was in registers
4763 //=======================================
4764
4765 // Now we emit the code for if the argument was originally passed in
4766 // registers. First start the appropriate block:
4767 CGF.EmitBlock(InRegBlock);
4768
John McCall7f416cc2015-09-08 08:05:57 +00004769 llvm::Value *reg_top = nullptr;
4770 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4771 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004772 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004773 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4774 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4775 Address RegAddr = Address::invalid();
4776 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004777
4778 if (IsIndirect) {
4779 // If it's been passed indirectly (actually a struct), whatever we find from
4780 // stored registers or on the stack will actually be a struct **.
4781 MemTy = llvm::PointerType::getUnqual(MemTy);
4782 }
4783
Craig Topper8a13c412014-05-21 05:09:00 +00004784 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004785 uint64_t NumMembers = 0;
4786 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004787 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004788 // Homogeneous aggregates passed in registers will have their elements split
4789 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4790 // qN+1, ...). We reload and store into a temporary local variable
4791 // contiguously.
4792 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004793 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004794 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4795 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004796 Address Tmp = CGF.CreateTempAlloca(HFATy,
4797 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004798
John McCall7f416cc2015-09-08 08:05:57 +00004799 // On big-endian platforms, the value will be right-aligned in its slot.
4800 int Offset = 0;
4801 if (CGF.CGM.getDataLayout().isBigEndian() &&
4802 BaseTyInfo.first.getQuantity() < 16)
4803 Offset = 16 - BaseTyInfo.first.getQuantity();
4804
Tim Northovera2ee4332014-03-29 15:09:45 +00004805 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004806 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4807 Address LoadAddr =
4808 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4809 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4810
4811 Address StoreAddr =
4812 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004813
4814 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4815 CGF.Builder.CreateStore(Elem, StoreAddr);
4816 }
4817
John McCall7f416cc2015-09-08 08:05:57 +00004818 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004819 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004820 // Otherwise the object is contiguous in memory.
4821
4822 // It might be right-aligned in its slot.
4823 CharUnits SlotSize = BaseAddr.getAlignment();
4824 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004825 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004826 TyInfo.first < SlotSize) {
4827 CharUnits Offset = SlotSize - TyInfo.first;
4828 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004829 }
4830
John McCall7f416cc2015-09-08 08:05:57 +00004831 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004832 }
4833
4834 CGF.EmitBranch(ContBlock);
4835
4836 //=======================================
4837 // Argument was on the stack
4838 //=======================================
4839 CGF.EmitBlock(OnStackBlock);
4840
John McCall7f416cc2015-09-08 08:05:57 +00004841 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4842 CharUnits::Zero(), "stack_p");
4843 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004844
John McCall7f416cc2015-09-08 08:05:57 +00004845 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004846 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004847 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4848 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004849
John McCall7f416cc2015-09-08 08:05:57 +00004850 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004851
John McCall7f416cc2015-09-08 08:05:57 +00004852 OnStackPtr = CGF.Builder.CreateAdd(
4853 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004854 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004855 OnStackPtr = CGF.Builder.CreateAnd(
4856 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004857 "align_stack");
4858
John McCall7f416cc2015-09-08 08:05:57 +00004859 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004860 }
John McCall7f416cc2015-09-08 08:05:57 +00004861 Address OnStackAddr(OnStackPtr,
4862 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004863
John McCall7f416cc2015-09-08 08:05:57 +00004864 // All stack slots are multiples of 8 bytes.
4865 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4866 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004867 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004868 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004869 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004870 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004871
John McCall7f416cc2015-09-08 08:05:57 +00004872 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004873 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004874 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004875
4876 // Write the new value of __stack for the next call to va_arg
4877 CGF.Builder.CreateStore(NewStack, stack_p);
4878
4879 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004880 TyInfo.first < StackSlotSize) {
4881 CharUnits Offset = StackSlotSize - TyInfo.first;
4882 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004883 }
4884
John McCall7f416cc2015-09-08 08:05:57 +00004885 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004886
4887 CGF.EmitBranch(ContBlock);
4888
4889 //=======================================
4890 // Tidy up
4891 //=======================================
4892 CGF.EmitBlock(ContBlock);
4893
John McCall7f416cc2015-09-08 08:05:57 +00004894 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4895 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004896
4897 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004898 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4899 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004900
4901 return ResAddr;
4902}
4903
John McCall7f416cc2015-09-08 08:05:57 +00004904Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4905 CodeGenFunction &CGF) const {
4906 // The backend's lowering doesn't support va_arg for aggregates or
4907 // illegal vector types. Lower VAArg here for these cases and use
4908 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004909 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004910 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004911
John McCall7f416cc2015-09-08 08:05:57 +00004912 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004913
John McCall7f416cc2015-09-08 08:05:57 +00004914 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004915 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004916 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4917 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4918 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004919 }
4920
John McCall7f416cc2015-09-08 08:05:57 +00004921 // The size of the actual thing passed, which might end up just
4922 // being a pointer for indirect types.
4923 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4924
4925 // Arguments bigger than 16 bytes which aren't homogeneous
4926 // aggregates should be passed indirectly.
4927 bool IsIndirect = false;
4928 if (TyInfo.first.getQuantity() > 16) {
4929 const Type *Base = nullptr;
4930 uint64_t Members = 0;
4931 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004932 }
4933
John McCall7f416cc2015-09-08 08:05:57 +00004934 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4935 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004936}
4937
4938//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004939// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004940//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004941
4942namespace {
4943
John McCall12f23522016-04-04 18:33:08 +00004944class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004945public:
4946 enum ABIKind {
4947 APCS = 0,
4948 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004949 AAPCS_VFP = 2,
4950 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004951 };
4952
4953private:
4954 ABIKind Kind;
4955
4956public:
John McCall12f23522016-04-04 18:33:08 +00004957 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
4958 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004959 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004960 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004961
John McCall3480ef22011-08-30 01:42:09 +00004962 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004963 switch (getTarget().getTriple().getEnvironment()) {
4964 case llvm::Triple::Android:
4965 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004966 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004967 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004968 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00004969 case llvm::Triple::MuslEABI:
4970 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004971 return true;
4972 default:
4973 return false;
4974 }
John McCall3480ef22011-08-30 01:42:09 +00004975 }
4976
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004977 bool isEABIHF() const {
4978 switch (getTarget().getTriple().getEnvironment()) {
4979 case llvm::Triple::EABIHF:
4980 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00004981 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004982 return true;
4983 default:
4984 return false;
4985 }
4986 }
4987
Daniel Dunbar020daa92009-09-12 01:00:39 +00004988 ABIKind getABIKind() const { return Kind; }
4989
Tim Northovera484bc02013-10-01 14:34:25 +00004990private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004991 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004992 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004993 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004994
Reid Klecknere9f6a712014-10-31 17:10:41 +00004995 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4996 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4997 uint64_t Members) const override;
4998
Craig Topper4f12f102014-03-12 06:41:41 +00004999 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005000
John McCall7f416cc2015-09-08 08:05:57 +00005001 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5002 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005003
5004 llvm::CallingConv::ID getLLVMDefaultCC() const;
5005 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005006 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005007
5008 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5009 ArrayRef<llvm::Type*> scalars,
5010 bool asReturnValue) const override {
5011 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5012 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005013};
5014
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005015class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5016public:
Chris Lattner2b037972010-07-29 02:01:43 +00005017 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5018 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005019
John McCall3480ef22011-08-30 01:42:09 +00005020 const ARMABIInfo &getABIInfo() const {
5021 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5022 }
5023
Craig Topper4f12f102014-03-12 06:41:41 +00005024 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005025 return 13;
5026 }
Roman Divackyc1617352011-05-18 19:36:54 +00005027
Craig Topper4f12f102014-03-12 06:41:41 +00005028 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005029 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5030 }
5031
Roman Divackyc1617352011-05-18 19:36:54 +00005032 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005033 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005034 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005035
5036 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005037 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005038 return false;
5039 }
John McCall3480ef22011-08-30 01:42:09 +00005040
Craig Topper4f12f102014-03-12 06:41:41 +00005041 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005042 if (getABIInfo().isEABI()) return 88;
5043 return TargetCodeGenInfo::getSizeOfUnwindException();
5044 }
Tim Northovera484bc02013-10-01 14:34:25 +00005045
Eric Christopher162c91c2015-06-05 22:03:00 +00005046 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005047 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005048 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005049 if (!FD)
5050 return;
5051
5052 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5053 if (!Attr)
5054 return;
5055
5056 const char *Kind;
5057 switch (Attr->getInterrupt()) {
5058 case ARMInterruptAttr::Generic: Kind = ""; break;
5059 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5060 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5061 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5062 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5063 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5064 }
5065
5066 llvm::Function *Fn = cast<llvm::Function>(GV);
5067
5068 Fn->addFnAttr("interrupt", Kind);
5069
Tim Northover5627d392015-10-30 16:30:45 +00005070 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5071 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005072 return;
5073
5074 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5075 // however this is not necessarily true on taking any interrupt. Instruct
5076 // the backend to perform a realignment as part of the function prologue.
5077 llvm::AttrBuilder B;
5078 B.addStackAlignmentAttr(8);
5079 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5080 llvm::AttributeSet::get(CGM.getLLVMContext(),
5081 llvm::AttributeSet::FunctionIndex,
5082 B));
5083 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005084};
5085
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005086class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005087public:
5088 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5089 : ARMTargetCodeGenInfo(CGT, K) {}
5090
Eric Christopher162c91c2015-06-05 22:03:00 +00005091 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005092 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005093
5094 void getDependentLibraryOption(llvm::StringRef Lib,
5095 llvm::SmallString<24> &Opt) const override {
5096 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5097 }
5098
5099 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5100 llvm::SmallString<32> &Opt) const override {
5101 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5102 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005103};
5104
Eric Christopher162c91c2015-06-05 22:03:00 +00005105void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005106 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005107 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005108 addStackProbeSizeTargetAttribute(D, GV, CGM);
5109}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005110}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005111
Chris Lattner22326a12010-07-29 02:31:05 +00005112void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005113 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005114 FI.getReturnInfo() =
5115 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005116
Tim Northoverbc784d12015-02-24 17:22:40 +00005117 for (auto &I : FI.arguments())
5118 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005119
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005120 // Always honor user-specified calling convention.
5121 if (FI.getCallingConvention() != llvm::CallingConv::C)
5122 return;
5123
John McCall882987f2013-02-28 19:01:20 +00005124 llvm::CallingConv::ID cc = getRuntimeCC();
5125 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005126 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005127}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005128
John McCall882987f2013-02-28 19:01:20 +00005129/// Return the default calling convention that LLVM will use.
5130llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5131 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005132 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005133 return llvm::CallingConv::ARM_AAPCS_VFP;
5134 else if (isEABI())
5135 return llvm::CallingConv::ARM_AAPCS;
5136 else
5137 return llvm::CallingConv::ARM_APCS;
5138}
5139
5140/// Return the calling convention that our ABI would like us to use
5141/// as the C calling convention.
5142llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005143 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005144 case APCS: return llvm::CallingConv::ARM_APCS;
5145 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5146 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005147 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005148 }
John McCall882987f2013-02-28 19:01:20 +00005149 llvm_unreachable("bad ABI kind");
5150}
5151
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005152void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005153 assert(getRuntimeCC() == llvm::CallingConv::C);
5154
5155 // Don't muddy up the IR with a ton of explicit annotations if
5156 // they'd just match what LLVM will infer from the triple.
5157 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5158 if (abiCC != getLLVMDefaultCC())
5159 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005160
Tim Northover5627d392015-10-30 16:30:45 +00005161 // AAPCS apparently requires runtime support functions to be soft-float, but
5162 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5163 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5164 switch (getABIKind()) {
5165 case APCS:
5166 case AAPCS16_VFP:
5167 if (abiCC != getLLVMDefaultCC())
5168 BuiltinCC = abiCC;
5169 break;
5170 case AAPCS:
5171 case AAPCS_VFP:
5172 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5173 break;
5174 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005175}
5176
Tim Northoverbc784d12015-02-24 17:22:40 +00005177ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5178 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005179 // 6.1.2.1 The following argument types are VFP CPRCs:
5180 // A single-precision floating-point type (including promoted
5181 // half-precision types); A double-precision floating-point type;
5182 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5183 // with a Base Type of a single- or double-precision floating-point type,
5184 // 64-bit containerized vectors or 128-bit containerized vectors with one
5185 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005186 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005187
Reid Klecknerb1be6832014-11-15 01:41:41 +00005188 Ty = useFirstFieldIfTransparentUnion(Ty);
5189
Manman Renfef9e312012-10-16 19:18:39 +00005190 // Handle illegal vector types here.
5191 if (isIllegalVectorType(Ty)) {
5192 uint64_t Size = getContext().getTypeSize(Ty);
5193 if (Size <= 32) {
5194 llvm::Type *ResType =
5195 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005196 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005197 }
5198 if (Size == 64) {
5199 llvm::Type *ResType = llvm::VectorType::get(
5200 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005201 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005202 }
5203 if (Size == 128) {
5204 llvm::Type *ResType = llvm::VectorType::get(
5205 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005206 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005207 }
John McCall7f416cc2015-09-08 08:05:57 +00005208 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005209 }
5210
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005211 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5212 // unspecified. This is not done for OpenCL as it handles the half type
5213 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005214 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005215 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5216 llvm::Type::getFloatTy(getVMContext()) :
5217 llvm::Type::getInt32Ty(getVMContext());
5218 return ABIArgInfo::getDirect(ResType);
5219 }
5220
John McCalla1dee5302010-08-22 10:59:02 +00005221 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005222 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005223 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005224 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005225 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005226
Tim Northover5a1558e2014-11-07 22:30:50 +00005227 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5228 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005229 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005230
Oliver Stannard405bded2014-02-11 09:25:50 +00005231 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005232 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005233 }
Tim Northover1060eae2013-06-21 22:49:34 +00005234
Daniel Dunbar09d33622009-09-14 21:54:03 +00005235 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005236 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005237 return ABIArgInfo::getIgnore();
5238
Tim Northover5a1558e2014-11-07 22:30:50 +00005239 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005240 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5241 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005242 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005243 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005244 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005245 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005246 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005247 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005248 }
Tim Northover5627d392015-10-30 16:30:45 +00005249 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5250 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5251 // this convention even for a variadic function: the backend will use GPRs
5252 // if needed.
5253 const Type *Base = nullptr;
5254 uint64_t Members = 0;
5255 if (isHomogeneousAggregate(Ty, Base, Members)) {
5256 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5257 llvm::Type *Ty =
5258 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5259 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5260 }
5261 }
5262
5263 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5264 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5265 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5266 // bigger than 128-bits, they get placed in space allocated by the caller,
5267 // and a pointer is passed.
5268 return ABIArgInfo::getIndirect(
5269 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005270 }
5271
Manman Ren6c30e132012-08-13 21:23:55 +00005272 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005273 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5274 // most 8-byte. We realign the indirect argument if type alignment is bigger
5275 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005276 uint64_t ABIAlign = 4;
5277 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5278 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005279 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005280 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005281
Manman Ren8cd99812012-11-06 04:58:01 +00005282 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005283 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005284 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5285 /*ByVal=*/true,
5286 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005287 }
5288
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005289 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005290 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005291 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005292 // FIXME: Try to match the types of the arguments more accurately where
5293 // we can.
5294 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005295 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5296 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005297 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005298 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5299 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005300 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005301
Tim Northover5a1558e2014-11-07 22:30:50 +00005302 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005303}
5304
Chris Lattner458b2aa2010-07-29 02:16:43 +00005305static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005306 llvm::LLVMContext &VMContext) {
5307 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5308 // is called integer-like if its size is less than or equal to one word, and
5309 // the offset of each of its addressable sub-fields is zero.
5310
5311 uint64_t Size = Context.getTypeSize(Ty);
5312
5313 // Check that the type fits in a word.
5314 if (Size > 32)
5315 return false;
5316
5317 // FIXME: Handle vector types!
5318 if (Ty->isVectorType())
5319 return false;
5320
Daniel Dunbard53bac72009-09-14 02:20:34 +00005321 // Float types are never treated as "integer like".
5322 if (Ty->isRealFloatingType())
5323 return false;
5324
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005325 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005326 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005327 return true;
5328
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005329 // Small complex integer types are "integer like".
5330 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5331 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005332
5333 // Single element and zero sized arrays should be allowed, by the definition
5334 // above, but they are not.
5335
5336 // Otherwise, it must be a record type.
5337 const RecordType *RT = Ty->getAs<RecordType>();
5338 if (!RT) return false;
5339
5340 // Ignore records with flexible arrays.
5341 const RecordDecl *RD = RT->getDecl();
5342 if (RD->hasFlexibleArrayMember())
5343 return false;
5344
5345 // Check that all sub-fields are at offset 0, and are themselves "integer
5346 // like".
5347 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5348
5349 bool HadField = false;
5350 unsigned idx = 0;
5351 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5352 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005353 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005354
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005355 // Bit-fields are not addressable, we only need to verify they are "integer
5356 // like". We still have to disallow a subsequent non-bitfield, for example:
5357 // struct { int : 0; int x }
5358 // is non-integer like according to gcc.
5359 if (FD->isBitField()) {
5360 if (!RD->isUnion())
5361 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005362
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005363 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5364 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005365
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005366 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005367 }
5368
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005369 // Check if this field is at offset 0.
5370 if (Layout.getFieldOffset(idx) != 0)
5371 return false;
5372
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005373 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5374 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005375
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005376 // Only allow at most one field in a structure. This doesn't match the
5377 // wording above, but follows gcc in situations with a field following an
5378 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005379 if (!RD->isUnion()) {
5380 if (HadField)
5381 return false;
5382
5383 HadField = true;
5384 }
5385 }
5386
5387 return true;
5388}
5389
Oliver Stannard405bded2014-02-11 09:25:50 +00005390ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5391 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005392 bool IsEffectivelyAAPCS_VFP =
5393 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005394
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005395 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005396 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005397
Daniel Dunbar19964db2010-09-23 01:54:32 +00005398 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005399 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005400 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005401 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005402
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005403 // __fp16 gets returned as if it were an int or float, but with the top 16
5404 // bits unspecified. This is not done for OpenCL as it handles the half type
5405 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005406 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005407 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5408 llvm::Type::getFloatTy(getVMContext()) :
5409 llvm::Type::getInt32Ty(getVMContext());
5410 return ABIArgInfo::getDirect(ResType);
5411 }
5412
John McCalla1dee5302010-08-22 10:59:02 +00005413 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005414 // Treat an enum type as its underlying type.
5415 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5416 RetTy = EnumTy->getDecl()->getIntegerType();
5417
Tim Northover5a1558e2014-11-07 22:30:50 +00005418 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5419 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005420 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005421
5422 // Are we following APCS?
5423 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005424 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005425 return ABIArgInfo::getIgnore();
5426
Daniel Dunbareedf1512010-02-01 23:31:19 +00005427 // Complex types are all returned as packed integers.
5428 //
5429 // FIXME: Consider using 2 x vector types if the back end handles them
5430 // correctly.
5431 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005432 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5433 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005434
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005435 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005436 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005437 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005438 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005439 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005440 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005441 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005442 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5443 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005444 }
5445
5446 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005447 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005448 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005449
5450 // Otherwise this is an AAPCS variant.
5451
Chris Lattner458b2aa2010-07-29 02:16:43 +00005452 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005453 return ABIArgInfo::getIgnore();
5454
Bob Wilson1d9269a2011-11-02 04:51:36 +00005455 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005456 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005457 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005458 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005459 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005460 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005461 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005462 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005463 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005464 }
5465
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005466 // Aggregates <= 4 bytes are returned in r0; other aggregates
5467 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005468 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005469 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005470 if (getDataLayout().isBigEndian())
5471 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005472 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005473
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005474 // Return in the smallest viable integer type.
5475 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005476 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005477 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005478 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5479 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005480 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5481 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5482 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005483 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005484 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005485 }
5486
John McCall7f416cc2015-09-08 08:05:57 +00005487 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005488}
5489
Manman Renfef9e312012-10-16 19:18:39 +00005490/// isIllegalVector - check whether Ty is an illegal vector type.
5491bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005492 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5493 if (isAndroid()) {
5494 // Android shipped using Clang 3.1, which supported a slightly different
5495 // vector ABI. The primary differences were that 3-element vector types
5496 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5497 // accepts that legacy behavior for Android only.
5498 // Check whether VT is legal.
5499 unsigned NumElements = VT->getNumElements();
5500 // NumElements should be power of 2 or equal to 3.
5501 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5502 return true;
5503 } else {
5504 // Check whether VT is legal.
5505 unsigned NumElements = VT->getNumElements();
5506 uint64_t Size = getContext().getTypeSize(VT);
5507 // NumElements should be power of 2.
5508 if (!llvm::isPowerOf2_32(NumElements))
5509 return true;
5510 // Size should be greater than 32 bits.
5511 return Size <= 32;
5512 }
Manman Renfef9e312012-10-16 19:18:39 +00005513 }
5514 return false;
5515}
5516
Reid Klecknere9f6a712014-10-31 17:10:41 +00005517bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5518 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5519 // double, or 64-bit or 128-bit vectors.
5520 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5521 if (BT->getKind() == BuiltinType::Float ||
5522 BT->getKind() == BuiltinType::Double ||
5523 BT->getKind() == BuiltinType::LongDouble)
5524 return true;
5525 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5526 unsigned VecSize = getContext().getTypeSize(VT);
5527 if (VecSize == 64 || VecSize == 128)
5528 return true;
5529 }
5530 return false;
5531}
5532
5533bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5534 uint64_t Members) const {
5535 return Members <= 4;
5536}
5537
John McCall7f416cc2015-09-08 08:05:57 +00005538Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5539 QualType Ty) const {
5540 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005541
John McCall7f416cc2015-09-08 08:05:57 +00005542 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005543 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005544 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5545 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5546 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005547 }
5548
John McCall7f416cc2015-09-08 08:05:57 +00005549 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5550 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005551
John McCall7f416cc2015-09-08 08:05:57 +00005552 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5553 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005554 const Type *Base = nullptr;
5555 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005556 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5557 IsIndirect = true;
5558
Tim Northover5627d392015-10-30 16:30:45 +00005559 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5560 // allocated by the caller.
5561 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5562 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5563 !isHomogeneousAggregate(Ty, Base, Members)) {
5564 IsIndirect = true;
5565
John McCall7f416cc2015-09-08 08:05:57 +00005566 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005567 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5568 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005569 // Our callers should be prepared to handle an under-aligned address.
5570 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5571 getABIKind() == ARMABIInfo::AAPCS) {
5572 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5573 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005574 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5575 // ARMv7k allows type alignment up to 16 bytes.
5576 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5577 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005578 } else {
5579 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005580 }
John McCall7f416cc2015-09-08 08:05:57 +00005581 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005582
John McCall7f416cc2015-09-08 08:05:57 +00005583 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5584 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005585}
5586
Chris Lattner0cf24192010-06-28 20:05:43 +00005587//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005588// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005589//===----------------------------------------------------------------------===//
5590
5591namespace {
5592
Justin Holewinski83e96682012-05-24 17:43:12 +00005593class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005594public:
Justin Holewinski36837432013-03-30 14:38:24 +00005595 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005596
5597 ABIArgInfo classifyReturnType(QualType RetTy) const;
5598 ABIArgInfo classifyArgumentType(QualType Ty) const;
5599
Craig Topper4f12f102014-03-12 06:41:41 +00005600 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005601 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5602 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005603};
5604
Justin Holewinski83e96682012-05-24 17:43:12 +00005605class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005606public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005607 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5608 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005609
Eric Christopher162c91c2015-06-05 22:03:00 +00005610 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005611 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005612private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005613 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5614 // resulting MDNode to the nvvm.annotations MDNode.
5615 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005616};
5617
Justin Holewinski83e96682012-05-24 17:43:12 +00005618ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005619 if (RetTy->isVoidType())
5620 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005621
5622 // note: this is different from default ABI
5623 if (!RetTy->isScalarType())
5624 return ABIArgInfo::getDirect();
5625
5626 // Treat an enum type as its underlying type.
5627 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5628 RetTy = EnumTy->getDecl()->getIntegerType();
5629
5630 return (RetTy->isPromotableIntegerType() ?
5631 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005632}
5633
Justin Holewinski83e96682012-05-24 17:43:12 +00005634ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005635 // Treat an enum type as its underlying type.
5636 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5637 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005638
Eli Bendersky95338a02014-10-29 13:43:21 +00005639 // Return aggregates type as indirect by value
5640 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005641 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005642
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005643 return (Ty->isPromotableIntegerType() ?
5644 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005645}
5646
Justin Holewinski83e96682012-05-24 17:43:12 +00005647void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005648 if (!getCXXABI().classifyReturnType(FI))
5649 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005650 for (auto &I : FI.arguments())
5651 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005652
5653 // Always honor user-specified calling convention.
5654 if (FI.getCallingConvention() != llvm::CallingConv::C)
5655 return;
5656
John McCall882987f2013-02-28 19:01:20 +00005657 FI.setEffectiveCallingConvention(getRuntimeCC());
5658}
5659
John McCall7f416cc2015-09-08 08:05:57 +00005660Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5661 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005662 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005663}
5664
Justin Holewinski83e96682012-05-24 17:43:12 +00005665void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005666setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005667 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005668 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005669 if (!FD) return;
5670
5671 llvm::Function *F = cast<llvm::Function>(GV);
5672
5673 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005674 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005675 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005676 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005677 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005678 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005679 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5680 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005681 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005682 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005683 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005684 }
Justin Holewinski38031972011-10-05 17:58:44 +00005685
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005686 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005687 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005688 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005689 // __global__ functions cannot be called from the device, we do not
5690 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005691 if (FD->hasAttr<CUDAGlobalAttr>()) {
5692 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5693 addNVVMMetadata(F, "kernel", 1);
5694 }
Artem Belevich7093e402015-04-21 22:55:54 +00005695 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005696 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005697 llvm::APSInt MaxThreads(32);
5698 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5699 if (MaxThreads > 0)
5700 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5701
5702 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5703 // not specified in __launch_bounds__ or if the user specified a 0 value,
5704 // we don't have to add a PTX directive.
5705 if (Attr->getMinBlocks()) {
5706 llvm::APSInt MinBlocks(32);
5707 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5708 if (MinBlocks > 0)
5709 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5710 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005711 }
5712 }
Justin Holewinski38031972011-10-05 17:58:44 +00005713 }
5714}
5715
Eli Benderskye06a2c42014-04-15 16:57:05 +00005716void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5717 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005718 llvm::Module *M = F->getParent();
5719 llvm::LLVMContext &Ctx = M->getContext();
5720
5721 // Get "nvvm.annotations" metadata node
5722 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5723
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005724 llvm::Metadata *MDVals[] = {
5725 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5726 llvm::ConstantAsMetadata::get(
5727 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005728 // Append metadata to nvvm.annotations
5729 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5730}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005731}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005732
5733//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005734// SystemZ ABI Implementation
5735//===----------------------------------------------------------------------===//
5736
5737namespace {
5738
Bryan Chane3f1ed52016-04-28 13:56:43 +00005739class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005740 bool HasVector;
5741
Ulrich Weigand47445072013-05-06 16:26:41 +00005742public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005743 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005744 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005745
5746 bool isPromotableIntegerType(QualType Ty) const;
5747 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005748 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005749 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005750 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005751
5752 ABIArgInfo classifyReturnType(QualType RetTy) const;
5753 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5754
Craig Topper4f12f102014-03-12 06:41:41 +00005755 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005756 if (!getCXXABI().classifyReturnType(FI))
5757 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005758 for (auto &I : FI.arguments())
5759 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005760 }
5761
John McCall7f416cc2015-09-08 08:05:57 +00005762 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5763 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005764
5765 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5766 ArrayRef<llvm::Type*> scalars,
5767 bool asReturnValue) const override {
5768 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5769 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005770};
5771
5772class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5773public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005774 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5775 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005776};
5777
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005778}
Ulrich Weigand47445072013-05-06 16:26:41 +00005779
5780bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5781 // Treat an enum type as its underlying type.
5782 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5783 Ty = EnumTy->getDecl()->getIntegerType();
5784
5785 // Promotable integer types are required to be promoted by the ABI.
5786 if (Ty->isPromotableIntegerType())
5787 return true;
5788
5789 // 32-bit values must also be promoted.
5790 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5791 switch (BT->getKind()) {
5792 case BuiltinType::Int:
5793 case BuiltinType::UInt:
5794 return true;
5795 default:
5796 return false;
5797 }
5798 return false;
5799}
5800
5801bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005802 return (Ty->isAnyComplexType() ||
5803 Ty->isVectorType() ||
5804 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005805}
5806
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005807bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5808 return (HasVector &&
5809 Ty->isVectorType() &&
5810 getContext().getTypeSize(Ty) <= 128);
5811}
5812
Ulrich Weigand47445072013-05-06 16:26:41 +00005813bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5814 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5815 switch (BT->getKind()) {
5816 case BuiltinType::Float:
5817 case BuiltinType::Double:
5818 return true;
5819 default:
5820 return false;
5821 }
5822
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005823 return false;
5824}
5825
5826QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005827 if (const RecordType *RT = Ty->getAsStructureType()) {
5828 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005829 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005830
5831 // If this is a C++ record, check the bases first.
5832 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005833 for (const auto &I : CXXRD->bases()) {
5834 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005835
5836 // Empty bases don't affect things either way.
5837 if (isEmptyRecord(getContext(), Base, true))
5838 continue;
5839
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005840 if (!Found.isNull())
5841 return Ty;
5842 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005843 }
5844
5845 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005846 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005847 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005848 // Unlike isSingleElementStruct(), empty structure and array fields
5849 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005850 if (getContext().getLangOpts().CPlusPlus &&
5851 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5852 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005853
5854 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005855 // Nested structures still do though.
5856 if (!Found.isNull())
5857 return Ty;
5858 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005859 }
5860
5861 // Unlike isSingleElementStruct(), trailing padding is allowed.
5862 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005863 if (!Found.isNull())
5864 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005865 }
5866
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005867 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005868}
5869
John McCall7f416cc2015-09-08 08:05:57 +00005870Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5871 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005872 // Assume that va_list type is correct; should be pointer to LLVM type:
5873 // struct {
5874 // i64 __gpr;
5875 // i64 __fpr;
5876 // i8 *__overflow_arg_area;
5877 // i8 *__reg_save_area;
5878 // };
5879
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005880 // Every non-vector argument occupies 8 bytes and is passed by preference
5881 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5882 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005883 Ty = getContext().getCanonicalType(Ty);
5884 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005885 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005886 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005887 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005888 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005889 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005890 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005891 CharUnits UnpaddedSize;
5892 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005893 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005894 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5895 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005896 } else {
5897 if (AI.getCoerceToType())
5898 ArgTy = AI.getCoerceToType();
5899 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005900 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005901 UnpaddedSize = TyInfo.first;
5902 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005903 }
John McCall7f416cc2015-09-08 08:05:57 +00005904 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5905 if (IsVector && UnpaddedSize > PaddedSize)
5906 PaddedSize = CharUnits::fromQuantity(16);
5907 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005908
John McCall7f416cc2015-09-08 08:05:57 +00005909 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005910
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005911 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005912 llvm::Value *PaddedSizeV =
5913 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005914
5915 if (IsVector) {
5916 // Work out the address of a vector argument on the stack.
5917 // Vector arguments are always passed in the high bits of a
5918 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005919 Address OverflowArgAreaPtr =
5920 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005921 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005922 Address OverflowArgArea =
5923 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5924 TyInfo.second);
5925 Address MemAddr =
5926 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005927
5928 // Update overflow_arg_area_ptr pointer
5929 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005930 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5931 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005932 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5933
5934 return MemAddr;
5935 }
5936
John McCall7f416cc2015-09-08 08:05:57 +00005937 assert(PaddedSize.getQuantity() == 8);
5938
5939 unsigned MaxRegs, RegCountField, RegSaveIndex;
5940 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005941 if (InFPRs) {
5942 MaxRegs = 4; // Maximum of 4 FPR arguments
5943 RegCountField = 1; // __fpr
5944 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005945 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005946 } else {
5947 MaxRegs = 5; // Maximum of 5 GPR arguments
5948 RegCountField = 0; // __gpr
5949 RegSaveIndex = 2; // save offset for r2
5950 RegPadding = Padding; // values are passed in the low bits of a GPR
5951 }
5952
John McCall7f416cc2015-09-08 08:05:57 +00005953 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5954 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5955 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005956 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005957 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5958 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005959 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005960
5961 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5962 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5963 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5964 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5965
5966 // Emit code to load the value if it was passed in registers.
5967 CGF.EmitBlock(InRegBlock);
5968
5969 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005970 llvm::Value *ScaledRegCount =
5971 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5972 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005973 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5974 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005975 llvm::Value *RegOffset =
5976 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005977 Address RegSaveAreaPtr =
5978 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5979 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005980 llvm::Value *RegSaveArea =
5981 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005982 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5983 "raw_reg_addr"),
5984 PaddedSize);
5985 Address RegAddr =
5986 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005987
5988 // Update the register count
5989 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5990 llvm::Value *NewRegCount =
5991 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5992 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5993 CGF.EmitBranch(ContBlock);
5994
5995 // Emit code to load the value if it was passed in memory.
5996 CGF.EmitBlock(InMemBlock);
5997
5998 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005999 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6000 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6001 Address OverflowArgArea =
6002 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6003 PaddedSize);
6004 Address RawMemAddr =
6005 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6006 Address MemAddr =
6007 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006008
6009 // Update overflow_arg_area_ptr pointer
6010 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006011 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6012 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006013 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6014 CGF.EmitBranch(ContBlock);
6015
6016 // Return the appropriate result.
6017 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006018 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6019 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006020
6021 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006022 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6023 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006024
6025 return ResAddr;
6026}
6027
Ulrich Weigand47445072013-05-06 16:26:41 +00006028ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6029 if (RetTy->isVoidType())
6030 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006031 if (isVectorArgumentType(RetTy))
6032 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006033 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006034 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006035 return (isPromotableIntegerType(RetTy) ?
6036 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6037}
6038
6039ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6040 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006041 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006042 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006043
6044 // Integers and enums are extended to full register width.
6045 if (isPromotableIntegerType(Ty))
6046 return ABIArgInfo::getExtend();
6047
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006048 // Handle vector types and vector-like structure types. Note that
6049 // as opposed to float-like structure types, we do not allow any
6050 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006051 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006052 QualType SingleElementTy = GetSingleElementType(Ty);
6053 if (isVectorArgumentType(SingleElementTy) &&
6054 getContext().getTypeSize(SingleElementTy) == Size)
6055 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6056
6057 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006058 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006059 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006060
6061 // Handle small structures.
6062 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6063 // Structures with flexible arrays have variable length, so really
6064 // fail the size test above.
6065 const RecordDecl *RD = RT->getDecl();
6066 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006067 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006068
6069 // The structure is passed as an unextended integer, a float, or a double.
6070 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006071 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006072 assert(Size == 32 || Size == 64);
6073 if (Size == 32)
6074 PassTy = llvm::Type::getFloatTy(getVMContext());
6075 else
6076 PassTy = llvm::Type::getDoubleTy(getVMContext());
6077 } else
6078 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6079 return ABIArgInfo::getDirect(PassTy);
6080 }
6081
6082 // Non-structure compounds are passed indirectly.
6083 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006084 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006085
Craig Topper8a13c412014-05-21 05:09:00 +00006086 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006087}
6088
6089//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006090// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006091//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006092
6093namespace {
6094
6095class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6096public:
Chris Lattner2b037972010-07-29 02:01:43 +00006097 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6098 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006099 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006100 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006101};
6102
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006103}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006104
Eric Christopher162c91c2015-06-05 22:03:00 +00006105void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006106 llvm::GlobalValue *GV,
6107 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006108 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006109 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6110 // Handle 'interrupt' attribute:
6111 llvm::Function *F = cast<llvm::Function>(GV);
6112
6113 // Step 1: Set ISR calling convention.
6114 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6115
6116 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006117 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006118
6119 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006120 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006121 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6122 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006123 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006124 }
6125}
6126
Chris Lattner0cf24192010-06-28 20:05:43 +00006127//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006128// MIPS ABI Implementation. This works for both little-endian and
6129// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006130//===----------------------------------------------------------------------===//
6131
John McCall943fae92010-05-27 06:19:26 +00006132namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006133class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006134 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006135 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6136 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006137 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006138 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006139 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006140 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006141public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006142 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006143 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006144 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006145
6146 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006147 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006148 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006149 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6150 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006151 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006152};
6153
John McCall943fae92010-05-27 06:19:26 +00006154class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006155 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006156public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006157 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6158 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006159 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006160
Craig Topper4f12f102014-03-12 06:41:41 +00006161 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006162 return 29;
6163 }
6164
Eric Christopher162c91c2015-06-05 22:03:00 +00006165 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006166 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006167 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006168 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006169 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006170 if (FD->hasAttr<Mips16Attr>()) {
6171 Fn->addFnAttr("mips16");
6172 }
6173 else if (FD->hasAttr<NoMips16Attr>()) {
6174 Fn->addFnAttr("nomips16");
6175 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006176
6177 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6178 if (!Attr)
6179 return;
6180
6181 const char *Kind;
6182 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006183 case MipsInterruptAttr::eic: Kind = "eic"; break;
6184 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6185 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6186 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6187 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6188 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6189 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6190 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6191 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6192 }
6193
6194 Fn->addFnAttr("interrupt", Kind);
6195
Reed Kotler373feca2013-01-16 17:10:28 +00006196 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006197
John McCall943fae92010-05-27 06:19:26 +00006198 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006199 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006200
Craig Topper4f12f102014-03-12 06:41:41 +00006201 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006202 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006203 }
John McCall943fae92010-05-27 06:19:26 +00006204};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006205}
John McCall943fae92010-05-27 06:19:26 +00006206
Eric Christopher7565e0d2015-05-29 23:09:49 +00006207void MipsABIInfo::CoerceToIntArgs(
6208 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006209 llvm::IntegerType *IntTy =
6210 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006211
6212 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6213 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6214 ArgList.push_back(IntTy);
6215
6216 // If necessary, add one more integer type to ArgList.
6217 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6218
6219 if (R)
6220 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006221}
6222
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006223// In N32/64, an aligned double precision floating point field is passed in
6224// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006225llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006226 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6227
6228 if (IsO32) {
6229 CoerceToIntArgs(TySize, ArgList);
6230 return llvm::StructType::get(getVMContext(), ArgList);
6231 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006232
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006233 if (Ty->isComplexType())
6234 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006235
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006236 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006237
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006238 // Unions/vectors are passed in integer registers.
6239 if (!RT || !RT->isStructureOrClassType()) {
6240 CoerceToIntArgs(TySize, ArgList);
6241 return llvm::StructType::get(getVMContext(), ArgList);
6242 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006243
6244 const RecordDecl *RD = RT->getDecl();
6245 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006246 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006247
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006248 uint64_t LastOffset = 0;
6249 unsigned idx = 0;
6250 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6251
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006252 // Iterate over fields in the struct/class and check if there are any aligned
6253 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006254 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6255 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006256 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006257 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6258
6259 if (!BT || BT->getKind() != BuiltinType::Double)
6260 continue;
6261
6262 uint64_t Offset = Layout.getFieldOffset(idx);
6263 if (Offset % 64) // Ignore doubles that are not aligned.
6264 continue;
6265
6266 // Add ((Offset - LastOffset) / 64) args of type i64.
6267 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6268 ArgList.push_back(I64);
6269
6270 // Add double type.
6271 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6272 LastOffset = Offset + 64;
6273 }
6274
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006275 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6276 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006277
6278 return llvm::StructType::get(getVMContext(), ArgList);
6279}
6280
Akira Hatanakaddd66342013-10-29 18:41:15 +00006281llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6282 uint64_t Offset) const {
6283 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006284 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006285
Akira Hatanakaddd66342013-10-29 18:41:15 +00006286 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006287}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006288
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006289ABIArgInfo
6290MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006291 Ty = useFirstFieldIfTransparentUnion(Ty);
6292
Akira Hatanaka1632af62012-01-09 19:31:25 +00006293 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006294 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006295 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006296
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006297 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6298 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006299 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6300 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006301
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006302 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006303 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006304 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006305 return ABIArgInfo::getIgnore();
6306
Mark Lacey3825e832013-10-06 01:33:34 +00006307 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006308 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006309 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006310 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006311
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006312 // If we have reached here, aggregates are passed directly by coercing to
6313 // another structure type. Padding is inserted if the offset of the
6314 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006315 ABIArgInfo ArgInfo =
6316 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6317 getPaddingType(OrigOffset, CurrOffset));
6318 ArgInfo.setInReg(true);
6319 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006320 }
6321
6322 // Treat an enum type as its underlying type.
6323 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6324 Ty = EnumTy->getDecl()->getIntegerType();
6325
Daniel Sanders5b445b32014-10-24 14:42:42 +00006326 // All integral types are promoted to the GPR width.
6327 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006328 return ABIArgInfo::getExtend();
6329
Akira Hatanakaddd66342013-10-29 18:41:15 +00006330 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006331 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006332}
6333
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006334llvm::Type*
6335MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006336 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006337 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006338
Akira Hatanakab6f74432012-02-09 18:49:26 +00006339 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006340 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006341 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6342 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006343
Akira Hatanakab6f74432012-02-09 18:49:26 +00006344 // N32/64 returns struct/classes in floating point registers if the
6345 // following conditions are met:
6346 // 1. The size of the struct/class is no larger than 128-bit.
6347 // 2. The struct/class has one or two fields all of which are floating
6348 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006349 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006350 //
6351 // Any other composite results are returned in integer registers.
6352 //
6353 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6354 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6355 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006356 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006357
Akira Hatanakab6f74432012-02-09 18:49:26 +00006358 if (!BT || !BT->isFloatingPoint())
6359 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006360
David Blaikie2d7c57e2012-04-30 02:36:29 +00006361 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006362 }
6363
6364 if (b == e)
6365 return llvm::StructType::get(getVMContext(), RTList,
6366 RD->hasAttr<PackedAttr>());
6367
6368 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006369 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006370 }
6371
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006372 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006373 return llvm::StructType::get(getVMContext(), RTList);
6374}
6375
Akira Hatanakab579fe52011-06-02 00:09:17 +00006376ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006377 uint64_t Size = getContext().getTypeSize(RetTy);
6378
Daniel Sandersed39f582014-09-04 13:28:14 +00006379 if (RetTy->isVoidType())
6380 return ABIArgInfo::getIgnore();
6381
6382 // O32 doesn't treat zero-sized structs differently from other structs.
6383 // However, N32/N64 ignores zero sized return values.
6384 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006385 return ABIArgInfo::getIgnore();
6386
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006387 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006388 if (Size <= 128) {
6389 if (RetTy->isAnyComplexType())
6390 return ABIArgInfo::getDirect();
6391
Daniel Sanderse5018b62014-09-04 15:05:39 +00006392 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006393 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006394 if (!IsO32 ||
6395 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6396 ABIArgInfo ArgInfo =
6397 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6398 ArgInfo.setInReg(true);
6399 return ArgInfo;
6400 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006401 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006402
John McCall7f416cc2015-09-08 08:05:57 +00006403 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006404 }
6405
6406 // Treat an enum type as its underlying type.
6407 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6408 RetTy = EnumTy->getDecl()->getIntegerType();
6409
6410 return (RetTy->isPromotableIntegerType() ?
6411 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6412}
6413
6414void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006415 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006416 if (!getCXXABI().classifyReturnType(FI))
6417 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006418
Eric Christopher7565e0d2015-05-29 23:09:49 +00006419 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006420 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006421
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006422 for (auto &I : FI.arguments())
6423 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006424}
6425
John McCall7f416cc2015-09-08 08:05:57 +00006426Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6427 QualType OrigTy) const {
6428 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006429
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006430 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6431 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006432 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006433 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006434 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006435 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006436 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006437 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006438 DidPromote = true;
6439 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6440 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006441 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006442
John McCall7f416cc2015-09-08 08:05:57 +00006443 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006444
John McCall7f416cc2015-09-08 08:05:57 +00006445 // The alignment of things in the argument area is never larger than
6446 // StackAlignInBytes.
6447 TyInfo.second =
6448 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6449
6450 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6451 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6452
6453 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6454 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6455
6456
6457 // If there was a promotion, "unpromote" into a temporary.
6458 // TODO: can we just use a pointer into a subset of the original slot?
6459 if (DidPromote) {
6460 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6461 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6462
6463 // Truncate down to the right width.
6464 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6465 : CGF.IntPtrTy);
6466 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6467 if (OrigTy->isPointerType())
6468 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6469
6470 CGF.Builder.CreateStore(V, Temp);
6471 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006472 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006473
John McCall7f416cc2015-09-08 08:05:57 +00006474 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006475}
6476
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006477bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6478 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006479
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006480 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6481 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6482 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006483
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006484 return false;
6485}
6486
John McCall943fae92010-05-27 06:19:26 +00006487bool
6488MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6489 llvm::Value *Address) const {
6490 // This information comes from gcc's implementation, which seems to
6491 // as canonical as it gets.
6492
John McCall943fae92010-05-27 06:19:26 +00006493 // Everything on MIPS is 4 bytes. Double-precision FP registers
6494 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006495 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006496
6497 // 0-31 are the general purpose registers, $0 - $31.
6498 // 32-63 are the floating-point registers, $f0 - $f31.
6499 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6500 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006501 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006502
6503 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6504 // They are one bit wide and ignored here.
6505
6506 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6507 // (coprocessor 1 is the FP unit)
6508 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6509 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6510 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006511 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006512 return false;
6513}
6514
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006515//===----------------------------------------------------------------------===//
6516// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006517// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006518// handling.
6519//===----------------------------------------------------------------------===//
6520
6521namespace {
6522
6523class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6524public:
6525 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6526 : DefaultTargetCodeGenInfo(CGT) {}
6527
Eric Christopher162c91c2015-06-05 22:03:00 +00006528 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006529 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006530};
6531
Eric Christopher162c91c2015-06-05 22:03:00 +00006532void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006533 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006534 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006535 if (!FD) return;
6536
6537 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006538
David Blaikiebbafb8a2012-03-11 07:00:24 +00006539 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006540 if (FD->hasAttr<OpenCLKernelAttr>()) {
6541 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006542 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006543 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6544 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006545 // Convert the reqd_work_group_size() attributes to metadata.
6546 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006547 llvm::NamedMDNode *OpenCLMetadata =
6548 M.getModule().getOrInsertNamedMetadata(
6549 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006550
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006551 SmallVector<llvm::Metadata *, 5> Operands;
6552 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006553
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006554 Operands.push_back(
6555 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6556 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6557 Operands.push_back(
6558 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6559 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6560 Operands.push_back(
6561 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6562 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006563
Eric Christopher7565e0d2015-05-29 23:09:49 +00006564 // Add a boolean constant operand for "required" (true) or "hint"
6565 // (false) for implementing the work_group_size_hint attr later.
6566 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006567 Operands.push_back(
6568 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006569 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6570 }
6571 }
6572 }
6573}
6574
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006575}
John McCall943fae92010-05-27 06:19:26 +00006576
Tony Linthicum76329bf2011-12-12 21:14:55 +00006577//===----------------------------------------------------------------------===//
6578// Hexagon ABI Implementation
6579//===----------------------------------------------------------------------===//
6580
6581namespace {
6582
6583class HexagonABIInfo : public ABIInfo {
6584
6585
6586public:
6587 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6588
6589private:
6590
6591 ABIArgInfo classifyReturnType(QualType RetTy) const;
6592 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6593
Craig Topper4f12f102014-03-12 06:41:41 +00006594 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006595
John McCall7f416cc2015-09-08 08:05:57 +00006596 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6597 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006598};
6599
6600class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6601public:
6602 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6603 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6604
Craig Topper4f12f102014-03-12 06:41:41 +00006605 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006606 return 29;
6607 }
6608};
6609
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006610}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006611
6612void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006613 if (!getCXXABI().classifyReturnType(FI))
6614 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006615 for (auto &I : FI.arguments())
6616 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006617}
6618
6619ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6620 if (!isAggregateTypeForABI(Ty)) {
6621 // Treat an enum type as its underlying type.
6622 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6623 Ty = EnumTy->getDecl()->getIntegerType();
6624
6625 return (Ty->isPromotableIntegerType() ?
6626 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6627 }
6628
6629 // Ignore empty records.
6630 if (isEmptyRecord(getContext(), Ty, true))
6631 return ABIArgInfo::getIgnore();
6632
Mark Lacey3825e832013-10-06 01:33:34 +00006633 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006634 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006635
6636 uint64_t Size = getContext().getTypeSize(Ty);
6637 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006638 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006639 // Pass in the smallest viable integer type.
6640 else if (Size > 32)
6641 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6642 else if (Size > 16)
6643 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6644 else if (Size > 8)
6645 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6646 else
6647 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6648}
6649
6650ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6651 if (RetTy->isVoidType())
6652 return ABIArgInfo::getIgnore();
6653
6654 // Large vector types should be returned via memory.
6655 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006656 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006657
6658 if (!isAggregateTypeForABI(RetTy)) {
6659 // Treat an enum type as its underlying type.
6660 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6661 RetTy = EnumTy->getDecl()->getIntegerType();
6662
6663 return (RetTy->isPromotableIntegerType() ?
6664 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6665 }
6666
Tony Linthicum76329bf2011-12-12 21:14:55 +00006667 if (isEmptyRecord(getContext(), RetTy, true))
6668 return ABIArgInfo::getIgnore();
6669
6670 // Aggregates <= 8 bytes are returned in r0; other aggregates
6671 // are returned indirectly.
6672 uint64_t Size = getContext().getTypeSize(RetTy);
6673 if (Size <= 64) {
6674 // Return in the smallest viable integer type.
6675 if (Size <= 8)
6676 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6677 if (Size <= 16)
6678 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6679 if (Size <= 32)
6680 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6681 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6682 }
6683
John McCall7f416cc2015-09-08 08:05:57 +00006684 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006685}
6686
John McCall7f416cc2015-09-08 08:05:57 +00006687Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6688 QualType Ty) const {
6689 // FIXME: Someone needs to audit that this handle alignment correctly.
6690 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6691 getContext().getTypeInfoInChars(Ty),
6692 CharUnits::fromQuantity(4),
6693 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006694}
6695
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006696//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006697// Lanai ABI Implementation
6698//===----------------------------------------------------------------------===//
6699
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006700namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006701class LanaiABIInfo : public DefaultABIInfo {
6702public:
6703 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6704
6705 bool shouldUseInReg(QualType Ty, CCState &State) const;
6706
6707 void computeInfo(CGFunctionInfo &FI) const override {
6708 CCState State(FI.getCallingConvention());
6709 // Lanai uses 4 registers to pass arguments unless the function has the
6710 // regparm attribute set.
6711 if (FI.getHasRegParm()) {
6712 State.FreeRegs = FI.getRegParm();
6713 } else {
6714 State.FreeRegs = 4;
6715 }
6716
6717 if (!getCXXABI().classifyReturnType(FI))
6718 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6719 for (auto &I : FI.arguments())
6720 I.info = classifyArgumentType(I.type, State);
6721 }
6722
Jacques Pienaare74d9132016-04-26 00:09:29 +00006723 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006724 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6725};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006726} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006727
6728bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6729 unsigned Size = getContext().getTypeSize(Ty);
6730 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6731
6732 if (SizeInRegs == 0)
6733 return false;
6734
6735 if (SizeInRegs > State.FreeRegs) {
6736 State.FreeRegs = 0;
6737 return false;
6738 }
6739
6740 State.FreeRegs -= SizeInRegs;
6741
6742 return true;
6743}
6744
Jacques Pienaare74d9132016-04-26 00:09:29 +00006745ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6746 CCState &State) const {
6747 if (!ByVal) {
6748 if (State.FreeRegs) {
6749 --State.FreeRegs; // Non-byval indirects just use one pointer.
6750 return getNaturalAlignIndirectInReg(Ty);
6751 }
6752 return getNaturalAlignIndirect(Ty, false);
6753 }
6754
6755 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006756 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006757 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6758 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6759 /*Realign=*/TypeAlign >
6760 MinABIStackAlignInBytes);
6761}
6762
Jacques Pienaard964cc22016-03-28 21:02:54 +00006763ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6764 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006765 // Check with the C++ ABI first.
6766 const RecordType *RT = Ty->getAs<RecordType>();
6767 if (RT) {
6768 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6769 if (RAA == CGCXXABI::RAA_Indirect) {
6770 return getIndirectResult(Ty, /*ByVal=*/false, State);
6771 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6772 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6773 }
6774 }
6775
6776 if (isAggregateTypeForABI(Ty)) {
6777 // Structures with flexible arrays are always indirect.
6778 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6779 return getIndirectResult(Ty, /*ByVal=*/true, State);
6780
6781 // Ignore empty structs/unions.
6782 if (isEmptyRecord(getContext(), Ty, true))
6783 return ABIArgInfo::getIgnore();
6784
6785 llvm::LLVMContext &LLVMContext = getVMContext();
6786 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6787 if (SizeInRegs <= State.FreeRegs) {
6788 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6789 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6790 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6791 State.FreeRegs -= SizeInRegs;
6792 return ABIArgInfo::getDirectInReg(Result);
6793 } else {
6794 State.FreeRegs = 0;
6795 }
6796 return getIndirectResult(Ty, true, State);
6797 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006798
6799 // Treat an enum type as its underlying type.
6800 if (const auto *EnumTy = Ty->getAs<EnumType>())
6801 Ty = EnumTy->getDecl()->getIntegerType();
6802
Jacques Pienaare74d9132016-04-26 00:09:29 +00006803 bool InReg = shouldUseInReg(Ty, State);
6804 if (Ty->isPromotableIntegerType()) {
6805 if (InReg)
6806 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006807 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006808 }
6809 if (InReg)
6810 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006811 return ABIArgInfo::getDirect();
6812}
6813
6814namespace {
6815class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6816public:
6817 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6818 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6819};
6820}
6821
6822//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006823// AMDGPU ABI Implementation
6824//===----------------------------------------------------------------------===//
6825
6826namespace {
6827
6828class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6829public:
6830 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6831 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006832 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006833 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00006834 unsigned getOpenCLKernelCallingConv() const override;
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006835};
6836
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006837}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006838
Eric Christopher162c91c2015-06-05 22:03:00 +00006839void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006840 const Decl *D,
6841 llvm::GlobalValue *GV,
6842 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006843 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006844 if (!FD)
6845 return;
6846
6847 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6848 llvm::Function *F = cast<llvm::Function>(GV);
6849 uint32_t NumVGPR = Attr->getNumVGPR();
6850 if (NumVGPR != 0)
6851 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6852 }
6853
6854 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6855 llvm::Function *F = cast<llvm::Function>(GV);
6856 unsigned NumSGPR = Attr->getNumSGPR();
6857 if (NumSGPR != 0)
6858 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6859 }
6860}
6861
Tony Linthicum76329bf2011-12-12 21:14:55 +00006862
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00006863unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
6864 return llvm::CallingConv::AMDGPU_KERNEL;
6865}
6866
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006867//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00006868// SPARC v8 ABI Implementation.
6869// Based on the SPARC Compliance Definition version 2.4.1.
6870//
6871// Ensures that complex values are passed in registers.
6872//
6873namespace {
6874class SparcV8ABIInfo : public DefaultABIInfo {
6875public:
6876 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6877
6878private:
6879 ABIArgInfo classifyReturnType(QualType RetTy) const;
6880 void computeInfo(CGFunctionInfo &FI) const override;
6881};
6882} // end anonymous namespace
6883
6884
6885ABIArgInfo
6886SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
6887 if (Ty->isAnyComplexType()) {
6888 return ABIArgInfo::getDirect();
6889 }
6890 else {
6891 return DefaultABIInfo::classifyReturnType(Ty);
6892 }
6893}
6894
6895void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6896
6897 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6898 for (auto &Arg : FI.arguments())
6899 Arg.info = classifyArgumentType(Arg.type);
6900}
6901
6902namespace {
6903class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
6904public:
6905 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
6906 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
6907};
6908} // end anonymous namespace
6909
6910//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006911// SPARC v9 ABI Implementation.
6912// Based on the SPARC Compliance Definition version 2.4.1.
6913//
6914// Function arguments a mapped to a nominal "parameter array" and promoted to
6915// registers depending on their type. Each argument occupies 8 or 16 bytes in
6916// the array, structs larger than 16 bytes are passed indirectly.
6917//
6918// One case requires special care:
6919//
6920// struct mixed {
6921// int i;
6922// float f;
6923// };
6924//
6925// When a struct mixed is passed by value, it only occupies 8 bytes in the
6926// parameter array, but the int is passed in an integer register, and the float
6927// is passed in a floating point register. This is represented as two arguments
6928// with the LLVM IR inreg attribute:
6929//
6930// declare void f(i32 inreg %i, float inreg %f)
6931//
6932// The code generator will only allocate 4 bytes from the parameter array for
6933// the inreg arguments. All other arguments are allocated a multiple of 8
6934// bytes.
6935//
6936namespace {
6937class SparcV9ABIInfo : public ABIInfo {
6938public:
6939 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6940
6941private:
6942 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006943 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006944 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6945 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006946
6947 // Coercion type builder for structs passed in registers. The coercion type
6948 // serves two purposes:
6949 //
6950 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6951 // in registers.
6952 // 2. Expose aligned floating point elements as first-level elements, so the
6953 // code generator knows to pass them in floating point registers.
6954 //
6955 // We also compute the InReg flag which indicates that the struct contains
6956 // aligned 32-bit floats.
6957 //
6958 struct CoerceBuilder {
6959 llvm::LLVMContext &Context;
6960 const llvm::DataLayout &DL;
6961 SmallVector<llvm::Type*, 8> Elems;
6962 uint64_t Size;
6963 bool InReg;
6964
6965 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6966 : Context(c), DL(dl), Size(0), InReg(false) {}
6967
6968 // Pad Elems with integers until Size is ToSize.
6969 void pad(uint64_t ToSize) {
6970 assert(ToSize >= Size && "Cannot remove elements");
6971 if (ToSize == Size)
6972 return;
6973
6974 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006975 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006976 if (Aligned > Size && Aligned <= ToSize) {
6977 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6978 Size = Aligned;
6979 }
6980
6981 // Add whole 64-bit words.
6982 while (Size + 64 <= ToSize) {
6983 Elems.push_back(llvm::Type::getInt64Ty(Context));
6984 Size += 64;
6985 }
6986
6987 // Final in-word padding.
6988 if (Size < ToSize) {
6989 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6990 Size = ToSize;
6991 }
6992 }
6993
6994 // Add a floating point element at Offset.
6995 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6996 // Unaligned floats are treated as integers.
6997 if (Offset % Bits)
6998 return;
6999 // The InReg flag is only required if there are any floats < 64 bits.
7000 if (Bits < 64)
7001 InReg = true;
7002 pad(Offset);
7003 Elems.push_back(Ty);
7004 Size = Offset + Bits;
7005 }
7006
7007 // Add a struct type to the coercion type, starting at Offset (in bits).
7008 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7009 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7010 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7011 llvm::Type *ElemTy = StrTy->getElementType(i);
7012 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7013 switch (ElemTy->getTypeID()) {
7014 case llvm::Type::StructTyID:
7015 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7016 break;
7017 case llvm::Type::FloatTyID:
7018 addFloat(ElemOffset, ElemTy, 32);
7019 break;
7020 case llvm::Type::DoubleTyID:
7021 addFloat(ElemOffset, ElemTy, 64);
7022 break;
7023 case llvm::Type::FP128TyID:
7024 addFloat(ElemOffset, ElemTy, 128);
7025 break;
7026 case llvm::Type::PointerTyID:
7027 if (ElemOffset % 64 == 0) {
7028 pad(ElemOffset);
7029 Elems.push_back(ElemTy);
7030 Size += 64;
7031 }
7032 break;
7033 default:
7034 break;
7035 }
7036 }
7037 }
7038
7039 // Check if Ty is a usable substitute for the coercion type.
7040 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007041 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007042 }
7043
7044 // Get the coercion type as a literal struct type.
7045 llvm::Type *getType() const {
7046 if (Elems.size() == 1)
7047 return Elems.front();
7048 else
7049 return llvm::StructType::get(Context, Elems);
7050 }
7051 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007052};
7053} // end anonymous namespace
7054
7055ABIArgInfo
7056SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7057 if (Ty->isVoidType())
7058 return ABIArgInfo::getIgnore();
7059
7060 uint64_t Size = getContext().getTypeSize(Ty);
7061
7062 // Anything too big to fit in registers is passed with an explicit indirect
7063 // pointer / sret pointer.
7064 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007065 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007066
7067 // Treat an enum type as its underlying type.
7068 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7069 Ty = EnumTy->getDecl()->getIntegerType();
7070
7071 // Integer types smaller than a register are extended.
7072 if (Size < 64 && Ty->isIntegerType())
7073 return ABIArgInfo::getExtend();
7074
7075 // Other non-aggregates go in registers.
7076 if (!isAggregateTypeForABI(Ty))
7077 return ABIArgInfo::getDirect();
7078
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007079 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7080 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7081 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007082 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007083
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007084 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007085 // Build a coercion type from the LLVM struct type.
7086 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7087 if (!StrTy)
7088 return ABIArgInfo::getDirect();
7089
7090 CoerceBuilder CB(getVMContext(), getDataLayout());
7091 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007092 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007093
7094 // Try to use the original type for coercion.
7095 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7096
7097 if (CB.InReg)
7098 return ABIArgInfo::getDirectInReg(CoerceTy);
7099 else
7100 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007101}
7102
John McCall7f416cc2015-09-08 08:05:57 +00007103Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7104 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007105 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7106 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7107 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7108 AI.setCoerceToType(ArgTy);
7109
John McCall7f416cc2015-09-08 08:05:57 +00007110 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007111
John McCall7f416cc2015-09-08 08:05:57 +00007112 CGBuilderTy &Builder = CGF.Builder;
7113 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7114 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7115
7116 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7117
7118 Address ArgAddr = Address::invalid();
7119 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007120 switch (AI.getKind()) {
7121 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007122 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007123 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007124 llvm_unreachable("Unsupported ABI kind for va_arg");
7125
John McCall7f416cc2015-09-08 08:05:57 +00007126 case ABIArgInfo::Extend: {
7127 Stride = SlotSize;
7128 CharUnits Offset = SlotSize - TypeInfo.first;
7129 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007130 break;
John McCall7f416cc2015-09-08 08:05:57 +00007131 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007132
John McCall7f416cc2015-09-08 08:05:57 +00007133 case ABIArgInfo::Direct: {
7134 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007135 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007136 ArgAddr = Addr;
7137 break;
John McCall7f416cc2015-09-08 08:05:57 +00007138 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007139
7140 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007141 Stride = SlotSize;
7142 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7143 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7144 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007145 break;
7146
7147 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007148 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007149 }
7150
7151 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007152 llvm::Value *NextPtr =
7153 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7154 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007155
John McCall7f416cc2015-09-08 08:05:57 +00007156 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007157}
7158
7159void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7160 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007161 for (auto &I : FI.arguments())
7162 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007163}
7164
7165namespace {
7166class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7167public:
7168 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7169 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007170
Craig Topper4f12f102014-03-12 06:41:41 +00007171 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007172 return 14;
7173 }
7174
7175 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007176 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007177};
7178} // end anonymous namespace
7179
Roman Divackyf02c9942014-02-24 18:46:27 +00007180bool
7181SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7182 llvm::Value *Address) const {
7183 // This is calculated from the LLVM and GCC tables and verified
7184 // against gcc output. AFAIK all ABIs use the same encoding.
7185
7186 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7187
7188 llvm::IntegerType *i8 = CGF.Int8Ty;
7189 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7190 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7191
7192 // 0-31: the 8-byte general-purpose registers
7193 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7194
7195 // 32-63: f0-31, the 4-byte floating-point registers
7196 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7197
7198 // Y = 64
7199 // PSR = 65
7200 // WIM = 66
7201 // TBR = 67
7202 // PC = 68
7203 // NPC = 69
7204 // FSR = 70
7205 // CSR = 71
7206 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007207
Roman Divackyf02c9942014-02-24 18:46:27 +00007208 // 72-87: d0-15, the 8-byte floating-point registers
7209 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7210
7211 return false;
7212}
7213
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007214
Robert Lytton0e076492013-08-13 09:43:10 +00007215//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007216// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007217//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007218
Robert Lytton0e076492013-08-13 09:43:10 +00007219namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007220
7221/// A SmallStringEnc instance is used to build up the TypeString by passing
7222/// it by reference between functions that append to it.
7223typedef llvm::SmallString<128> SmallStringEnc;
7224
7225/// TypeStringCache caches the meta encodings of Types.
7226///
7227/// The reason for caching TypeStrings is two fold:
7228/// 1. To cache a type's encoding for later uses;
7229/// 2. As a means to break recursive member type inclusion.
7230///
7231/// A cache Entry can have a Status of:
7232/// NonRecursive: The type encoding is not recursive;
7233/// Recursive: The type encoding is recursive;
7234/// Incomplete: An incomplete TypeString;
7235/// IncompleteUsed: An incomplete TypeString that has been used in a
7236/// Recursive type encoding.
7237///
7238/// A NonRecursive entry will have all of its sub-members expanded as fully
7239/// as possible. Whilst it may contain types which are recursive, the type
7240/// itself is not recursive and thus its encoding may be safely used whenever
7241/// the type is encountered.
7242///
7243/// A Recursive entry will have all of its sub-members expanded as fully as
7244/// possible. The type itself is recursive and it may contain other types which
7245/// are recursive. The Recursive encoding must not be used during the expansion
7246/// of a recursive type's recursive branch. For simplicity the code uses
7247/// IncompleteCount to reject all usage of Recursive encodings for member types.
7248///
7249/// An Incomplete entry is always a RecordType and only encodes its
7250/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7251/// are placed into the cache during type expansion as a means to identify and
7252/// handle recursive inclusion of types as sub-members. If there is recursion
7253/// the entry becomes IncompleteUsed.
7254///
7255/// During the expansion of a RecordType's members:
7256///
7257/// If the cache contains a NonRecursive encoding for the member type, the
7258/// cached encoding is used;
7259///
7260/// If the cache contains a Recursive encoding for the member type, the
7261/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7262///
7263/// If the member is a RecordType, an Incomplete encoding is placed into the
7264/// cache to break potential recursive inclusion of itself as a sub-member;
7265///
7266/// Once a member RecordType has been expanded, its temporary incomplete
7267/// entry is removed from the cache. If a Recursive encoding was swapped out
7268/// it is swapped back in;
7269///
7270/// If an incomplete entry is used to expand a sub-member, the incomplete
7271/// entry is marked as IncompleteUsed. The cache keeps count of how many
7272/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7273///
7274/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7275/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7276/// Else the member is part of a recursive type and thus the recursion has
7277/// been exited too soon for the encoding to be correct for the member.
7278///
7279class TypeStringCache {
7280 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7281 struct Entry {
7282 std::string Str; // The encoded TypeString for the type.
7283 enum Status State; // Information about the encoding in 'Str'.
7284 std::string Swapped; // A temporary place holder for a Recursive encoding
7285 // during the expansion of RecordType's members.
7286 };
7287 std::map<const IdentifierInfo *, struct Entry> Map;
7288 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7289 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7290public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007291 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007292 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7293 bool removeIncomplete(const IdentifierInfo *ID);
7294 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7295 bool IsRecursive);
7296 StringRef lookupStr(const IdentifierInfo *ID);
7297};
7298
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007299/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007300/// FieldEncoding is a helper for this ordering process.
7301class FieldEncoding {
7302 bool HasName;
7303 std::string Enc;
7304public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007305 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7306 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007307 bool operator<(const FieldEncoding &rhs) const {
7308 if (HasName != rhs.HasName) return HasName;
7309 return Enc < rhs.Enc;
7310 }
7311};
7312
Robert Lytton7d1db152013-08-19 09:46:39 +00007313class XCoreABIInfo : public DefaultABIInfo {
7314public:
7315 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007316 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7317 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007318};
7319
Robert Lyttond21e2d72014-03-03 13:45:29 +00007320class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007321 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007322public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007323 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007324 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007325 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7326 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007327};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007328
Robert Lytton2d196952013-10-11 10:29:34 +00007329} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007330
James Y Knight29b5f082016-02-24 02:59:33 +00007331// TODO: this implementation is likely now redundant with the default
7332// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007333Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7334 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007335 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007336
Robert Lytton2d196952013-10-11 10:29:34 +00007337 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007338 CharUnits SlotSize = CharUnits::fromQuantity(4);
7339 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007340
Robert Lytton2d196952013-10-11 10:29:34 +00007341 // Handle the argument.
7342 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007343 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007344 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7345 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7346 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007347 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007348
7349 Address Val = Address::invalid();
7350 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007351 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007352 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007353 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007354 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007355 llvm_unreachable("Unsupported ABI kind for va_arg");
7356 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007357 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7358 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007359 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007360 case ABIArgInfo::Extend:
7361 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007362 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7363 ArgSize = CharUnits::fromQuantity(
7364 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007365 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007366 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007367 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007368 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7369 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7370 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007371 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007372 }
Robert Lytton2d196952013-10-11 10:29:34 +00007373
7374 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007375 if (!ArgSize.isZero()) {
7376 llvm::Value *APN =
7377 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7378 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007379 }
John McCall7f416cc2015-09-08 08:05:57 +00007380
Robert Lytton2d196952013-10-11 10:29:34 +00007381 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007382}
Robert Lytton0e076492013-08-13 09:43:10 +00007383
Robert Lytton844aeeb2014-05-02 09:33:20 +00007384/// During the expansion of a RecordType, an incomplete TypeString is placed
7385/// into the cache as a means to identify and break recursion.
7386/// If there is a Recursive encoding in the cache, it is swapped out and will
7387/// be reinserted by removeIncomplete().
7388/// All other types of encoding should have been used rather than arriving here.
7389void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7390 std::string StubEnc) {
7391 if (!ID)
7392 return;
7393 Entry &E = Map[ID];
7394 assert( (E.Str.empty() || E.State == Recursive) &&
7395 "Incorrectly use of addIncomplete");
7396 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7397 E.Swapped.swap(E.Str); // swap out the Recursive
7398 E.Str.swap(StubEnc);
7399 E.State = Incomplete;
7400 ++IncompleteCount;
7401}
7402
7403/// Once the RecordType has been expanded, the temporary incomplete TypeString
7404/// must be removed from the cache.
7405/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7406/// Returns true if the RecordType was defined recursively.
7407bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7408 if (!ID)
7409 return false;
7410 auto I = Map.find(ID);
7411 assert(I != Map.end() && "Entry not present");
7412 Entry &E = I->second;
7413 assert( (E.State == Incomplete ||
7414 E.State == IncompleteUsed) &&
7415 "Entry must be an incomplete type");
7416 bool IsRecursive = false;
7417 if (E.State == IncompleteUsed) {
7418 // We made use of our Incomplete encoding, thus we are recursive.
7419 IsRecursive = true;
7420 --IncompleteUsedCount;
7421 }
7422 if (E.Swapped.empty())
7423 Map.erase(I);
7424 else {
7425 // Swap the Recursive back.
7426 E.Swapped.swap(E.Str);
7427 E.Swapped.clear();
7428 E.State = Recursive;
7429 }
7430 --IncompleteCount;
7431 return IsRecursive;
7432}
7433
7434/// Add the encoded TypeString to the cache only if it is NonRecursive or
7435/// Recursive (viz: all sub-members were expanded as fully as possible).
7436void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7437 bool IsRecursive) {
7438 if (!ID || IncompleteUsedCount)
7439 return; // No key or it is is an incomplete sub-type so don't add.
7440 Entry &E = Map[ID];
7441 if (IsRecursive && !E.Str.empty()) {
7442 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7443 "This is not the same Recursive entry");
7444 // The parent container was not recursive after all, so we could have used
7445 // this Recursive sub-member entry after all, but we assumed the worse when
7446 // we started viz: IncompleteCount!=0.
7447 return;
7448 }
7449 assert(E.Str.empty() && "Entry already present");
7450 E.Str = Str.str();
7451 E.State = IsRecursive? Recursive : NonRecursive;
7452}
7453
7454/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7455/// are recursively expanding a type (IncompleteCount != 0) and the cached
7456/// encoding is Recursive, return an empty StringRef.
7457StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7458 if (!ID)
7459 return StringRef(); // We have no key.
7460 auto I = Map.find(ID);
7461 if (I == Map.end())
7462 return StringRef(); // We have no encoding.
7463 Entry &E = I->second;
7464 if (E.State == Recursive && IncompleteCount)
7465 return StringRef(); // We don't use Recursive encodings for member types.
7466
7467 if (E.State == Incomplete) {
7468 // The incomplete type is being used to break out of recursion.
7469 E.State = IncompleteUsed;
7470 ++IncompleteUsedCount;
7471 }
7472 return E.Str.c_str();
7473}
7474
7475/// The XCore ABI includes a type information section that communicates symbol
7476/// type information to the linker. The linker uses this information to verify
7477/// safety/correctness of things such as array bound and pointers et al.
7478/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7479/// This type information (TypeString) is emitted into meta data for all global
7480/// symbols: definitions, declarations, functions & variables.
7481///
7482/// The TypeString carries type, qualifier, name, size & value details.
7483/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007484/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007485/// The output is tested by test/CodeGen/xcore-stringtype.c.
7486///
7487static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7488 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7489
7490/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7491void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7492 CodeGen::CodeGenModule &CGM) const {
7493 SmallStringEnc Enc;
7494 if (getTypeString(Enc, D, CGM, TSC)) {
7495 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00007496 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
7497 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007498 llvm::NamedMDNode *MD =
7499 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7500 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7501 }
7502}
7503
Xiuli Pan972bea82016-03-24 03:57:17 +00007504//===----------------------------------------------------------------------===//
7505// SPIR ABI Implementation
7506//===----------------------------------------------------------------------===//
7507
7508namespace {
7509class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7510public:
7511 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7512 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7513 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7514 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007515 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00007516};
7517} // End anonymous namespace.
7518
7519/// Emit SPIR specific metadata: OpenCL and SPIR version.
7520void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7521 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007522 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7523 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7524 llvm::Module &M = CGM.getModule();
7525 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7526 // opencl.spir.version named metadata.
7527 llvm::Metadata *SPIRVerElts[] = {
7528 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7529 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7530 llvm::NamedMDNode *SPIRVerMD =
7531 M.getOrInsertNamedMetadata("opencl.spir.version");
7532 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
7533 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7534 // opencl.ocl.version named metadata node.
7535 llvm::Metadata *OCLVerElts[] = {
7536 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7537 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7538 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7539 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7540 llvm::NamedMDNode *OCLVerMD =
7541 M.getOrInsertNamedMetadata("opencl.ocl.version");
7542 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7543}
7544
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007545unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7546 return llvm::CallingConv::SPIR_KERNEL;
7547}
7548
Robert Lytton844aeeb2014-05-02 09:33:20 +00007549static bool appendType(SmallStringEnc &Enc, QualType QType,
7550 const CodeGen::CodeGenModule &CGM,
7551 TypeStringCache &TSC);
7552
7553/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007554/// Builds a SmallVector containing the encoded field types in declaration
7555/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007556static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7557 const RecordDecl *RD,
7558 const CodeGen::CodeGenModule &CGM,
7559 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007560 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007561 SmallStringEnc Enc;
7562 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007563 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007564 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007565 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007566 Enc += "b(";
7567 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007568 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007569 Enc += ':';
7570 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007571 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007572 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007573 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007574 Enc += ')';
7575 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007576 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007577 }
7578 return true;
7579}
7580
7581/// Appends structure and union types to Enc and adds encoding to cache.
7582/// Recursively calls appendType (via extractFieldType) for each field.
7583/// Union types have their fields ordered according to the ABI.
7584static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7585 const CodeGen::CodeGenModule &CGM,
7586 TypeStringCache &TSC, const IdentifierInfo *ID) {
7587 // Append the cached TypeString if we have one.
7588 StringRef TypeString = TSC.lookupStr(ID);
7589 if (!TypeString.empty()) {
7590 Enc += TypeString;
7591 return true;
7592 }
7593
7594 // Start to emit an incomplete TypeString.
7595 size_t Start = Enc.size();
7596 Enc += (RT->isUnionType()? 'u' : 's');
7597 Enc += '(';
7598 if (ID)
7599 Enc += ID->getName();
7600 Enc += "){";
7601
7602 // We collect all encoded fields and order as necessary.
7603 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007604 const RecordDecl *RD = RT->getDecl()->getDefinition();
7605 if (RD && !RD->field_empty()) {
7606 // An incomplete TypeString stub is placed in the cache for this RecordType
7607 // so that recursive calls to this RecordType will use it whilst building a
7608 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007609 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007610 std::string StubEnc(Enc.substr(Start).str());
7611 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7612 TSC.addIncomplete(ID, std::move(StubEnc));
7613 if (!extractFieldType(FE, RD, CGM, TSC)) {
7614 (void) TSC.removeIncomplete(ID);
7615 return false;
7616 }
7617 IsRecursive = TSC.removeIncomplete(ID);
7618 // The ABI requires unions to be sorted but not structures.
7619 // See FieldEncoding::operator< for sort algorithm.
7620 if (RT->isUnionType())
7621 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007622 // We can now complete the TypeString.
7623 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007624 for (unsigned I = 0; I != E; ++I) {
7625 if (I)
7626 Enc += ',';
7627 Enc += FE[I].str();
7628 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007629 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007630 Enc += '}';
7631 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7632 return true;
7633}
7634
7635/// Appends enum types to Enc and adds the encoding to the cache.
7636static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7637 TypeStringCache &TSC,
7638 const IdentifierInfo *ID) {
7639 // Append the cached TypeString if we have one.
7640 StringRef TypeString = TSC.lookupStr(ID);
7641 if (!TypeString.empty()) {
7642 Enc += TypeString;
7643 return true;
7644 }
7645
7646 size_t Start = Enc.size();
7647 Enc += "e(";
7648 if (ID)
7649 Enc += ID->getName();
7650 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007651
7652 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007653 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007654 SmallVector<FieldEncoding, 16> FE;
7655 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7656 ++I) {
7657 SmallStringEnc EnumEnc;
7658 EnumEnc += "m(";
7659 EnumEnc += I->getName();
7660 EnumEnc += "){";
7661 I->getInitVal().toString(EnumEnc);
7662 EnumEnc += '}';
7663 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7664 }
7665 std::sort(FE.begin(), FE.end());
7666 unsigned E = FE.size();
7667 for (unsigned I = 0; I != E; ++I) {
7668 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007669 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007670 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007671 }
7672 }
7673 Enc += '}';
7674 TSC.addIfComplete(ID, Enc.substr(Start), false);
7675 return true;
7676}
7677
7678/// Appends type's qualifier to Enc.
7679/// This is done prior to appending the type's encoding.
7680static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7681 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007682 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007683 int Lookup = 0;
7684 if (QT.isConstQualified())
7685 Lookup += 1<<0;
7686 if (QT.isRestrictQualified())
7687 Lookup += 1<<1;
7688 if (QT.isVolatileQualified())
7689 Lookup += 1<<2;
7690 Enc += Table[Lookup];
7691}
7692
7693/// Appends built-in types to Enc.
7694static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7695 const char *EncType;
7696 switch (BT->getKind()) {
7697 case BuiltinType::Void:
7698 EncType = "0";
7699 break;
7700 case BuiltinType::Bool:
7701 EncType = "b";
7702 break;
7703 case BuiltinType::Char_U:
7704 EncType = "uc";
7705 break;
7706 case BuiltinType::UChar:
7707 EncType = "uc";
7708 break;
7709 case BuiltinType::SChar:
7710 EncType = "sc";
7711 break;
7712 case BuiltinType::UShort:
7713 EncType = "us";
7714 break;
7715 case BuiltinType::Short:
7716 EncType = "ss";
7717 break;
7718 case BuiltinType::UInt:
7719 EncType = "ui";
7720 break;
7721 case BuiltinType::Int:
7722 EncType = "si";
7723 break;
7724 case BuiltinType::ULong:
7725 EncType = "ul";
7726 break;
7727 case BuiltinType::Long:
7728 EncType = "sl";
7729 break;
7730 case BuiltinType::ULongLong:
7731 EncType = "ull";
7732 break;
7733 case BuiltinType::LongLong:
7734 EncType = "sll";
7735 break;
7736 case BuiltinType::Float:
7737 EncType = "ft";
7738 break;
7739 case BuiltinType::Double:
7740 EncType = "d";
7741 break;
7742 case BuiltinType::LongDouble:
7743 EncType = "ld";
7744 break;
7745 default:
7746 return false;
7747 }
7748 Enc += EncType;
7749 return true;
7750}
7751
7752/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7753static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7754 const CodeGen::CodeGenModule &CGM,
7755 TypeStringCache &TSC) {
7756 Enc += "p(";
7757 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7758 return false;
7759 Enc += ')';
7760 return true;
7761}
7762
7763/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007764static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7765 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007766 const CodeGen::CodeGenModule &CGM,
7767 TypeStringCache &TSC, StringRef NoSizeEnc) {
7768 if (AT->getSizeModifier() != ArrayType::Normal)
7769 return false;
7770 Enc += "a(";
7771 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7772 CAT->getSize().toStringUnsigned(Enc);
7773 else
7774 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7775 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007776 // The Qualifiers should be attached to the type rather than the array.
7777 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007778 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7779 return false;
7780 Enc += ')';
7781 return true;
7782}
7783
7784/// Appends a function encoding to Enc, calling appendType for the return type
7785/// and the arguments.
7786static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7787 const CodeGen::CodeGenModule &CGM,
7788 TypeStringCache &TSC) {
7789 Enc += "f{";
7790 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7791 return false;
7792 Enc += "}(";
7793 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7794 // N.B. we are only interested in the adjusted param types.
7795 auto I = FPT->param_type_begin();
7796 auto E = FPT->param_type_end();
7797 if (I != E) {
7798 do {
7799 if (!appendType(Enc, *I, CGM, TSC))
7800 return false;
7801 ++I;
7802 if (I != E)
7803 Enc += ',';
7804 } while (I != E);
7805 if (FPT->isVariadic())
7806 Enc += ",va";
7807 } else {
7808 if (FPT->isVariadic())
7809 Enc += "va";
7810 else
7811 Enc += '0';
7812 }
7813 }
7814 Enc += ')';
7815 return true;
7816}
7817
7818/// Handles the type's qualifier before dispatching a call to handle specific
7819/// type encodings.
7820static bool appendType(SmallStringEnc &Enc, QualType QType,
7821 const CodeGen::CodeGenModule &CGM,
7822 TypeStringCache &TSC) {
7823
7824 QualType QT = QType.getCanonicalType();
7825
Robert Lytton6adb20f2014-06-05 09:06:21 +00007826 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7827 // The Qualifiers should be attached to the type rather than the array.
7828 // Thus we don't call appendQualifier() here.
7829 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7830
Robert Lytton844aeeb2014-05-02 09:33:20 +00007831 appendQualifier(Enc, QT);
7832
7833 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7834 return appendBuiltinType(Enc, BT);
7835
Robert Lytton844aeeb2014-05-02 09:33:20 +00007836 if (const PointerType *PT = QT->getAs<PointerType>())
7837 return appendPointerType(Enc, PT, CGM, TSC);
7838
7839 if (const EnumType *ET = QT->getAs<EnumType>())
7840 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7841
7842 if (const RecordType *RT = QT->getAsStructureType())
7843 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7844
7845 if (const RecordType *RT = QT->getAsUnionType())
7846 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7847
7848 if (const FunctionType *FT = QT->getAs<FunctionType>())
7849 return appendFunctionType(Enc, FT, CGM, TSC);
7850
7851 return false;
7852}
7853
7854static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7855 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7856 if (!D)
7857 return false;
7858
7859 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7860 if (FD->getLanguageLinkage() != CLanguageLinkage)
7861 return false;
7862 return appendType(Enc, FD->getType(), CGM, TSC);
7863 }
7864
7865 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7866 if (VD->getLanguageLinkage() != CLanguageLinkage)
7867 return false;
7868 QualType QT = VD->getType().getCanonicalType();
7869 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7870 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007871 // The Qualifiers should be attached to the type rather than the array.
7872 // Thus we don't call appendQualifier() here.
7873 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007874 }
7875 return appendType(Enc, QT, CGM, TSC);
7876 }
7877 return false;
7878}
7879
7880
Robert Lytton0e076492013-08-13 09:43:10 +00007881//===----------------------------------------------------------------------===//
7882// Driver code
7883//===----------------------------------------------------------------------===//
7884
Rafael Espindola9f834732014-09-19 01:54:22 +00007885const llvm::Triple &CodeGenModule::getTriple() const {
7886 return getTarget().getTriple();
7887}
7888
7889bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00007890 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00007891}
7892
Chris Lattner2b037972010-07-29 02:01:43 +00007893const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007894 if (TheTargetCodeGenInfo)
7895 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007896
Reid Kleckner9305fd12016-04-13 23:37:17 +00007897 // Helper to set the unique_ptr while still keeping the return value.
7898 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
7899 this->TheTargetCodeGenInfo.reset(P);
7900 return *P;
7901 };
7902
John McCallc8e01702013-04-16 22:48:15 +00007903 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007904 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007905 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007906 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007907
Derek Schuff09338a22012-09-06 17:37:28 +00007908 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007909 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007910 case llvm::Triple::mips:
7911 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007912 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00007913 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
7914 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007915
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007916 case llvm::Triple::mips64:
7917 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007918 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007919
Tim Northover25e8a672014-05-24 12:51:25 +00007920 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007921 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007922 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007923 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007924 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007925
Reid Kleckner9305fd12016-04-13 23:37:17 +00007926 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007927 }
7928
Dan Gohmanc2853072015-09-03 22:51:53 +00007929 case llvm::Triple::wasm32:
7930 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007931 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00007932
Daniel Dunbard59655c2009-09-12 00:59:49 +00007933 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007934 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007935 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007936 case llvm::Triple::thumbeb: {
7937 if (Triple.getOS() == llvm::Triple::Win32) {
7938 return SetCGInfo(
7939 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007940 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007941
Reid Kleckner9305fd12016-04-13 23:37:17 +00007942 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
7943 StringRef ABIStr = getTarget().getABI();
7944 if (ABIStr == "apcs-gnu")
7945 Kind = ARMABIInfo::APCS;
7946 else if (ABIStr == "aapcs16")
7947 Kind = ARMABIInfo::AAPCS16_VFP;
7948 else if (CodeGenOpts.FloatABI == "hard" ||
7949 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007950 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00007951 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007952 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00007953 Kind = ARMABIInfo::AAPCS_VFP;
7954
7955 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
7956 }
7957
John McCallea8d8bb2010-03-11 00:10:12 +00007958 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007959 return SetCGInfo(
7960 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007961 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007962 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007963 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007964 if (getTarget().getABI() == "elfv2")
7965 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007966 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007967
Reid Kleckner9305fd12016-04-13 23:37:17 +00007968 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007969 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00007970 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007971 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007972 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007973 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007974 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007975 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007976 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007977
Reid Kleckner9305fd12016-04-13 23:37:17 +00007978 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007979 }
John McCallea8d8bb2010-03-11 00:10:12 +00007980
Peter Collingbournec947aae2012-05-20 23:28:41 +00007981 case llvm::Triple::nvptx:
7982 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007983 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007984
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007985 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007986 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007987
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007988 case llvm::Triple::systemz: {
7989 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00007990 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007991 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007992
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007993 case llvm::Triple::tce:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007994 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007995
Eli Friedman33465822011-07-08 23:31:17 +00007996 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007997 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007998 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007999 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008000 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008001
John McCall1fe2a8c2013-06-18 02:46:29 +00008002 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008003 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8004 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8005 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008006 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008007 return SetCGInfo(new X86_32TargetCodeGenInfo(
8008 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8009 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8010 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008011 }
Eli Friedman33465822011-07-08 23:31:17 +00008012 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008013
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008014 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008015 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008016 X86AVXABILevel AVXLevel =
8017 (ABI == "avx512"
8018 ? X86AVXABILevel::AVX512
8019 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008020
Chris Lattner04dc9572010-08-31 16:44:54 +00008021 switch (Triple.getOS()) {
8022 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008023 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008024 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008025 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008026 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008027 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008028 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008029 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008030 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008031 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008032 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008033 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008034 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008035 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008036 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008037 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008038 case llvm::Triple::sparc:
8039 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008040 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008041 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008042 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008043 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008044 case llvm::Triple::spir:
8045 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008046 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008047 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008048}