blob: be97d648e88441e341b2490b2746132610789275 [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}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000378
379unsigned TargetCodeGenInfo::getOpenCLImageAddrSpace(CodeGen::CodeGenModule &CGM) const {
380 return CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
381}
382
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000383static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000384
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000385/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000386/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000387static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
388 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000389 if (FD->isUnnamedBitfield())
390 return true;
391
392 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000393
Eli Friedman0b3f2012011-11-18 03:47:20 +0000394 // Constant arrays of empty records count as empty, strip them off.
395 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000396 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000397 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
398 if (AT->getSize() == 0)
399 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000400 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000401 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000402
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000403 const RecordType *RT = FT->getAs<RecordType>();
404 if (!RT)
405 return false;
406
407 // C++ record fields are never empty, at least in the Itanium ABI.
408 //
409 // FIXME: We should use a predicate for whether this behavior is true in the
410 // current ABI.
411 if (isa<CXXRecordDecl>(RT->getDecl()))
412 return false;
413
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000414 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000415}
416
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000417/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000418/// fields. Note that a structure with a flexible array member is not
419/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000420static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000421 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000422 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000423 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000424 const RecordDecl *RD = RT->getDecl();
425 if (RD->hasFlexibleArrayMember())
426 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000427
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000428 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000429 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000430 for (const auto &I : CXXRD->bases())
431 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000432 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000433
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000434 for (const auto *I : RD->fields())
435 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000436 return false;
437 return true;
438}
439
440/// isSingleElementStruct - Determine if a structure is a "single
441/// element struct", i.e. it has exactly one non-empty field or
442/// exactly one field which is itself a single element
443/// struct. Structures with flexible array members are never
444/// considered single element structs.
445///
446/// \return The field declaration for the single non-empty field, if
447/// it exists.
448static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000449 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000450 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000451 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000452
453 const RecordDecl *RD = RT->getDecl();
454 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000455 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000456
Craig Topper8a13c412014-05-21 05:09:00 +0000457 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000458
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000459 // If this is a C++ record, check the bases first.
460 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000461 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000462 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000463 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000464 continue;
465
466 // If we already found an element then this isn't a single-element struct.
467 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000468 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000469
470 // If this is non-empty and not a single element struct, the composite
471 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000472 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000473 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000474 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000475 }
476 }
477
478 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000479 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000480 QualType FT = FD->getType();
481
482 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000483 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000484 continue;
485
486 // If we already found an element then this isn't a single-element
487 // struct.
488 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000489 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000490
491 // Treat single element arrays as the element.
492 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
493 if (AT->getSize().getZExtValue() != 1)
494 break;
495 FT = AT->getElementType();
496 }
497
John McCalla1dee5302010-08-22 10:59:02 +0000498 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000499 Found = FT.getTypePtr();
500 } else {
501 Found = isSingleElementStruct(FT, Context);
502 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000503 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000504 }
505 }
506
Eli Friedmanee945342011-11-18 01:25:50 +0000507 // We don't consider a struct a single-element struct if it has
508 // padding beyond the element type.
509 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000510 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000511
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000512 return Found;
513}
514
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000515namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000516Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
517 const ABIArgInfo &AI) {
518 // This default implementation defers to the llvm backend's va_arg
519 // instruction. It can handle only passing arguments directly
520 // (typically only handled in the backend for primitive types), or
521 // aggregates passed indirectly by pointer (NOTE: if the "byval"
522 // flag has ABI impact in the callee, this implementation cannot
523 // work.)
524
525 // Only a few cases are covered here at the moment -- those needed
526 // by the default abi.
527 llvm::Value *Val;
528
529 if (AI.isIndirect()) {
530 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000531 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000532 assert(
533 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000534 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000535
536 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
537 CharUnits TyAlignForABI = TyInfo.second;
538
539 llvm::Type *BaseTy =
540 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
541 llvm::Value *Addr =
542 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
543 return Address(Addr, TyAlignForABI);
544 } else {
545 assert((AI.isDirect() || AI.isExtend()) &&
546 "Unexpected ArgInfo Kind in generic VAArg emitter!");
547
548 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000549 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000550 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000551 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000552 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000553 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000554 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000555 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000556
557 Address Temp = CGF.CreateMemTemp(Ty, "varet");
558 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
559 CGF.Builder.CreateStore(Val, Temp);
560 return Temp;
561 }
562}
563
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000564/// DefaultABIInfo - The default implementation for ABI specific
565/// details. This implementation provides information which results in
566/// self-consistent and sensible LLVM IR generation, but does not
567/// conform to any particular ABI.
568class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000569public:
570 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000571
Chris Lattner458b2aa2010-07-29 02:16:43 +0000572 ABIArgInfo classifyReturnType(QualType RetTy) const;
573 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000574
Craig Topper4f12f102014-03-12 06:41:41 +0000575 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000576 if (!getCXXABI().classifyReturnType(FI))
577 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000578 for (auto &I : FI.arguments())
579 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000580 }
581
John McCall7f416cc2015-09-08 08:05:57 +0000582 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000583 QualType Ty) const override {
584 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
585 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000586};
587
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000588class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
589public:
Chris Lattner2b037972010-07-29 02:01:43 +0000590 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
591 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000592};
593
Chris Lattner458b2aa2010-07-29 02:16:43 +0000594ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000595 Ty = useFirstFieldIfTransparentUnion(Ty);
596
597 if (isAggregateTypeForABI(Ty)) {
598 // Records with non-trivial destructors/copy-constructors should not be
599 // passed by value.
600 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000601 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000602
John McCall7f416cc2015-09-08 08:05:57 +0000603 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000604 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000605
Chris Lattner9723d6c2010-03-11 18:19:55 +0000606 // Treat an enum type as its underlying type.
607 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
608 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000609
Chris Lattner9723d6c2010-03-11 18:19:55 +0000610 return (Ty->isPromotableIntegerType() ?
611 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000612}
613
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000614ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
615 if (RetTy->isVoidType())
616 return ABIArgInfo::getIgnore();
617
618 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000619 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000620
621 // Treat an enum type as its underlying type.
622 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
623 RetTy = EnumTy->getDecl()->getIntegerType();
624
625 return (RetTy->isPromotableIntegerType() ?
626 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
627}
628
Derek Schuff09338a22012-09-06 17:37:28 +0000629//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000630// WebAssembly ABI Implementation
631//
632// This is a very simple ABI that relies a lot on DefaultABIInfo.
633//===----------------------------------------------------------------------===//
634
635class WebAssemblyABIInfo final : public DefaultABIInfo {
636public:
637 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
638 : DefaultABIInfo(CGT) {}
639
640private:
641 ABIArgInfo classifyReturnType(QualType RetTy) const;
642 ABIArgInfo classifyArgumentType(QualType Ty) const;
643
644 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000645 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000646 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000647 void computeInfo(CGFunctionInfo &FI) const override {
648 if (!getCXXABI().classifyReturnType(FI))
649 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
650 for (auto &Arg : FI.arguments())
651 Arg.info = classifyArgumentType(Arg.type);
652 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000653
654 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
655 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000656};
657
658class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
659public:
660 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
661 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
662};
663
664/// \brief Classify argument of given type \p Ty.
665ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
666 Ty = useFirstFieldIfTransparentUnion(Ty);
667
668 if (isAggregateTypeForABI(Ty)) {
669 // Records with non-trivial destructors/copy-constructors should not be
670 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000671 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000672 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000673 // Ignore empty structs/unions.
674 if (isEmptyRecord(getContext(), Ty, true))
675 return ABIArgInfo::getIgnore();
676 // Lower single-element structs to just pass a regular value. TODO: We
677 // could do reasonable-size multiple-element structs too, using getExpand(),
678 // though watch out for things like bitfields.
679 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
680 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000681 }
682
683 // Otherwise just do the default thing.
684 return DefaultABIInfo::classifyArgumentType(Ty);
685}
686
687ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
688 if (isAggregateTypeForABI(RetTy)) {
689 // Records with non-trivial destructors/copy-constructors should not be
690 // returned by value.
691 if (!getRecordArgABI(RetTy, getCXXABI())) {
692 // Ignore empty structs/unions.
693 if (isEmptyRecord(getContext(), RetTy, true))
694 return ABIArgInfo::getIgnore();
695 // Lower single-element structs to just return a regular value. TODO: We
696 // could do reasonable-size multiple-element structs too, using
697 // ABIArgInfo::getDirect().
698 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
699 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
700 }
701 }
702
703 // Otherwise just do the default thing.
704 return DefaultABIInfo::classifyReturnType(RetTy);
705}
706
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000707Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
708 QualType Ty) const {
709 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
710 getContext().getTypeInfoInChars(Ty),
711 CharUnits::fromQuantity(4),
712 /*AllowHigherAlign=*/ true);
713}
714
Dan Gohmanc2853072015-09-03 22:51:53 +0000715//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000716// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000717//
718// This is a simplified version of the x86_32 ABI. Arguments and return values
719// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000720//===----------------------------------------------------------------------===//
721
722class PNaClABIInfo : public ABIInfo {
723 public:
724 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
725
726 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000727 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000728
Craig Topper4f12f102014-03-12 06:41:41 +0000729 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000730 Address EmitVAArg(CodeGenFunction &CGF,
731 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000732};
733
734class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
735 public:
736 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
737 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
738};
739
740void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000741 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000742 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
743
Reid Kleckner40ca9132014-05-13 22:05:45 +0000744 for (auto &I : FI.arguments())
745 I.info = classifyArgumentType(I.type);
746}
Derek Schuff09338a22012-09-06 17:37:28 +0000747
John McCall7f416cc2015-09-08 08:05:57 +0000748Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
749 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000750 // The PNaCL ABI is a bit odd, in that varargs don't use normal
751 // function classification. Structs get passed directly for varargs
752 // functions, through a rewriting transform in
753 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
754 // this target to actually support a va_arg instructions with an
755 // aggregate type, unlike other targets.
756 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000757}
758
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000759/// \brief Classify argument of given type \p Ty.
760ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000761 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000762 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000763 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
764 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000765 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
766 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000767 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000768 } else if (Ty->isFloatingType()) {
769 // Floating-point types don't go inreg.
770 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000771 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000772
773 return (Ty->isPromotableIntegerType() ?
774 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000775}
776
777ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
778 if (RetTy->isVoidType())
779 return ABIArgInfo::getIgnore();
780
Eli Benderskye20dad62013-04-04 22:49:35 +0000781 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000782 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000783 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000784
785 // Treat an enum type as its underlying type.
786 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
787 RetTy = EnumTy->getDecl()->getIntegerType();
788
789 return (RetTy->isPromotableIntegerType() ?
790 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
791}
792
Chad Rosier651c1832013-03-25 21:00:27 +0000793/// IsX86_MMXType - Return true if this is an MMX type.
794bool IsX86_MMXType(llvm::Type *IRType) {
795 // 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 +0000796 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
797 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
798 IRType->getScalarSizeInBits() != 64;
799}
800
Jay Foad7c57be32011-07-11 09:56:20 +0000801static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000802 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000803 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000804 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
805 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
806 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000807 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000808 }
809
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000810 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000811 }
812
813 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000814 return Ty;
815}
816
Reid Kleckner80944df2014-10-31 22:00:51 +0000817/// Returns true if this type can be passed in SSE registers with the
818/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
819static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
820 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
821 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
822 return true;
823 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
824 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
825 // registers specially.
826 unsigned VecSize = Context.getTypeSize(VT);
827 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
828 return true;
829 }
830 return false;
831}
832
833/// Returns true if this aggregate is small enough to be passed in SSE registers
834/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
835static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
836 return NumMembers <= 4;
837}
838
Chris Lattner0cf24192010-06-28 20:05:43 +0000839//===----------------------------------------------------------------------===//
840// X86-32 ABI Implementation
841//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000842
Reid Kleckner661f35b2014-01-18 01:12:41 +0000843/// \brief Similar to llvm::CCState, but for Clang.
844struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000845 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000846
847 unsigned CC;
848 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000849 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000850};
851
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000852/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000853class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000854 enum Class {
855 Integer,
856 Float
857 };
858
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000859 static const unsigned MinABIStackAlignInBytes = 4;
860
David Chisnallde3a0692009-08-17 23:08:21 +0000861 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000862 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000863 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000864 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000865 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000866 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000867
868 static bool isRegisterSize(unsigned Size) {
869 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
870 }
871
Reid Kleckner80944df2014-10-31 22:00:51 +0000872 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
873 // FIXME: Assumes vectorcall is in use.
874 return isX86VectorTypeForVectorCall(getContext(), Ty);
875 }
876
877 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
878 uint64_t NumMembers) const override {
879 // FIXME: Assumes vectorcall is in use.
880 return isX86VectorCallAggregateSmallEnough(NumMembers);
881 }
882
Reid Kleckner40ca9132014-05-13 22:05:45 +0000883 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000884
Daniel Dunbar557893d2010-04-21 19:10:51 +0000885 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
886 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000887 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
888
John McCall7f416cc2015-09-08 08:05:57 +0000889 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000890
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000891 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000892 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000893
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000894 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000895 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000896 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000897 /// \brief Updates the number of available free registers, returns
898 /// true if any registers were allocated.
899 bool updateFreeRegs(QualType Ty, CCState &State) const;
900
901 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
902 bool &NeedsPadding) const;
903 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000904
Reid Kleckner04046052016-05-02 17:41:07 +0000905 bool canExpandIndirectArgument(QualType Ty) const;
906
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000907 /// \brief Rewrite the function info so that all memory arguments use
908 /// inalloca.
909 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
910
911 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000912 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000913 QualType Type) const;
914
Rafael Espindola75419dc2012-07-23 23:30:29 +0000915public:
916
Craig Topper4f12f102014-03-12 06:41:41 +0000917 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000918 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
919 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000920
Michael Kupersteindc745202015-10-19 07:52:25 +0000921 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
922 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000923 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000924 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000925 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
926 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000927 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000928 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000929 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000930
931 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
932 ArrayRef<llvm::Type*> scalars,
933 bool asReturnValue) const override {
934 // LLVM's x86-32 lowering currently only assigns up to three
935 // integer registers and three fp registers. Oddly, it'll use up to
936 // four vector registers for vectors, but those can overlap with the
937 // scalar registers.
938 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
939 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000940};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000941
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000942class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
943public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000944 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
945 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000946 unsigned NumRegisterParameters, bool SoftFloatABI)
947 : TargetCodeGenInfo(new X86_32ABIInfo(
948 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
949 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000950
John McCall1fe2a8c2013-06-18 02:46:29 +0000951 static bool isStructReturnInRegABI(
952 const llvm::Triple &Triple, const CodeGenOptions &Opts);
953
Eric Christopher162c91c2015-06-05 22:03:00 +0000954 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000955 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000956
Craig Topper4f12f102014-03-12 06:41:41 +0000957 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000958 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000959 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000960 return 4;
961 }
962
963 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000964 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000965
Jay Foad7c57be32011-07-11 09:56:20 +0000966 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000967 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000968 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000969 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
970 }
971
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000972 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
973 std::string &Constraints,
974 std::vector<llvm::Type *> &ResultRegTypes,
975 std::vector<llvm::Type *> &ResultTruncRegTypes,
976 std::vector<LValue> &ResultRegDests,
977 std::string &AsmString,
978 unsigned NumOutputs) const override;
979
Craig Topper4f12f102014-03-12 06:41:41 +0000980 llvm::Constant *
981 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000982 unsigned Sig = (0xeb << 0) | // jmp rel8
983 (0x06 << 8) | // .+0x08
984 ('F' << 16) |
985 ('T' << 24);
986 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
987 }
John McCall01391782016-02-05 21:37:38 +0000988
989 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
990 return "movl\t%ebp, %ebp"
991 "\t\t## marker for objc_retainAutoreleaseReturnValue";
992 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000993};
994
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000995}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000996
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000997/// Rewrite input constraint references after adding some output constraints.
998/// In the case where there is one output and one input and we add one output,
999/// we need to replace all operand references greater than or equal to 1:
1000/// mov $0, $1
1001/// mov eax, $1
1002/// The result will be:
1003/// mov $0, $2
1004/// mov eax, $2
1005static void rewriteInputConstraintReferences(unsigned FirstIn,
1006 unsigned NumNewOuts,
1007 std::string &AsmString) {
1008 std::string Buf;
1009 llvm::raw_string_ostream OS(Buf);
1010 size_t Pos = 0;
1011 while (Pos < AsmString.size()) {
1012 size_t DollarStart = AsmString.find('$', Pos);
1013 if (DollarStart == std::string::npos)
1014 DollarStart = AsmString.size();
1015 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1016 if (DollarEnd == std::string::npos)
1017 DollarEnd = AsmString.size();
1018 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1019 Pos = DollarEnd;
1020 size_t NumDollars = DollarEnd - DollarStart;
1021 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1022 // We have an operand reference.
1023 size_t DigitStart = Pos;
1024 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1025 if (DigitEnd == std::string::npos)
1026 DigitEnd = AsmString.size();
1027 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1028 unsigned OperandIndex;
1029 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1030 if (OperandIndex >= FirstIn)
1031 OperandIndex += NumNewOuts;
1032 OS << OperandIndex;
1033 } else {
1034 OS << OperandStr;
1035 }
1036 Pos = DigitEnd;
1037 }
1038 }
1039 AsmString = std::move(OS.str());
1040}
1041
1042/// Add output constraints for EAX:EDX because they are return registers.
1043void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1044 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1045 std::vector<llvm::Type *> &ResultRegTypes,
1046 std::vector<llvm::Type *> &ResultTruncRegTypes,
1047 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1048 unsigned NumOutputs) const {
1049 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1050
1051 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1052 // larger.
1053 if (!Constraints.empty())
1054 Constraints += ',';
1055 if (RetWidth <= 32) {
1056 Constraints += "={eax}";
1057 ResultRegTypes.push_back(CGF.Int32Ty);
1058 } else {
1059 // Use the 'A' constraint for EAX:EDX.
1060 Constraints += "=A";
1061 ResultRegTypes.push_back(CGF.Int64Ty);
1062 }
1063
1064 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1065 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1066 ResultTruncRegTypes.push_back(CoerceTy);
1067
1068 // Coerce the integer by bitcasting the return slot pointer.
1069 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1070 CoerceTy->getPointerTo()));
1071 ResultRegDests.push_back(ReturnSlot);
1072
1073 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1074}
1075
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001076/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001077/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001078bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1079 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001080 uint64_t Size = Context.getTypeSize(Ty);
1081
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001082 // For i386, type must be register sized.
1083 // For the MCU ABI, it only needs to be <= 8-byte
1084 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1085 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001086
1087 if (Ty->isVectorType()) {
1088 // 64- and 128- bit vectors inside structures are not returned in
1089 // registers.
1090 if (Size == 64 || Size == 128)
1091 return false;
1092
1093 return true;
1094 }
1095
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001096 // If this is a builtin, pointer, enum, complex type, member pointer, or
1097 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001098 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001099 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001100 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101 return true;
1102
1103 // Arrays are treated like records.
1104 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001105 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106
1107 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001108 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001109 if (!RT) return false;
1110
Anders Carlsson40446e82010-01-27 03:25:19 +00001111 // FIXME: Traverse bases here too.
1112
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001113 // Structure types are passed in register if all fields would be
1114 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001115 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001117 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001118 continue;
1119
1120 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001121 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001122 return false;
1123 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001124 return true;
1125}
1126
Reid Kleckner04046052016-05-02 17:41:07 +00001127static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1128 // Treat complex types as the element type.
1129 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1130 Ty = CTy->getElementType();
1131
1132 // Check for a type which we know has a simple scalar argument-passing
1133 // convention without any padding. (We're specifically looking for 32
1134 // and 64-bit integer and integer-equivalents, float, and double.)
1135 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1136 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1137 return false;
1138
1139 uint64_t Size = Context.getTypeSize(Ty);
1140 return Size == 32 || Size == 64;
1141}
1142
1143/// Test whether an argument type which is to be passed indirectly (on the
1144/// stack) would have the equivalent layout if it was expanded into separate
1145/// arguments. If so, we prefer to do the latter to avoid inhibiting
1146/// optimizations.
1147bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1148 // We can only expand structure types.
1149 const RecordType *RT = Ty->getAs<RecordType>();
1150 if (!RT)
1151 return false;
1152 const RecordDecl *RD = RT->getDecl();
1153 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1154 if (!IsWin32StructABI ) {
1155 // On non-Windows, we have to conservatively match our old bitcode
1156 // prototypes in order to be ABI-compatible at the bitcode level.
1157 if (!CXXRD->isCLike())
1158 return false;
1159 } else {
1160 // Don't do this for dynamic classes.
1161 if (CXXRD->isDynamicClass())
1162 return false;
1163 // Don't do this if there are any non-empty bases.
1164 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1165 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1166 return false;
1167 }
1168 }
1169 }
1170
1171 uint64_t Size = 0;
1172
1173 for (const auto *FD : RD->fields()) {
1174 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1175 // argument is smaller than 32-bits, expanding the struct will create
1176 // alignment padding.
1177 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1178 return false;
1179
1180 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1181 // how to expand them yet, and the predicate for telling if a bitfield still
1182 // counts as "basic" is more complicated than what we were doing previously.
1183 if (FD->isBitField())
1184 return false;
1185
1186 Size += getContext().getTypeSize(FD->getType());
1187 }
1188
1189 // We can do this if there was no alignment padding.
1190 return Size == getContext().getTypeSize(Ty);
1191}
1192
John McCall7f416cc2015-09-08 08:05:57 +00001193ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001194 // If the return value is indirect, then the hidden argument is consuming one
1195 // integer register.
1196 if (State.FreeRegs) {
1197 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001198 if (!IsMCUABI)
1199 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001200 }
John McCall7f416cc2015-09-08 08:05:57 +00001201 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001202}
1203
Eric Christopher7565e0d2015-05-29 23:09:49 +00001204ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1205 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001206 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001207 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001208
Reid Kleckner80944df2014-10-31 22:00:51 +00001209 const Type *Base = nullptr;
1210 uint64_t NumElts = 0;
1211 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1212 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1213 // The LLVM struct type for such an aggregate should lower properly.
1214 return ABIArgInfo::getDirect();
1215 }
1216
Chris Lattner458b2aa2010-07-29 02:16:43 +00001217 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001218 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001219 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001220 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001221
1222 // 128-bit vectors are a special case; they are returned in
1223 // registers and we need to make sure to pick a type the LLVM
1224 // backend will like.
1225 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001226 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001227 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001228
1229 // Always return in register if it fits in a general purpose
1230 // register, or if it is 64 bits and has a single element.
1231 if ((Size == 8 || Size == 16 || Size == 32) ||
1232 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001233 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001234 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001235
John McCall7f416cc2015-09-08 08:05:57 +00001236 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001237 }
1238
1239 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001240 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001241
John McCalla1dee5302010-08-22 10:59:02 +00001242 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001243 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001244 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001245 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001246 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001247 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001248
David Chisnallde3a0692009-08-17 23:08:21 +00001249 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001250 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001251 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001252
Denis Zobnin380b2242016-02-11 11:26:03 +00001253 // Ignore empty structs/unions.
1254 if (isEmptyRecord(getContext(), RetTy, true))
1255 return ABIArgInfo::getIgnore();
1256
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001257 // Small structures which are register sized are generally returned
1258 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001259 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001260 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001261
1262 // As a special-case, if the struct is a "single-element" struct, and
1263 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001264 // floating-point register. (MSVC does not apply this special case.)
1265 // We apply a similar transformation for pointer types to improve the
1266 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001267 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001268 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001269 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001270 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1271
1272 // FIXME: We should be able to narrow this integer in cases with dead
1273 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001274 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001275 }
1276
John McCall7f416cc2015-09-08 08:05:57 +00001277 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001279
Chris Lattner458b2aa2010-07-29 02:16:43 +00001280 // Treat an enum type as its underlying type.
1281 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1282 RetTy = EnumTy->getDecl()->getIntegerType();
1283
1284 return (RetTy->isPromotableIntegerType() ?
1285 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001286}
1287
Eli Friedman7919bea2012-06-05 19:40:46 +00001288static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1289 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1290}
1291
Daniel Dunbared23de32010-09-16 20:42:00 +00001292static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1293 const RecordType *RT = Ty->getAs<RecordType>();
1294 if (!RT)
1295 return 0;
1296 const RecordDecl *RD = RT->getDecl();
1297
1298 // If this is a C++ record, check the bases first.
1299 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001300 for (const auto &I : CXXRD->bases())
1301 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001302 return false;
1303
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001304 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001305 QualType FT = i->getType();
1306
Eli Friedman7919bea2012-06-05 19:40:46 +00001307 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001308 return true;
1309
1310 if (isRecordWithSSEVectorType(Context, FT))
1311 return true;
1312 }
1313
1314 return false;
1315}
1316
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001317unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1318 unsigned Align) const {
1319 // Otherwise, if the alignment is less than or equal to the minimum ABI
1320 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001321 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001322 return 0; // Use default alignment.
1323
1324 // On non-Darwin, the stack type alignment is always 4.
1325 if (!IsDarwinVectorABI) {
1326 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001327 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001328 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001329
Daniel Dunbared23de32010-09-16 20:42:00 +00001330 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001331 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1332 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001333 return 16;
1334
1335 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001336}
1337
Rafael Espindola703c47f2012-10-19 05:04:37 +00001338ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001339 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001340 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001341 if (State.FreeRegs) {
1342 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001343 if (!IsMCUABI)
1344 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001345 }
John McCall7f416cc2015-09-08 08:05:57 +00001346 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001347 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001348
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001349 // Compute the byval alignment.
1350 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1351 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1352 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001353 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001354
1355 // If the stack alignment is less than the type alignment, realign the
1356 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001357 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001358 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1359 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001360}
1361
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001362X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1363 const Type *T = isSingleElementStruct(Ty, getContext());
1364 if (!T)
1365 T = Ty.getTypePtr();
1366
1367 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1368 BuiltinType::Kind K = BT->getKind();
1369 if (K == BuiltinType::Float || K == BuiltinType::Double)
1370 return Float;
1371 }
1372 return Integer;
1373}
1374
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001375bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001376 if (!IsSoftFloatABI) {
1377 Class C = classify(Ty);
1378 if (C == Float)
1379 return false;
1380 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001381
Rafael Espindola077dd592012-10-24 01:58:58 +00001382 unsigned Size = getContext().getTypeSize(Ty);
1383 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001384
1385 if (SizeInRegs == 0)
1386 return false;
1387
Michael Kuperstein68901882015-10-25 08:18:20 +00001388 if (!IsMCUABI) {
1389 if (SizeInRegs > State.FreeRegs) {
1390 State.FreeRegs = 0;
1391 return false;
1392 }
1393 } else {
1394 // The MCU psABI allows passing parameters in-reg even if there are
1395 // earlier parameters that are passed on the stack. Also,
1396 // it does not allow passing >8-byte structs in-register,
1397 // even if there are 3 free registers available.
1398 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1399 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001400 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001401
Reid Kleckner661f35b2014-01-18 01:12:41 +00001402 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001403 return true;
1404}
1405
1406bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1407 bool &InReg,
1408 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001409 // On Windows, aggregates other than HFAs are never passed in registers, and
1410 // they do not consume register slots. Homogenous floating-point aggregates
1411 // (HFAs) have already been dealt with at this point.
1412 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1413 return false;
1414
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001415 NeedsPadding = false;
1416 InReg = !IsMCUABI;
1417
1418 if (!updateFreeRegs(Ty, State))
1419 return false;
1420
1421 if (IsMCUABI)
1422 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001423
Reid Kleckner80944df2014-10-31 22:00:51 +00001424 if (State.CC == llvm::CallingConv::X86_FastCall ||
1425 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001426 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001427 NeedsPadding = true;
1428
Rafael Espindola077dd592012-10-24 01:58:58 +00001429 return false;
1430 }
1431
Rafael Espindola703c47f2012-10-19 05:04:37 +00001432 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001433}
1434
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001435bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1436 if (!updateFreeRegs(Ty, State))
1437 return false;
1438
1439 if (IsMCUABI)
1440 return false;
1441
1442 if (State.CC == llvm::CallingConv::X86_FastCall ||
1443 State.CC == llvm::CallingConv::X86_VectorCall) {
1444 if (getContext().getTypeSize(Ty) > 32)
1445 return false;
1446
1447 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1448 Ty->isReferenceType());
1449 }
1450
1451 return true;
1452}
1453
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001454ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1455 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001456 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001457
Reid Klecknerb1be6832014-11-15 01:41:41 +00001458 Ty = useFirstFieldIfTransparentUnion(Ty);
1459
Reid Kleckner80944df2014-10-31 22:00:51 +00001460 // Check with the C++ ABI first.
1461 const RecordType *RT = Ty->getAs<RecordType>();
1462 if (RT) {
1463 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1464 if (RAA == CGCXXABI::RAA_Indirect) {
1465 return getIndirectResult(Ty, false, State);
1466 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1467 // The field index doesn't matter, we'll fix it up later.
1468 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1469 }
1470 }
1471
1472 // vectorcall adds the concept of a homogenous vector aggregate, similar
1473 // to other targets.
1474 const Type *Base = nullptr;
1475 uint64_t NumElts = 0;
1476 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1477 isHomogeneousAggregate(Ty, Base, NumElts)) {
1478 if (State.FreeSSERegs >= NumElts) {
1479 State.FreeSSERegs -= NumElts;
1480 if (Ty->isBuiltinType() || Ty->isVectorType())
1481 return ABIArgInfo::getDirect();
1482 return ABIArgInfo::getExpand();
1483 }
1484 return getIndirectResult(Ty, /*ByVal=*/false, State);
1485 }
1486
1487 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001488 // Structures with flexible arrays are always indirect.
1489 // FIXME: This should not be byval!
1490 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1491 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001492
Reid Kleckner04046052016-05-02 17:41:07 +00001493 // Ignore empty structs/unions on non-Windows.
1494 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001495 return ABIArgInfo::getIgnore();
1496
Rafael Espindolafad28de2012-10-24 01:59:00 +00001497 llvm::LLVMContext &LLVMContext = getVMContext();
1498 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001499 bool NeedsPadding = false;
1500 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001501 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001502 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001503 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001504 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001505 if (InReg)
1506 return ABIArgInfo::getDirectInReg(Result);
1507 else
1508 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001509 }
Craig Topper8a13c412014-05-21 05:09:00 +00001510 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001511
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001512 // Expand small (<= 128-bit) record types when we know that the stack layout
1513 // of those arguments will match the struct. This is important because the
1514 // LLVM backend isn't smart enough to remove byval, which inhibits many
1515 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001516 // Don't do this for the MCU if there are still free integer registers
1517 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001518 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1519 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001520 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001521 State.CC == llvm::CallingConv::X86_FastCall ||
1522 State.CC == llvm::CallingConv::X86_VectorCall,
1523 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001524
Reid Kleckner661f35b2014-01-18 01:12:41 +00001525 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001526 }
1527
Chris Lattnerd774ae92010-08-26 20:05:13 +00001528 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001529 // On Darwin, some vectors are passed in memory, we handle this by passing
1530 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001531 if (IsDarwinVectorABI) {
1532 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001533 if ((Size == 8 || Size == 16 || Size == 32) ||
1534 (Size == 64 && VT->getNumElements() == 1))
1535 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1536 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001537 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001538
Chad Rosier651c1832013-03-25 21:00:27 +00001539 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1540 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001541
Chris Lattnerd774ae92010-08-26 20:05:13 +00001542 return ABIArgInfo::getDirect();
1543 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001544
1545
Chris Lattner458b2aa2010-07-29 02:16:43 +00001546 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1547 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001548
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001549 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001550
1551 if (Ty->isPromotableIntegerType()) {
1552 if (InReg)
1553 return ABIArgInfo::getExtendInReg();
1554 return ABIArgInfo::getExtend();
1555 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001556
Rafael Espindola703c47f2012-10-19 05:04:37 +00001557 if (InReg)
1558 return ABIArgInfo::getDirectInReg();
1559 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001560}
1561
Rafael Espindolaa6472962012-07-24 00:01:07 +00001562void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001563 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001564 if (IsMCUABI)
1565 State.FreeRegs = 3;
1566 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001567 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001568 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1569 State.FreeRegs = 2;
1570 State.FreeSSERegs = 6;
1571 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001572 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001573 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001574 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001575
Reid Kleckner677539d2014-07-10 01:58:55 +00001576 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001577 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001578 } else if (FI.getReturnInfo().isIndirect()) {
1579 // The C++ ABI is not aware of register usage, so we have to check if the
1580 // return value was sret and put it in a register ourselves if appropriate.
1581 if (State.FreeRegs) {
1582 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001583 if (!IsMCUABI)
1584 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001585 }
1586 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001587
Peter Collingbournef7706832014-12-12 23:41:25 +00001588 // The chain argument effectively gives us another free register.
1589 if (FI.isChainCall())
1590 ++State.FreeRegs;
1591
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001592 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001593 for (auto &I : FI.arguments()) {
1594 I.info = classifyArgumentType(I.type, State);
1595 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001596 }
1597
1598 // If we needed to use inalloca for any argument, do a second pass and rewrite
1599 // all the memory arguments to use inalloca.
1600 if (UsedInAlloca)
1601 rewriteWithInAlloca(FI);
1602}
1603
1604void
1605X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001606 CharUnits &StackOffset, ABIArgInfo &Info,
1607 QualType Type) const {
1608 // Arguments are always 4-byte-aligned.
1609 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1610
1611 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001612 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1613 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001614 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001615
John McCall7f416cc2015-09-08 08:05:57 +00001616 // Insert padding bytes to respect alignment.
1617 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001618 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001619 if (StackOffset != FieldEnd) {
1620 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001621 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001622 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001623 FrameFields.push_back(Ty);
1624 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001625}
1626
Reid Kleckner852361d2014-07-26 00:12:26 +00001627static bool isArgInAlloca(const ABIArgInfo &Info) {
1628 // Leave ignored and inreg arguments alone.
1629 switch (Info.getKind()) {
1630 case ABIArgInfo::InAlloca:
1631 return true;
1632 case ABIArgInfo::Indirect:
1633 assert(Info.getIndirectByVal());
1634 return true;
1635 case ABIArgInfo::Ignore:
1636 return false;
1637 case ABIArgInfo::Direct:
1638 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001639 if (Info.getInReg())
1640 return false;
1641 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001642 case ABIArgInfo::Expand:
1643 case ABIArgInfo::CoerceAndExpand:
1644 // These are aggregate types which are never passed in registers when
1645 // inalloca is involved.
1646 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001647 }
1648 llvm_unreachable("invalid enum");
1649}
1650
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001651void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1652 assert(IsWin32StructABI && "inalloca only supported on win32");
1653
1654 // Build a packed struct type for all of the arguments in memory.
1655 SmallVector<llvm::Type *, 6> FrameFields;
1656
John McCall7f416cc2015-09-08 08:05:57 +00001657 // The stack alignment is always 4.
1658 CharUnits StackAlign = CharUnits::fromQuantity(4);
1659
1660 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001661 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1662
1663 // Put 'this' into the struct before 'sret', if necessary.
1664 bool IsThisCall =
1665 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1666 ABIArgInfo &Ret = FI.getReturnInfo();
1667 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1668 isArgInAlloca(I->info)) {
1669 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1670 ++I;
1671 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001672
1673 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001674 if (Ret.isIndirect() && !Ret.getInReg()) {
1675 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1676 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001677 // On Windows, the hidden sret parameter is always returned in eax.
1678 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001679 }
1680
1681 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001682 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001683 ++I;
1684
1685 // Put arguments passed in memory into the struct.
1686 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001687 if (isArgInAlloca(I->info))
1688 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001689 }
1690
1691 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001692 /*isPacked=*/true),
1693 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001694}
1695
John McCall7f416cc2015-09-08 08:05:57 +00001696Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1697 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001698
John McCall7f416cc2015-09-08 08:05:57 +00001699 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001700
John McCall7f416cc2015-09-08 08:05:57 +00001701 // x86-32 changes the alignment of certain arguments on the stack.
1702 //
1703 // Just messing with TypeInfo like this works because we never pass
1704 // anything indirectly.
1705 TypeInfo.second = CharUnits::fromQuantity(
1706 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001707
John McCall7f416cc2015-09-08 08:05:57 +00001708 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1709 TypeInfo, CharUnits::fromQuantity(4),
1710 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001711}
1712
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001713bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1714 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1715 assert(Triple.getArch() == llvm::Triple::x86);
1716
1717 switch (Opts.getStructReturnConvention()) {
1718 case CodeGenOptions::SRCK_Default:
1719 break;
1720 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1721 return false;
1722 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1723 return true;
1724 }
1725
Michael Kupersteind749f232015-10-27 07:46:22 +00001726 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001727 return true;
1728
1729 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001730 case llvm::Triple::DragonFly:
1731 case llvm::Triple::FreeBSD:
1732 case llvm::Triple::OpenBSD:
1733 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001734 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001735 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001736 default:
1737 return false;
1738 }
1739}
1740
Eric Christopher162c91c2015-06-05 22:03:00 +00001741void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001742 llvm::GlobalValue *GV,
1743 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001744 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001745 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1746 // Get the LLVM function.
1747 llvm::Function *Fn = cast<llvm::Function>(GV);
1748
1749 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001750 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001751 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001752 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1753 llvm::AttributeSet::get(CGM.getLLVMContext(),
1754 llvm::AttributeSet::FunctionIndex,
1755 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001756 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001757 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1758 llvm::Function *Fn = cast<llvm::Function>(GV);
1759 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1760 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001761 }
1762}
1763
John McCallbeec5a02010-03-06 00:35:14 +00001764bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1765 CodeGen::CodeGenFunction &CGF,
1766 llvm::Value *Address) const {
1767 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001768
Chris Lattnerece04092012-02-07 00:39:47 +00001769 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001770
John McCallbeec5a02010-03-06 00:35:14 +00001771 // 0-7 are the eight integer registers; the order is different
1772 // on Darwin (for EH), but the range is the same.
1773 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001774 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001775
John McCallc8e01702013-04-16 22:48:15 +00001776 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001777 // 12-16 are st(0..4). Not sure why we stop at 4.
1778 // These have size 16, which is sizeof(long double) on
1779 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001780 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001781 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001782
John McCallbeec5a02010-03-06 00:35:14 +00001783 } else {
1784 // 9 is %eflags, which doesn't get a size on Darwin for some
1785 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001786 Builder.CreateAlignedStore(
1787 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1788 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001789
1790 // 11-16 are st(0..5). Not sure why we stop at 5.
1791 // These have size 12, which is sizeof(long double) on
1792 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001793 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001794 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1795 }
John McCallbeec5a02010-03-06 00:35:14 +00001796
1797 return false;
1798}
1799
Chris Lattner0cf24192010-06-28 20:05:43 +00001800//===----------------------------------------------------------------------===//
1801// X86-64 ABI Implementation
1802//===----------------------------------------------------------------------===//
1803
1804
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001805namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001806/// The AVX ABI level for X86 targets.
1807enum class X86AVXABILevel {
1808 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001809 AVX,
1810 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001811};
1812
1813/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1814static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1815 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001816 case X86AVXABILevel::AVX512:
1817 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001818 case X86AVXABILevel::AVX:
1819 return 256;
1820 case X86AVXABILevel::None:
1821 return 128;
1822 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001823 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001824}
1825
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001826/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001827class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001828 enum Class {
1829 Integer = 0,
1830 SSE,
1831 SSEUp,
1832 X87,
1833 X87Up,
1834 ComplexX87,
1835 NoClass,
1836 Memory
1837 };
1838
1839 /// merge - Implement the X86_64 ABI merging algorithm.
1840 ///
1841 /// Merge an accumulating classification \arg Accum with a field
1842 /// classification \arg Field.
1843 ///
1844 /// \param Accum - The accumulating classification. This should
1845 /// always be either NoClass or the result of a previous merge
1846 /// call. In addition, this should never be Memory (the caller
1847 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001848 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001849
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001850 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1851 ///
1852 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1853 /// final MEMORY or SSE classes when necessary.
1854 ///
1855 /// \param AggregateSize - The size of the current aggregate in
1856 /// the classification process.
1857 ///
1858 /// \param Lo - The classification for the parts of the type
1859 /// residing in the low word of the containing object.
1860 ///
1861 /// \param Hi - The classification for the parts of the type
1862 /// residing in the higher words of the containing object.
1863 ///
1864 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1865
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001866 /// classify - Determine the x86_64 register classes in which the
1867 /// given type T should be passed.
1868 ///
1869 /// \param Lo - The classification for the parts of the type
1870 /// residing in the low word of the containing object.
1871 ///
1872 /// \param Hi - The classification for the parts of the type
1873 /// residing in the high word of the containing object.
1874 ///
1875 /// \param OffsetBase - The bit offset of this type in the
1876 /// containing object. Some parameters are classified different
1877 /// depending on whether they straddle an eightbyte boundary.
1878 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001879 /// \param isNamedArg - Whether the argument in question is a "named"
1880 /// argument, as used in AMD64-ABI 3.5.7.
1881 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001882 /// If a word is unused its result will be NoClass; if a type should
1883 /// be passed in Memory then at least the classification of \arg Lo
1884 /// will be Memory.
1885 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001886 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001887 ///
1888 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1889 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001890 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1891 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001892
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001893 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001894 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1895 unsigned IROffset, QualType SourceTy,
1896 unsigned SourceOffset) const;
1897 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1898 unsigned IROffset, QualType SourceTy,
1899 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001900
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001901 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001902 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001903 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001904
1905 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001906 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001907 ///
1908 /// \param freeIntRegs - The number of free integer registers remaining
1909 /// available.
1910 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001911
Chris Lattner458b2aa2010-07-29 02:16:43 +00001912 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001913
Bill Wendling5cd41c42010-10-18 03:41:31 +00001914 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001915 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001916 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001917 unsigned &neededSSE,
1918 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001919
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001920 bool IsIllegalVectorType(QualType Ty) const;
1921
John McCalle0fda732011-04-21 01:20:55 +00001922 /// The 0.98 ABI revision clarified a lot of ambiguities,
1923 /// unfortunately in ways that were not always consistent with
1924 /// certain previous compilers. In particular, platforms which
1925 /// required strict binary compatibility with older versions of GCC
1926 /// may need to exempt themselves.
1927 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001928 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001929 }
1930
David Majnemere2ae2282016-03-04 05:26:16 +00001931 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1932 // compilers require us to classify it as INTEGER.
1933 bool classifyIntegerMMXAsSSE() const {
1934 const llvm::Triple &Triple = getTarget().getTriple();
1935 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1936 return false;
1937 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1938 return false;
1939 return true;
1940 }
1941
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001942 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001943 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1944 // 64-bit hardware.
1945 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001946
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001947public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001948 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001949 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001950 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001951 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001952
John McCalla729c622012-02-17 03:33:10 +00001953 bool isPassedUsingAVXType(QualType type) const {
1954 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001955 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001956 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1957 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001958 if (info.isDirect()) {
1959 llvm::Type *ty = info.getCoerceToType();
1960 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1961 return (vectorTy->getBitWidth() > 128);
1962 }
1963 return false;
1964 }
1965
Craig Topper4f12f102014-03-12 06:41:41 +00001966 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001967
John McCall7f416cc2015-09-08 08:05:57 +00001968 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1969 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001970 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1971 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001972
1973 bool has64BitPointers() const {
1974 return Has64BitPointers;
1975 }
John McCall12f23522016-04-04 18:33:08 +00001976
1977 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1978 ArrayRef<llvm::Type*> scalars,
1979 bool asReturnValue) const override {
1980 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
1981 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001982};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001983
Chris Lattner04dc9572010-08-31 16:44:54 +00001984/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001985class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001986public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001987 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1988 : ABIInfo(CGT),
1989 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001990
Craig Topper4f12f102014-03-12 06:41:41 +00001991 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001992
John McCall7f416cc2015-09-08 08:05:57 +00001993 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1994 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001995
1996 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1997 // FIXME: Assumes vectorcall is in use.
1998 return isX86VectorTypeForVectorCall(getContext(), Ty);
1999 }
2000
2001 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2002 uint64_t NumMembers) const override {
2003 // FIXME: Assumes vectorcall is in use.
2004 return isX86VectorCallAggregateSmallEnough(NumMembers);
2005 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002006
2007private:
2008 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2009 bool IsReturnType) const;
2010
2011 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002012};
2013
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002014class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2015public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002016 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002017 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002018
John McCalla729c622012-02-17 03:33:10 +00002019 const X86_64ABIInfo &getABIInfo() const {
2020 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2021 }
2022
Craig Topper4f12f102014-03-12 06:41:41 +00002023 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002024 return 7;
2025 }
2026
2027 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002028 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002029 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002030
John McCall943fae92010-05-27 06:19:26 +00002031 // 0-15 are the 16 integer registers.
2032 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002033 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002034 return false;
2035 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002036
Jay Foad7c57be32011-07-11 09:56:20 +00002037 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002038 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002039 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002040 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2041 }
2042
John McCalla729c622012-02-17 03:33:10 +00002043 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002044 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002045 // The default CC on x86-64 sets %al to the number of SSA
2046 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002047 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002048 // that when AVX types are involved: the ABI explicitly states it is
2049 // undefined, and it doesn't work in practice because of how the ABI
2050 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002051 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002052 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002053 for (CallArgList::const_iterator
2054 it = args.begin(), ie = args.end(); it != ie; ++it) {
2055 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2056 HasAVXType = true;
2057 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002058 }
2059 }
John McCalla729c622012-02-17 03:33:10 +00002060
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002061 if (!HasAVXType)
2062 return true;
2063 }
John McCallcbc038a2011-09-21 08:08:30 +00002064
John McCalla729c622012-02-17 03:33:10 +00002065 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002066 }
2067
Craig Topper4f12f102014-03-12 06:41:41 +00002068 llvm::Constant *
2069 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002070 unsigned Sig;
2071 if (getABIInfo().has64BitPointers())
2072 Sig = (0xeb << 0) | // jmp rel8
2073 (0x0a << 8) | // .+0x0c
2074 ('F' << 16) |
2075 ('T' << 24);
2076 else
2077 Sig = (0xeb << 0) | // jmp rel8
2078 (0x06 << 8) | // .+0x08
2079 ('F' << 16) |
2080 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002081 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2082 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002083
2084 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2085 CodeGen::CodeGenModule &CGM) const override {
2086 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2087 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2088 llvm::Function *Fn = cast<llvm::Function>(GV);
2089 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2090 }
2091 }
2092 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002093};
2094
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002095class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2096public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002097 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2098 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002099
2100 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002101 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002102 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002103 // If the argument contains a space, enclose it in quotes.
2104 if (Lib.find(" ") != StringRef::npos)
2105 Opt += "\"" + Lib.str() + "\"";
2106 else
2107 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002108 }
2109};
2110
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002111static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002112 // If the argument does not end in .lib, automatically add the suffix.
2113 // If the argument contains a space, enclose it in quotes.
2114 // This matches the behavior of MSVC.
2115 bool Quote = (Lib.find(" ") != StringRef::npos);
2116 std::string ArgStr = Quote ? "\"" : "";
2117 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002118 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002119 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002120 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002121 return ArgStr;
2122}
2123
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002124class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2125public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002126 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002127 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2128 unsigned NumRegisterParameters)
2129 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002130 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002131
Eric Christopher162c91c2015-06-05 22:03:00 +00002132 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002133 CodeGen::CodeGenModule &CGM) const override;
2134
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002135 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002136 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002137 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002138 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002139 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002140
2141 void getDetectMismatchOption(llvm::StringRef Name,
2142 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002143 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002144 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002145 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002146};
2147
Hans Wennborg77dc2362015-01-20 19:45:50 +00002148static void addStackProbeSizeTargetAttribute(const Decl *D,
2149 llvm::GlobalValue *GV,
2150 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002151 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002152 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2153 llvm::Function *Fn = cast<llvm::Function>(GV);
2154
Eric Christopher7565e0d2015-05-29 23:09:49 +00002155 Fn->addFnAttr("stack-probe-size",
2156 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002157 }
2158 }
2159}
2160
Eric Christopher162c91c2015-06-05 22:03:00 +00002161void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002162 llvm::GlobalValue *GV,
2163 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002164 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002165
2166 addStackProbeSizeTargetAttribute(D, GV, CGM);
2167}
2168
Chris Lattner04dc9572010-08-31 16:44:54 +00002169class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2170public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002171 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2172 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002173 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002174
Eric Christopher162c91c2015-06-05 22:03:00 +00002175 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002176 CodeGen::CodeGenModule &CGM) const override;
2177
Craig Topper4f12f102014-03-12 06:41:41 +00002178 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002179 return 7;
2180 }
2181
2182 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002183 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002184 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002185
Chris Lattner04dc9572010-08-31 16:44:54 +00002186 // 0-15 are the 16 integer registers.
2187 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002188 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002189 return false;
2190 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002191
2192 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002193 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002194 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002195 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002196 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002197
2198 void getDetectMismatchOption(llvm::StringRef Name,
2199 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002200 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002201 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002202 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002203};
2204
Eric Christopher162c91c2015-06-05 22:03:00 +00002205void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002206 llvm::GlobalValue *GV,
2207 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002208 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002209
Alexey Bataevd51e9932016-01-15 04:06:31 +00002210 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2211 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2212 llvm::Function *Fn = cast<llvm::Function>(GV);
2213 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2214 }
2215 }
2216
Hans Wennborg77dc2362015-01-20 19:45:50 +00002217 addStackProbeSizeTargetAttribute(D, GV, CGM);
2218}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002219}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002220
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002221void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2222 Class &Hi) const {
2223 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2224 //
2225 // (a) If one of the classes is Memory, the whole argument is passed in
2226 // memory.
2227 //
2228 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2229 // memory.
2230 //
2231 // (c) If the size of the aggregate exceeds two eightbytes and the first
2232 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2233 // argument is passed in memory. NOTE: This is necessary to keep the
2234 // ABI working for processors that don't support the __m256 type.
2235 //
2236 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2237 //
2238 // Some of these are enforced by the merging logic. Others can arise
2239 // only with unions; for example:
2240 // union { _Complex double; unsigned; }
2241 //
2242 // Note that clauses (b) and (c) were added in 0.98.
2243 //
2244 if (Hi == Memory)
2245 Lo = Memory;
2246 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2247 Lo = Memory;
2248 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2249 Lo = Memory;
2250 if (Hi == SSEUp && Lo != SSE)
2251 Hi = SSE;
2252}
2253
Chris Lattnerd776fb12010-06-28 21:43:59 +00002254X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002255 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2256 // classified recursively so that always two fields are
2257 // considered. The resulting class is calculated according to
2258 // the classes of the fields in the eightbyte:
2259 //
2260 // (a) If both classes are equal, this is the resulting class.
2261 //
2262 // (b) If one of the classes is NO_CLASS, the resulting class is
2263 // the other class.
2264 //
2265 // (c) If one of the classes is MEMORY, the result is the MEMORY
2266 // class.
2267 //
2268 // (d) If one of the classes is INTEGER, the result is the
2269 // INTEGER.
2270 //
2271 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2272 // MEMORY is used as class.
2273 //
2274 // (f) Otherwise class SSE is used.
2275
2276 // Accum should never be memory (we should have returned) or
2277 // ComplexX87 (because this cannot be passed in a structure).
2278 assert((Accum != Memory && Accum != ComplexX87) &&
2279 "Invalid accumulated classification during merge.");
2280 if (Accum == Field || Field == NoClass)
2281 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002282 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002283 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002284 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002285 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002286 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002287 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002288 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2289 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002290 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002291 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002292}
2293
Chris Lattner5c740f12010-06-30 19:14:05 +00002294void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002295 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002296 // FIXME: This code can be simplified by introducing a simple value class for
2297 // Class pairs with appropriate constructor methods for the various
2298 // situations.
2299
2300 // FIXME: Some of the split computations are wrong; unaligned vectors
2301 // shouldn't be passed in registers for example, so there is no chance they
2302 // can straddle an eightbyte. Verify & simplify.
2303
2304 Lo = Hi = NoClass;
2305
2306 Class &Current = OffsetBase < 64 ? Lo : Hi;
2307 Current = Memory;
2308
John McCall9dd450b2009-09-21 23:43:11 +00002309 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002310 BuiltinType::Kind k = BT->getKind();
2311
2312 if (k == BuiltinType::Void) {
2313 Current = NoClass;
2314 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2315 Lo = Integer;
2316 Hi = Integer;
2317 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2318 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002319 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002320 Current = SSE;
2321 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002322 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2323 if (LDF == &llvm::APFloat::IEEEquad) {
2324 Lo = SSE;
2325 Hi = SSEUp;
2326 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2327 Lo = X87;
2328 Hi = X87Up;
2329 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2330 Current = SSE;
2331 } else
2332 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002333 }
2334 // FIXME: _Decimal32 and _Decimal64 are SSE.
2335 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002336 return;
2337 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002338
Chris Lattnerd776fb12010-06-28 21:43:59 +00002339 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002340 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002341 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
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->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002346 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002347 return;
2348 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002349
Chris Lattnerd776fb12010-06-28 21:43:59 +00002350 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002351 if (Ty->isMemberFunctionPointerType()) {
2352 if (Has64BitPointers) {
2353 // If Has64BitPointers, this is an {i64, i64}, so classify both
2354 // Lo and Hi now.
2355 Lo = Hi = Integer;
2356 } else {
2357 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2358 // straddles an eightbyte boundary, Hi should be classified as well.
2359 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2360 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2361 if (EB_FuncPtr != EB_ThisAdj) {
2362 Lo = Hi = Integer;
2363 } else {
2364 Current = Integer;
2365 }
2366 }
2367 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002368 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002369 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002370 return;
2371 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002372
Chris Lattnerd776fb12010-06-28 21:43:59 +00002373 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002374 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002375 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2376 // gcc passes the following as integer:
2377 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2378 // 2 bytes - <2 x char>, <1 x short>
2379 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002380 Current = Integer;
2381
2382 // If this type crosses an eightbyte boundary, it should be
2383 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002384 uint64_t EB_Lo = (OffsetBase) / 64;
2385 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2386 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002387 Hi = Lo;
2388 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002389 QualType ElementType = VT->getElementType();
2390
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002391 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002392 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002393 return;
2394
David Majnemere2ae2282016-03-04 05:26:16 +00002395 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2396 // pass them as integer. For platforms where clang is the de facto
2397 // platform compiler, we must continue to use integer.
2398 if (!classifyIntegerMMXAsSSE() &&
2399 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2400 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2401 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2402 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002403 Current = Integer;
2404 else
2405 Current = SSE;
2406
2407 // If this type crosses an eightbyte boundary, it should be
2408 // split.
2409 if (OffsetBase && OffsetBase != 64)
2410 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002411 } else if (Size == 128 ||
2412 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002413 // Arguments of 256-bits are split into four eightbyte chunks. The
2414 // least significant one belongs to class SSE and all the others to class
2415 // SSEUP. The original Lo and Hi design considers that types can't be
2416 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2417 // This design isn't correct for 256-bits, but since there're no cases
2418 // where the upper parts would need to be inspected, avoid adding
2419 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002420 //
2421 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2422 // registers if they are "named", i.e. not part of the "..." of a
2423 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002424 //
2425 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2426 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002427 Lo = SSE;
2428 Hi = SSEUp;
2429 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002430 return;
2431 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002432
Chris Lattnerd776fb12010-06-28 21:43:59 +00002433 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002434 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002435
Chris Lattner2b037972010-07-29 02:01:43 +00002436 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002437 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002438 if (Size <= 64)
2439 Current = Integer;
2440 else if (Size <= 128)
2441 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002442 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002443 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002444 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002445 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002446 } else if (ET == getContext().LongDoubleTy) {
2447 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2448 if (LDF == &llvm::APFloat::IEEEquad)
2449 Current = Memory;
2450 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2451 Current = ComplexX87;
2452 else if (LDF == &llvm::APFloat::IEEEdouble)
2453 Lo = Hi = SSE;
2454 else
2455 llvm_unreachable("unexpected long double representation!");
2456 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002457
2458 // If this complex type crosses an eightbyte boundary then it
2459 // should be split.
2460 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002461 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002462 if (Hi == NoClass && EB_Real != EB_Imag)
2463 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002464
Chris Lattnerd776fb12010-06-28 21:43:59 +00002465 return;
2466 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002467
Chris Lattner2b037972010-07-29 02:01:43 +00002468 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002469 // Arrays are treated like structures.
2470
Chris Lattner2b037972010-07-29 02:01:43 +00002471 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002472
2473 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002474 // than four eightbytes, ..., it has class MEMORY.
2475 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002476 return;
2477
2478 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2479 // fields, it has class MEMORY.
2480 //
2481 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002482 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002483 return;
2484
2485 // Otherwise implement simplified merge. We could be smarter about
2486 // this, but it isn't worth it and would be harder to verify.
2487 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002488 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002489 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002490
2491 // The only case a 256-bit wide vector could be used is when the array
2492 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2493 // to work for sizes wider than 128, early check and fallback to memory.
2494 if (Size > 128 && EltSize != 256)
2495 return;
2496
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002497 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2498 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002499 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002500 Lo = merge(Lo, FieldLo);
2501 Hi = merge(Hi, FieldHi);
2502 if (Lo == Memory || Hi == Memory)
2503 break;
2504 }
2505
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002506 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002507 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002508 return;
2509 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002510
Chris Lattnerd776fb12010-06-28 21:43:59 +00002511 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002512 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002513
2514 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002515 // than four eightbytes, ..., it has class MEMORY.
2516 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002517 return;
2518
Anders Carlsson20759ad2009-09-16 15:53:40 +00002519 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2520 // copy constructor or a non-trivial destructor, it is passed by invisible
2521 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002522 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002523 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002524
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002525 const RecordDecl *RD = RT->getDecl();
2526
2527 // Assume variable sized types are passed in memory.
2528 if (RD->hasFlexibleArrayMember())
2529 return;
2530
Chris Lattner2b037972010-07-29 02:01:43 +00002531 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532
2533 // Reset Lo class, this will be recomputed.
2534 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002535
2536 // If this is a C++ record, classify the bases first.
2537 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002538 for (const auto &I : CXXRD->bases()) {
2539 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002540 "Unexpected base class!");
2541 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002542 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002543
2544 // Classify this field.
2545 //
2546 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2547 // single eightbyte, each is classified separately. Each eightbyte gets
2548 // initialized to class NO_CLASS.
2549 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002550 uint64_t Offset =
2551 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002552 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002553 Lo = merge(Lo, FieldLo);
2554 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002555 if (Lo == Memory || Hi == Memory) {
2556 postMerge(Size, Lo, Hi);
2557 return;
2558 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002559 }
2560 }
2561
2562 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002563 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002564 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002565 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2567 bool BitField = i->isBitField();
2568
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002569 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2570 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002571 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002572 // The only case a 256-bit wide vector could be used is when the struct
2573 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2574 // to work for sizes wider than 128, early check and fallback to memory.
2575 //
2576 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2577 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002578 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002579 return;
2580 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002581 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002582 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002583 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002584 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002585 return;
2586 }
2587
2588 // Classify this field.
2589 //
2590 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2591 // exceeds a single eightbyte, each is classified
2592 // separately. Each eightbyte gets initialized to class
2593 // NO_CLASS.
2594 Class FieldLo, FieldHi;
2595
2596 // Bit-fields require special handling, they do not force the
2597 // structure to be passed in memory even if unaligned, and
2598 // therefore they can straddle an eightbyte.
2599 if (BitField) {
2600 // Ignore padding bit-fields.
2601 if (i->isUnnamedBitfield())
2602 continue;
2603
2604 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002605 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002606
2607 uint64_t EB_Lo = Offset / 64;
2608 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002609
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002610 if (EB_Lo) {
2611 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2612 FieldLo = NoClass;
2613 FieldHi = Integer;
2614 } else {
2615 FieldLo = Integer;
2616 FieldHi = EB_Hi ? Integer : NoClass;
2617 }
2618 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002619 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 Lo = merge(Lo, FieldLo);
2621 Hi = merge(Hi, FieldHi);
2622 if (Lo == Memory || Hi == Memory)
2623 break;
2624 }
2625
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002626 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627 }
2628}
2629
Chris Lattner22a931e2010-06-29 06:01:59 +00002630ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002631 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2632 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002633 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002634 // Treat an enum type as its underlying type.
2635 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2636 Ty = EnumTy->getDecl()->getIntegerType();
2637
2638 return (Ty->isPromotableIntegerType() ?
2639 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2640 }
2641
John McCall7f416cc2015-09-08 08:05:57 +00002642 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002643}
2644
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002645bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2646 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2647 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002648 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002649 if (Size <= 64 || Size > LargestVector)
2650 return true;
2651 }
2652
2653 return false;
2654}
2655
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002656ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2657 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002658 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2659 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002660 //
2661 // This assumption is optimistic, as there could be free registers available
2662 // when we need to pass this argument in memory, and LLVM could try to pass
2663 // the argument in the free register. This does not seem to happen currently,
2664 // but this code would be much safer if we could mark the argument with
2665 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002666 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002667 // Treat an enum type as its underlying type.
2668 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2669 Ty = EnumTy->getDecl()->getIntegerType();
2670
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002671 return (Ty->isPromotableIntegerType() ?
2672 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002673 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674
Mark Lacey3825e832013-10-06 01:33:34 +00002675 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002676 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002677
Chris Lattner44c2b902011-05-22 23:21:23 +00002678 // Compute the byval alignment. We specify the alignment of the byval in all
2679 // cases so that the mid-level optimizer knows the alignment of the byval.
2680 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002681
2682 // Attempt to avoid passing indirect results using byval when possible. This
2683 // is important for good codegen.
2684 //
2685 // We do this by coercing the value into a scalar type which the backend can
2686 // handle naturally (i.e., without using byval).
2687 //
2688 // For simplicity, we currently only do this when we have exhausted all of the
2689 // free integer registers. Doing this when there are free integer registers
2690 // would require more care, as we would have to ensure that the coerced value
2691 // did not claim the unused register. That would require either reording the
2692 // arguments to the function (so that any subsequent inreg values came first),
2693 // or only doing this optimization when there were no following arguments that
2694 // might be inreg.
2695 //
2696 // We currently expect it to be rare (particularly in well written code) for
2697 // arguments to be passed on the stack when there are still free integer
2698 // registers available (this would typically imply large structs being passed
2699 // by value), so this seems like a fair tradeoff for now.
2700 //
2701 // We can revisit this if the backend grows support for 'onstack' parameter
2702 // attributes. See PR12193.
2703 if (freeIntRegs == 0) {
2704 uint64_t Size = getContext().getTypeSize(Ty);
2705
2706 // If this type fits in an eightbyte, coerce it into the matching integral
2707 // type, which will end up on the stack (with alignment 8).
2708 if (Align == 8 && Size <= 64)
2709 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2710 Size));
2711 }
2712
John McCall7f416cc2015-09-08 08:05:57 +00002713 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002714}
2715
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002716/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2717/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002718llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002719 // Wrapper structs/arrays that only contain vectors are passed just like
2720 // vectors; strip them off if present.
2721 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2722 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002723
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002724 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002725 if (isa<llvm::VectorType>(IRType) ||
2726 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002727 return IRType;
2728
2729 // We couldn't find the preferred IR vector type for 'Ty'.
2730 uint64_t Size = getContext().getTypeSize(Ty);
2731 assert((Size == 128 || Size == 256) && "Invalid type found!");
2732
2733 // Return a LLVM IR vector type based on the size of 'Ty'.
2734 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2735 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002736}
2737
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002738/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2739/// is known to either be off the end of the specified type or being in
2740/// alignment padding. The user type specified is known to be at most 128 bits
2741/// in size, and have passed through X86_64ABIInfo::classify with a successful
2742/// classification that put one of the two halves in the INTEGER class.
2743///
2744/// It is conservatively correct to return false.
2745static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2746 unsigned EndBit, ASTContext &Context) {
2747 // If the bytes being queried are off the end of the type, there is no user
2748 // data hiding here. This handles analysis of builtins, vectors and other
2749 // types that don't contain interesting padding.
2750 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2751 if (TySize <= StartBit)
2752 return true;
2753
Chris Lattner98076a22010-07-29 07:43:55 +00002754 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2755 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2756 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2757
2758 // Check each element to see if the element overlaps with the queried range.
2759 for (unsigned i = 0; i != NumElts; ++i) {
2760 // If the element is after the span we care about, then we're done..
2761 unsigned EltOffset = i*EltSize;
2762 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002763
Chris Lattner98076a22010-07-29 07:43:55 +00002764 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2765 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2766 EndBit-EltOffset, Context))
2767 return false;
2768 }
2769 // If it overlaps no elements, then it is safe to process as padding.
2770 return true;
2771 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002772
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002773 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2774 const RecordDecl *RD = RT->getDecl();
2775 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002776
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002777 // If this is a C++ record, check the bases first.
2778 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002779 for (const auto &I : CXXRD->bases()) {
2780 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002781 "Unexpected base class!");
2782 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002783 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002784
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002785 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002786 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002787 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002788
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002789 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002790 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002791 EndBit-BaseOffset, Context))
2792 return false;
2793 }
2794 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002795
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002796 // Verify that no field has data that overlaps the region of interest. Yes
2797 // this could be sped up a lot by being smarter about queried fields,
2798 // however we're only looking at structs up to 16 bytes, so we don't care
2799 // much.
2800 unsigned idx = 0;
2801 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2802 i != e; ++i, ++idx) {
2803 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002804
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002805 // If we found a field after the region we care about, then we're done.
2806 if (FieldOffset >= EndBit) break;
2807
2808 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2809 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2810 Context))
2811 return false;
2812 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002813
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002814 // If nothing in this record overlapped the area of interest, then we're
2815 // clean.
2816 return true;
2817 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002818
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002819 return false;
2820}
2821
Chris Lattnere556a712010-07-29 18:39:32 +00002822/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2823/// float member at the specified offset. For example, {int,{float}} has a
2824/// float at offset 4. It is conservatively correct for this routine to return
2825/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002826static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002827 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002828 // Base case if we find a float.
2829 if (IROffset == 0 && IRType->isFloatTy())
2830 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002831
Chris Lattnere556a712010-07-29 18:39:32 +00002832 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002833 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002834 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2835 unsigned Elt = SL->getElementContainingOffset(IROffset);
2836 IROffset -= SL->getElementOffset(Elt);
2837 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2838 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002839
Chris Lattnere556a712010-07-29 18:39:32 +00002840 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002841 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2842 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002843 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2844 IROffset -= IROffset/EltSize*EltSize;
2845 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2846 }
2847
2848 return false;
2849}
2850
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002851
2852/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2853/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002854llvm::Type *X86_64ABIInfo::
2855GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002856 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002857 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002858 // pass as float if the last 4 bytes is just padding. This happens for
2859 // structs that contain 3 floats.
2860 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2861 SourceOffset*8+64, getContext()))
2862 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002863
Chris Lattnere556a712010-07-29 18:39:32 +00002864 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2865 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2866 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002867 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2868 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002869 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002870
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002871 return llvm::Type::getDoubleTy(getVMContext());
2872}
2873
2874
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002875/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2876/// an 8-byte GPR. This means that we either have a scalar or we are talking
2877/// about the high or low part of an up-to-16-byte struct. This routine picks
2878/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002879/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2880/// etc).
2881///
2882/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2883/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2884/// the 8-byte value references. PrefType may be null.
2885///
Alp Toker9907f082014-07-09 14:06:35 +00002886/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002887/// an offset into this that we're processing (which is always either 0 or 8).
2888///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002889llvm::Type *X86_64ABIInfo::
2890GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002891 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002892 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2893 // returning an 8-byte unit starting with it. See if we can safely use it.
2894 if (IROffset == 0) {
2895 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002896 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2897 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002898 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002899
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002900 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2901 // goodness in the source type is just tail padding. This is allowed to
2902 // kick in for struct {double,int} on the int, but not on
2903 // struct{double,int,int} because we wouldn't return the second int. We
2904 // have to do this analysis on the source type because we can't depend on
2905 // unions being lowered a specific way etc.
2906 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002907 IRType->isIntegerTy(32) ||
2908 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2909 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2910 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002911
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002912 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2913 SourceOffset*8+64, getContext()))
2914 return IRType;
2915 }
2916 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002917
Chris Lattner2192fe52011-07-18 04:24:23 +00002918 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002919 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002920 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002921 if (IROffset < SL->getSizeInBytes()) {
2922 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2923 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002924
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002925 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2926 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002927 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002928 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002929
Chris Lattner2192fe52011-07-18 04:24:23 +00002930 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002931 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002932 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002933 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002934 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2935 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002936 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002937
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002938 // Okay, we don't have any better idea of what to pass, so we pass this in an
2939 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002940 unsigned TySizeInBytes =
2941 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002942
Chris Lattner3f763422010-07-29 17:34:39 +00002943 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002944
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002945 // It is always safe to classify this as an integer type up to i64 that
2946 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002947 return llvm::IntegerType::get(getVMContext(),
2948 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002949}
2950
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002951
2952/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2953/// be used as elements of a two register pair to pass or return, return a
2954/// first class aggregate to represent them. For example, if the low part of
2955/// a by-value argument should be passed as i32* and the high part as float,
2956/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002957static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002958GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002959 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002960 // In order to correctly satisfy the ABI, we need to the high part to start
2961 // at offset 8. If the high and low parts we inferred are both 4-byte types
2962 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2963 // the second element at offset 8. Check for this:
2964 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2965 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002966 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002967 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002968
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002969 // To handle this, we have to increase the size of the low part so that the
2970 // second element will start at an 8 byte offset. We can't increase the size
2971 // of the second element because it might make us access off the end of the
2972 // struct.
2973 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002974 // There are usually two sorts of types the ABI generation code can produce
2975 // for the low part of a pair that aren't 8 bytes in size: float or
2976 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2977 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002978 // Promote these to a larger type.
2979 if (Lo->isFloatTy())
2980 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2981 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002982 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2983 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002984 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2985 }
2986 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002987
Reid Kleckneree7cf842014-12-01 22:02:27 +00002988 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002989
2990
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002991 // Verify that the second element is at an 8-byte offset.
2992 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2993 "Invalid x86-64 argument pair!");
2994 return Result;
2995}
2996
Chris Lattner31faff52010-07-28 23:06:14 +00002997ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002998classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002999 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3000 // classification algorithm.
3001 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003002 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003003
3004 // Check some invariants.
3005 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003006 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3007
Craig Topper8a13c412014-05-21 05:09:00 +00003008 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003009 switch (Lo) {
3010 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003011 if (Hi == NoClass)
3012 return ABIArgInfo::getIgnore();
3013 // If the low part is just padding, it takes no register, leave ResType
3014 // null.
3015 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3016 "Unknown missing lo part");
3017 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003018
3019 case SSEUp:
3020 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003021 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003022
3023 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3024 // hidden argument.
3025 case Memory:
3026 return getIndirectReturnResult(RetTy);
3027
3028 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3029 // available register of the sequence %rax, %rdx is used.
3030 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003031 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003032
Chris Lattner1f3a0632010-07-29 21:42:50 +00003033 // If we have a sign or zero extended integer, make sure to return Extend
3034 // so that the parameter gets the right LLVM IR attributes.
3035 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3036 // Treat an enum type as its underlying type.
3037 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3038 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003039
Chris Lattner1f3a0632010-07-29 21:42:50 +00003040 if (RetTy->isIntegralOrEnumerationType() &&
3041 RetTy->isPromotableIntegerType())
3042 return ABIArgInfo::getExtend();
3043 }
Chris Lattner31faff52010-07-28 23:06:14 +00003044 break;
3045
3046 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3047 // available SSE register of the sequence %xmm0, %xmm1 is used.
3048 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003049 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003050 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003051
3052 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3053 // returned on the X87 stack in %st0 as 80-bit x87 number.
3054 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003055 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003056 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003057
3058 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3059 // part of the value is returned in %st0 and the imaginary part in
3060 // %st1.
3061 case ComplexX87:
3062 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003063 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003064 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003065 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003066 break;
3067 }
3068
Craig Topper8a13c412014-05-21 05:09:00 +00003069 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003070 switch (Hi) {
3071 // Memory was handled previously and X87 should
3072 // never occur as a hi class.
3073 case Memory:
3074 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003075 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003076
3077 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003078 case NoClass:
3079 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003080
Chris Lattner52b3c132010-09-01 00:20:33 +00003081 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003082 HighPart = GetINTEGERTypeAtOffset(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;
Chris Lattner52b3c132010-09-01 00:20:33 +00003086 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003087 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003088 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3089 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003090 break;
3091
3092 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003093 // is passed in the next available eightbyte chunk if the last used
3094 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003095 //
Chris Lattner57540c52011-04-15 05:22:18 +00003096 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003097 case SSEUp:
3098 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003099 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003100 break;
3101
3102 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3103 // returned together with the previous X87 value in %st0.
3104 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003105 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003106 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003107 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003108 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003109 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003110 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003111 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3112 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003113 }
Chris Lattner31faff52010-07-28 23:06:14 +00003114 break;
3115 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003116
Chris Lattner52b3c132010-09-01 00:20:33 +00003117 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003118 // known to pass in the high eightbyte of the result. We do this by forming a
3119 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003120 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003121 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003122
Chris Lattner1f3a0632010-07-29 21:42:50 +00003123 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003124}
3125
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003126ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003127 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3128 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003129 const
3130{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003131 Ty = useFirstFieldIfTransparentUnion(Ty);
3132
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003133 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003134 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003135
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003136 // Check some invariants.
3137 // FIXME: Enforce these by construction.
3138 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003139 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3140
3141 neededInt = 0;
3142 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003143 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003144 switch (Lo) {
3145 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003146 if (Hi == NoClass)
3147 return ABIArgInfo::getIgnore();
3148 // If the low part is just padding, it takes no register, leave ResType
3149 // null.
3150 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3151 "Unknown missing lo part");
3152 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003153
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003154 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3155 // on the stack.
3156 case Memory:
3157
3158 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3159 // COMPLEX_X87, it is passed in memory.
3160 case X87:
3161 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003162 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003163 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003164 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003165
3166 case SSEUp:
3167 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003168 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003169
3170 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3171 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3172 // and %r9 is used.
3173 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003174 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003175
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003176 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003177 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003178
3179 // If we have a sign or zero extended integer, make sure to return Extend
3180 // so that the parameter gets the right LLVM IR attributes.
3181 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3182 // Treat an enum type as its underlying type.
3183 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3184 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003185
Chris Lattner1f3a0632010-07-29 21:42:50 +00003186 if (Ty->isIntegralOrEnumerationType() &&
3187 Ty->isPromotableIntegerType())
3188 return ABIArgInfo::getExtend();
3189 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003190
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003191 break;
3192
3193 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3194 // available SSE register is used, the registers are taken in the
3195 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003196 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003197 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003198 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003199 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003200 break;
3201 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003202 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003203
Craig Topper8a13c412014-05-21 05:09:00 +00003204 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003205 switch (Hi) {
3206 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003207 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208 // which is passed in memory.
3209 case Memory:
3210 case X87:
3211 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003212 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003213
3214 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003215
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003216 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003217 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003218 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003219 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003220
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003221 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3222 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003223 break;
3224
3225 // X87Up generally doesn't occur here (long double is passed in
3226 // memory), except in situations involving unions.
3227 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003228 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003229 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003230
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003231 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3232 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003233
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003234 ++neededSSE;
3235 break;
3236
3237 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3238 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003239 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003240 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003241 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003242 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003243 break;
3244 }
3245
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003246 // If a high part was specified, merge it together with the low part. It is
3247 // known to pass in the high eightbyte of the result. We do this by forming a
3248 // first class struct aggregate with the high and low part: {low, high}
3249 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003250 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003251
Chris Lattner1f3a0632010-07-29 21:42:50 +00003252 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003253}
3254
Chris Lattner22326a12010-07-29 02:31:05 +00003255void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003256
Reid Kleckner40ca9132014-05-13 22:05:45 +00003257 if (!getCXXABI().classifyReturnType(FI))
3258 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003259
3260 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003261 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003262
3263 // If the return value is indirect, then the hidden argument is consuming one
3264 // integer register.
3265 if (FI.getReturnInfo().isIndirect())
3266 --freeIntRegs;
3267
Peter Collingbournef7706832014-12-12 23:41:25 +00003268 // The chain argument effectively gives us another free register.
3269 if (FI.isChainCall())
3270 ++freeIntRegs;
3271
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003272 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003273 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3274 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003275 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003276 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003277 it != ie; ++it, ++ArgNo) {
3278 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003279
Bill Wendling9987c0e2010-10-18 23:51:38 +00003280 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003281 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003282 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003283
3284 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3285 // eightbyte of an argument, the whole argument is passed on the
3286 // stack. If registers have already been assigned for some
3287 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003288 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003289 freeIntRegs -= neededInt;
3290 freeSSERegs -= neededSSE;
3291 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003292 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003293 }
3294 }
3295}
3296
John McCall7f416cc2015-09-08 08:05:57 +00003297static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3298 Address VAListAddr, QualType Ty) {
3299 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3300 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003301 llvm::Value *overflow_arg_area =
3302 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3303
3304 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3305 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003306 // It isn't stated explicitly in the standard, but in practice we use
3307 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003308 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3309 if (Align > CharUnits::fromQuantity(8)) {
3310 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3311 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003312 }
3313
3314 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003315 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003316 llvm::Value *Res =
3317 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003318 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003319
3320 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3321 // l->overflow_arg_area + sizeof(type).
3322 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3323 // an 8 byte boundary.
3324
3325 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003326 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003327 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003328 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3329 "overflow_arg_area.next");
3330 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3331
3332 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003333 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003334}
3335
John McCall7f416cc2015-09-08 08:05:57 +00003336Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3337 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003338 // Assume that va_list type is correct; should be pointer to LLVM type:
3339 // struct {
3340 // i32 gp_offset;
3341 // i32 fp_offset;
3342 // i8* overflow_arg_area;
3343 // i8* reg_save_area;
3344 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003345 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003346
John McCall7f416cc2015-09-08 08:05:57 +00003347 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003348 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003349 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003350
3351 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3352 // in the registers. If not go to step 7.
3353 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003354 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003355
3356 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3357 // general purpose registers needed to pass type and num_fp to hold
3358 // the number of floating point registers needed.
3359
3360 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3361 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3362 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3363 //
3364 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3365 // register save space).
3366
Craig Topper8a13c412014-05-21 05:09:00 +00003367 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003368 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3369 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003370 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003371 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003372 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3373 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003374 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003375 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3376 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003377 }
3378
3379 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003380 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003381 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3382 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003383 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3384 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003385 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3386 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003387 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3388 }
3389
3390 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3391 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3392 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3393 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3394
3395 // Emit code to load the value if it was passed in registers.
3396
3397 CGF.EmitBlock(InRegBlock);
3398
3399 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3400 // an offset of l->gp_offset and/or l->fp_offset. This may require
3401 // copying to a temporary location in case the parameter is passed
3402 // in different register classes or requires an alignment greater
3403 // than 8 for general purpose registers and 16 for XMM registers.
3404 //
3405 // FIXME: This really results in shameful code when we end up needing to
3406 // collect arguments from different places; often what should result in a
3407 // simple assembling of a structure from scattered addresses has many more
3408 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003409 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003410 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3411 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3412 "reg_save_area");
3413
3414 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003415 if (neededInt && neededSSE) {
3416 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003417 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003418 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003419 Address Tmp = CGF.CreateMemTemp(Ty);
3420 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003421 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003422 llvm::Type *TyLo = ST->getElementType(0);
3423 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003424 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003425 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003426 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3427 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003428 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3429 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003430 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3431 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003432
John McCall7f416cc2015-09-08 08:05:57 +00003433 // Copy the first element.
3434 llvm::Value *V =
3435 CGF.Builder.CreateDefaultAlignedLoad(
3436 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3437 CGF.Builder.CreateStore(V,
3438 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3439
3440 // Copy the second element.
3441 V = CGF.Builder.CreateDefaultAlignedLoad(
3442 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3443 CharUnits Offset = CharUnits::fromQuantity(
3444 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3445 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3446
3447 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003448 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003449 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3450 CharUnits::fromQuantity(8));
3451 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003452
3453 // Copy to a temporary if necessary to ensure the appropriate alignment.
3454 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003455 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003456 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003457 CharUnits TyAlign = SizeAlign.second;
3458
3459 // Copy into a temporary if the type is more aligned than the
3460 // register save area.
3461 if (TyAlign.getQuantity() > 8) {
3462 Address Tmp = CGF.CreateMemTemp(Ty);
3463 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003464 RegAddr = Tmp;
3465 }
John McCall7f416cc2015-09-08 08:05:57 +00003466
Chris Lattner0cf24192010-06-28 20:05:43 +00003467 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003468 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3469 CharUnits::fromQuantity(16));
3470 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003471 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003472 assert(neededSSE == 2 && "Invalid number of needed registers!");
3473 // SSE registers are spaced 16 bytes apart in the register save
3474 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003475 // The ABI isn't explicit about this, but it seems reasonable
3476 // to assume that the slots are 16-byte aligned, since the stack is
3477 // naturally 16-byte aligned and the prologue is expected to store
3478 // all the SSE registers to the RSA.
3479 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3480 CharUnits::fromQuantity(16));
3481 Address RegAddrHi =
3482 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3483 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003484 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003485 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003486 llvm::Value *V;
3487 Address Tmp = CGF.CreateMemTemp(Ty);
3488 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3489 V = CGF.Builder.CreateLoad(
3490 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3491 CGF.Builder.CreateStore(V,
3492 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3493 V = CGF.Builder.CreateLoad(
3494 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3495 CGF.Builder.CreateStore(V,
3496 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3497
3498 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003499 }
3500
3501 // AMD64-ABI 3.5.7p5: Step 5. Set:
3502 // l->gp_offset = l->gp_offset + num_gp * 8
3503 // l->fp_offset = l->fp_offset + num_fp * 16.
3504 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003505 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003506 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3507 gp_offset_p);
3508 }
3509 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003510 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003511 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3512 fp_offset_p);
3513 }
3514 CGF.EmitBranch(ContBlock);
3515
3516 // Emit code to load the value if it was passed in memory.
3517
3518 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003519 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003520
3521 // Return the appropriate result.
3522
3523 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003524 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3525 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003526 return ResAddr;
3527}
3528
Charles Davisc7d5c942015-09-17 20:55:33 +00003529Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3530 QualType Ty) const {
3531 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3532 CGF.getContext().getTypeInfoInChars(Ty),
3533 CharUnits::fromQuantity(8),
3534 /*allowHigherAlign*/ false);
3535}
3536
Reid Kleckner80944df2014-10-31 22:00:51 +00003537ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3538 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003539
3540 if (Ty->isVoidType())
3541 return ABIArgInfo::getIgnore();
3542
3543 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3544 Ty = EnumTy->getDecl()->getIntegerType();
3545
Reid Kleckner80944df2014-10-31 22:00:51 +00003546 TypeInfo Info = getContext().getTypeInfo(Ty);
3547 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003548 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003549
Reid Kleckner9005f412014-05-02 00:51:20 +00003550 const RecordType *RT = Ty->getAs<RecordType>();
3551 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003552 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003553 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003554 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003555 }
3556
3557 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003558 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003559
Reid Kleckner9005f412014-05-02 00:51:20 +00003560 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003561
Reid Kleckner80944df2014-10-31 22:00:51 +00003562 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3563 // other targets.
3564 const Type *Base = nullptr;
3565 uint64_t NumElts = 0;
3566 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3567 if (FreeSSERegs >= NumElts) {
3568 FreeSSERegs -= NumElts;
3569 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3570 return ABIArgInfo::getDirect();
3571 return ABIArgInfo::getExpand();
3572 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003573 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003574 }
3575
3576
Reid Klecknerec87fec2014-05-02 01:17:12 +00003577 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003578 // If the member pointer is represented by an LLVM int or ptr, pass it
3579 // directly.
3580 llvm::Type *LLTy = CGT.ConvertType(Ty);
3581 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3582 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003583 }
3584
Michael Kuperstein4f818702015-02-24 09:35:58 +00003585 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003586 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3587 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003588 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003589 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003590
Reid Kleckner9005f412014-05-02 00:51:20 +00003591 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003592 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003593 }
3594
Julien Lerouge10dcff82014-08-27 00:36:55 +00003595 // Bool type is always extended to the ABI, other builtin types are not
3596 // extended.
3597 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3598 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003599 return ABIArgInfo::getExtend();
3600
Reid Kleckner11a17192015-10-28 22:29:52 +00003601 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3602 // passes them indirectly through memory.
3603 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3604 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3605 if (LDF == &llvm::APFloat::x87DoubleExtended)
3606 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3607 }
3608
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003609 return ABIArgInfo::getDirect();
3610}
3611
3612void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003613 bool IsVectorCall =
3614 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003615
Reid Kleckner80944df2014-10-31 22:00:51 +00003616 // We can use up to 4 SSE return registers with vectorcall.
3617 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3618 if (!getCXXABI().classifyReturnType(FI))
3619 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3620
3621 // We can use up to 6 SSE register parameters with vectorcall.
3622 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003623 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003624 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003625}
3626
John McCall7f416cc2015-09-08 08:05:57 +00003627Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3628 QualType Ty) const {
3629 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3630 CGF.getContext().getTypeInfoInChars(Ty),
3631 CharUnits::fromQuantity(8),
3632 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003633}
Chris Lattner0cf24192010-06-28 20:05:43 +00003634
John McCallea8d8bb2010-03-11 00:10:12 +00003635// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003636namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003637/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3638class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003639bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003640public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003641 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3642 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003643
John McCall7f416cc2015-09-08 08:05:57 +00003644 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3645 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003646};
3647
3648class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3649public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003650 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3651 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003652
Craig Topper4f12f102014-03-12 06:41:41 +00003653 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003654 // This is recovered from gcc output.
3655 return 1; // r1 is the dedicated stack pointer
3656 }
3657
3658 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003659 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003660};
3661
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003662}
John McCallea8d8bb2010-03-11 00:10:12 +00003663
James Y Knight29b5f082016-02-24 02:59:33 +00003664// TODO: this implementation is now likely redundant with
3665// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003666Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3667 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003668 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003669 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3670 // TODO: Implement this. For now ignore.
3671 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003672 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003673 }
3674
John McCall7f416cc2015-09-08 08:05:57 +00003675 // struct __va_list_tag {
3676 // unsigned char gpr;
3677 // unsigned char fpr;
3678 // unsigned short reserved;
3679 // void *overflow_arg_area;
3680 // void *reg_save_area;
3681 // };
3682
Roman Divacky8a12d842014-11-03 18:32:54 +00003683 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003684 bool isInt =
3685 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003686 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003687
3688 // All aggregates are passed indirectly? That doesn't seem consistent
3689 // with the argument-lowering code.
3690 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003691
3692 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003693
3694 // The calling convention either uses 1-2 GPRs or 1 FPR.
3695 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003696 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003697 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3698 } else {
3699 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003700 }
John McCall7f416cc2015-09-08 08:05:57 +00003701
3702 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3703
3704 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003705 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003706 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3707 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3708 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003709
Eric Christopher7565e0d2015-05-29 23:09:49 +00003710 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003711 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003712
3713 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3714 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3715 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3716
3717 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3718
John McCall7f416cc2015-09-08 08:05:57 +00003719 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3720 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003721
John McCall7f416cc2015-09-08 08:05:57 +00003722 // Case 1: consume registers.
3723 Address RegAddr = Address::invalid();
3724 {
3725 CGF.EmitBlock(UsingRegs);
3726
3727 Address RegSaveAreaPtr =
3728 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3729 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3730 CharUnits::fromQuantity(8));
3731 assert(RegAddr.getElementType() == CGF.Int8Ty);
3732
3733 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003734 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003735 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3736 CharUnits::fromQuantity(32));
3737 }
3738
3739 // Get the address of the saved value by scaling the number of
3740 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003741 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003742 llvm::Value *RegOffset =
3743 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3744 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3745 RegAddr.getPointer(), RegOffset),
3746 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3747 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3748
3749 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003750 NumRegs =
3751 Builder.CreateAdd(NumRegs,
3752 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003753 Builder.CreateStore(NumRegs, NumRegsAddr);
3754
3755 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003756 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003757
John McCall7f416cc2015-09-08 08:05:57 +00003758 // Case 2: consume space in the overflow area.
3759 Address MemAddr = Address::invalid();
3760 {
3761 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003762
Roman Divacky039b9702016-02-20 08:31:24 +00003763 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3764
John McCall7f416cc2015-09-08 08:05:57 +00003765 // Everything in the overflow area is rounded up to a size of at least 4.
3766 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3767
3768 CharUnits Size;
3769 if (!isIndirect) {
3770 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003771 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003772 } else {
3773 Size = CGF.getPointerSize();
3774 }
3775
3776 Address OverflowAreaAddr =
3777 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003778 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003779 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003780 // Round up address of argument to alignment
3781 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3782 if (Align > OverflowAreaAlign) {
3783 llvm::Value *Ptr = OverflowArea.getPointer();
3784 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3785 Align);
3786 }
3787
John McCall7f416cc2015-09-08 08:05:57 +00003788 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3789
3790 // Increase the overflow area.
3791 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3792 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3793 CGF.EmitBranch(Cont);
3794 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003795
3796 CGF.EmitBlock(Cont);
3797
John McCall7f416cc2015-09-08 08:05:57 +00003798 // Merge the cases with a phi.
3799 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3800 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003801
John McCall7f416cc2015-09-08 08:05:57 +00003802 // Load the pointer if the argument was passed indirectly.
3803 if (isIndirect) {
3804 Result = Address(Builder.CreateLoad(Result, "aggr"),
3805 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003806 }
3807
3808 return Result;
3809}
3810
John McCallea8d8bb2010-03-11 00:10:12 +00003811bool
3812PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3813 llvm::Value *Address) const {
3814 // This is calculated from the LLVM and GCC tables and verified
3815 // against gcc output. AFAIK all ABIs use the same encoding.
3816
3817 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003818
Chris Lattnerece04092012-02-07 00:39:47 +00003819 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003820 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3821 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3822 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3823
3824 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003825 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003826
3827 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003828 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003829
3830 // 64-76 are various 4-byte special-purpose registers:
3831 // 64: mq
3832 // 65: lr
3833 // 66: ctr
3834 // 67: ap
3835 // 68-75 cr0-7
3836 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003837 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003838
3839 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003840 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003841
3842 // 109: vrsave
3843 // 110: vscr
3844 // 111: spe_acc
3845 // 112: spefscr
3846 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003847 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003848
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003849 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003850}
3851
Roman Divackyd966e722012-05-09 18:22:46 +00003852// PowerPC-64
3853
3854namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003855/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00003856class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003857public:
3858 enum ABIKind {
3859 ELFv1 = 0,
3860 ELFv2
3861 };
3862
3863private:
3864 static const unsigned GPRBits = 64;
3865 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003866 bool HasQPX;
3867
3868 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3869 // will be passed in a QPX register.
3870 bool IsQPXVectorTy(const Type *Ty) const {
3871 if (!HasQPX)
3872 return false;
3873
3874 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3875 unsigned NumElements = VT->getNumElements();
3876 if (NumElements == 1)
3877 return false;
3878
3879 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3880 if (getContext().getTypeSize(Ty) <= 256)
3881 return true;
3882 } else if (VT->getElementType()->
3883 isSpecificBuiltinType(BuiltinType::Float)) {
3884 if (getContext().getTypeSize(Ty) <= 128)
3885 return true;
3886 }
3887 }
3888
3889 return false;
3890 }
3891
3892 bool IsQPXVectorTy(QualType Ty) const {
3893 return IsQPXVectorTy(Ty.getTypePtr());
3894 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003895
3896public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003897 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
James Y Knight29b5f082016-02-24 02:59:33 +00003898 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003899
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003900 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003901 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003902
3903 ABIArgInfo classifyReturnType(QualType RetTy) const;
3904 ABIArgInfo classifyArgumentType(QualType Ty) const;
3905
Reid Klecknere9f6a712014-10-31 17:10:41 +00003906 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3907 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3908 uint64_t Members) const override;
3909
Bill Schmidt84d37792012-10-12 19:26:17 +00003910 // TODO: We can add more logic to computeInfo to improve performance.
3911 // Example: For aggregate arguments that fit in a register, we could
3912 // use getDirectInReg (as is done below for structs containing a single
3913 // floating-point value) to avoid pushing them to memory on function
3914 // entry. This would require changing the logic in PPCISelLowering
3915 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003916 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003917 if (!getCXXABI().classifyReturnType(FI))
3918 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003919 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003920 // We rely on the default argument classification for the most part.
3921 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003922 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003923 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003924 if (T) {
3925 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003926 if (IsQPXVectorTy(T) ||
3927 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003928 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003929 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003930 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003931 continue;
3932 }
3933 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003934 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003935 }
3936 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003937
John McCall7f416cc2015-09-08 08:05:57 +00003938 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3939 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003940};
3941
3942class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003943
Bill Schmidt25cb3492012-10-03 19:18:57 +00003944public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003945 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003946 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003947 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003948
Craig Topper4f12f102014-03-12 06:41:41 +00003949 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003950 // This is recovered from gcc output.
3951 return 1; // r1 is the dedicated stack pointer
3952 }
3953
3954 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003955 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003956};
3957
Roman Divackyd966e722012-05-09 18:22:46 +00003958class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3959public:
3960 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3961
Craig Topper4f12f102014-03-12 06:41:41 +00003962 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003963 // This is recovered from gcc output.
3964 return 1; // r1 is the dedicated stack pointer
3965 }
3966
3967 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003968 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003969};
3970
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003971}
Roman Divackyd966e722012-05-09 18:22:46 +00003972
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003973// Return true if the ABI requires Ty to be passed sign- or zero-
3974// extended to 64 bits.
3975bool
3976PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3977 // Treat an enum type as its underlying type.
3978 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3979 Ty = EnumTy->getDecl()->getIntegerType();
3980
3981 // Promotable integer types are required to be promoted by the ABI.
3982 if (Ty->isPromotableIntegerType())
3983 return true;
3984
3985 // In addition to the usual promotable integer types, we also need to
3986 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3987 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3988 switch (BT->getKind()) {
3989 case BuiltinType::Int:
3990 case BuiltinType::UInt:
3991 return true;
3992 default:
3993 break;
3994 }
3995
3996 return false;
3997}
3998
John McCall7f416cc2015-09-08 08:05:57 +00003999/// isAlignedParamType - Determine whether a type requires 16-byte or
4000/// higher alignment in the parameter area. Always returns at least 8.
4001CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004002 // Complex types are passed just like their elements.
4003 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4004 Ty = CTy->getElementType();
4005
4006 // Only vector types of size 16 bytes need alignment (larger types are
4007 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004008 if (IsQPXVectorTy(Ty)) {
4009 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004010 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004011
John McCall7f416cc2015-09-08 08:05:57 +00004012 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004013 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004014 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004015 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004016
4017 // For single-element float/vector structs, we consider the whole type
4018 // to have the same alignment requirements as its single element.
4019 const Type *AlignAsType = nullptr;
4020 const Type *EltType = isSingleElementStruct(Ty, getContext());
4021 if (EltType) {
4022 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004023 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004024 getContext().getTypeSize(EltType) == 128) ||
4025 (BT && BT->isFloatingPoint()))
4026 AlignAsType = EltType;
4027 }
4028
Ulrich Weigandb7122372014-07-21 00:48:09 +00004029 // Likewise for ELFv2 homogeneous aggregates.
4030 const Type *Base = nullptr;
4031 uint64_t Members = 0;
4032 if (!AlignAsType && Kind == ELFv2 &&
4033 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4034 AlignAsType = Base;
4035
Ulrich Weigand581badc2014-07-10 17:20:07 +00004036 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004037 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4038 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004039 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004040
John McCall7f416cc2015-09-08 08:05:57 +00004041 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004042 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004043 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004044 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004045
4046 // Otherwise, we only need alignment for any aggregate type that
4047 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004048 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4049 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004050 return CharUnits::fromQuantity(32);
4051 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004052 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004053
John McCall7f416cc2015-09-08 08:05:57 +00004054 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004055}
4056
Ulrich Weigandb7122372014-07-21 00:48:09 +00004057/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4058/// aggregate. Base is set to the base element type, and Members is set
4059/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004060bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4061 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004062 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4063 uint64_t NElements = AT->getSize().getZExtValue();
4064 if (NElements == 0)
4065 return false;
4066 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4067 return false;
4068 Members *= NElements;
4069 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4070 const RecordDecl *RD = RT->getDecl();
4071 if (RD->hasFlexibleArrayMember())
4072 return false;
4073
4074 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004075
4076 // If this is a C++ record, check the bases first.
4077 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4078 for (const auto &I : CXXRD->bases()) {
4079 // Ignore empty records.
4080 if (isEmptyRecord(getContext(), I.getType(), true))
4081 continue;
4082
4083 uint64_t FldMembers;
4084 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4085 return false;
4086
4087 Members += FldMembers;
4088 }
4089 }
4090
Ulrich Weigandb7122372014-07-21 00:48:09 +00004091 for (const auto *FD : RD->fields()) {
4092 // Ignore (non-zero arrays of) empty records.
4093 QualType FT = FD->getType();
4094 while (const ConstantArrayType *AT =
4095 getContext().getAsConstantArrayType(FT)) {
4096 if (AT->getSize().getZExtValue() == 0)
4097 return false;
4098 FT = AT->getElementType();
4099 }
4100 if (isEmptyRecord(getContext(), FT, true))
4101 continue;
4102
4103 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4104 if (getContext().getLangOpts().CPlusPlus &&
4105 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4106 continue;
4107
4108 uint64_t FldMembers;
4109 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4110 return false;
4111
4112 Members = (RD->isUnion() ?
4113 std::max(Members, FldMembers) : Members + FldMembers);
4114 }
4115
4116 if (!Base)
4117 return false;
4118
4119 // Ensure there is no padding.
4120 if (getContext().getTypeSize(Base) * Members !=
4121 getContext().getTypeSize(Ty))
4122 return false;
4123 } else {
4124 Members = 1;
4125 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4126 Members = 2;
4127 Ty = CT->getElementType();
4128 }
4129
Reid Klecknere9f6a712014-10-31 17:10:41 +00004130 // Most ABIs only support float, double, and some vector type widths.
4131 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004132 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004133
4134 // The base type must be the same for all members. Types that
4135 // agree in both total size and mode (float vs. vector) are
4136 // treated as being equivalent here.
4137 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004138 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004139 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004140 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4141 // so make sure to widen it explicitly.
4142 if (const VectorType *VT = Base->getAs<VectorType>()) {
4143 QualType EltTy = VT->getElementType();
4144 unsigned NumElements =
4145 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4146 Base = getContext()
4147 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4148 .getTypePtr();
4149 }
4150 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004151
4152 if (Base->isVectorType() != TyPtr->isVectorType() ||
4153 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4154 return false;
4155 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004156 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4157}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004158
Reid Klecknere9f6a712014-10-31 17:10:41 +00004159bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4160 // Homogeneous aggregates for ELFv2 must have base types of float,
4161 // double, long double, or 128-bit vectors.
4162 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4163 if (BT->getKind() == BuiltinType::Float ||
4164 BT->getKind() == BuiltinType::Double ||
4165 BT->getKind() == BuiltinType::LongDouble)
4166 return true;
4167 }
4168 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004169 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004170 return true;
4171 }
4172 return false;
4173}
4174
4175bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4176 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004177 // Vector types require one register, floating point types require one
4178 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004179 uint32_t NumRegs =
4180 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004181
4182 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004183 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004184}
4185
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004186ABIArgInfo
4187PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004188 Ty = useFirstFieldIfTransparentUnion(Ty);
4189
Bill Schmidt90b22c92012-11-27 02:46:43 +00004190 if (Ty->isAnyComplexType())
4191 return ABIArgInfo::getDirect();
4192
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004193 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4194 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004195 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004196 uint64_t Size = getContext().getTypeSize(Ty);
4197 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004198 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004199 else if (Size < 128) {
4200 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4201 return ABIArgInfo::getDirect(CoerceTy);
4202 }
4203 }
4204
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004205 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004206 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004207 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004208
John McCall7f416cc2015-09-08 08:05:57 +00004209 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4210 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004211
4212 // ELFv2 homogeneous aggregates are passed as array types.
4213 const Type *Base = nullptr;
4214 uint64_t Members = 0;
4215 if (Kind == ELFv2 &&
4216 isHomogeneousAggregate(Ty, Base, Members)) {
4217 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4218 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4219 return ABIArgInfo::getDirect(CoerceTy);
4220 }
4221
Ulrich Weigand601957f2014-07-21 00:56:36 +00004222 // If an aggregate may end up fully in registers, we do not
4223 // use the ByVal method, but pass the aggregate as array.
4224 // This is usually beneficial since we avoid forcing the
4225 // back-end to store the argument to memory.
4226 uint64_t Bits = getContext().getTypeSize(Ty);
4227 if (Bits > 0 && Bits <= 8 * GPRBits) {
4228 llvm::Type *CoerceTy;
4229
4230 // Types up to 8 bytes are passed as integer type (which will be
4231 // properly aligned in the argument save area doubleword).
4232 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004233 CoerceTy =
4234 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004235 // Larger types are passed as arrays, with the base type selected
4236 // according to the required alignment in the save area.
4237 else {
4238 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004239 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004240 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4241 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4242 }
4243
4244 return ABIArgInfo::getDirect(CoerceTy);
4245 }
4246
Ulrich Weigandb7122372014-07-21 00:48:09 +00004247 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004248 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4249 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004250 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004251 }
4252
4253 return (isPromotableTypeForABI(Ty) ?
4254 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4255}
4256
4257ABIArgInfo
4258PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4259 if (RetTy->isVoidType())
4260 return ABIArgInfo::getIgnore();
4261
Bill Schmidta3d121c2012-12-17 04:20:17 +00004262 if (RetTy->isAnyComplexType())
4263 return ABIArgInfo::getDirect();
4264
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004265 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4266 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004267 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004268 uint64_t Size = getContext().getTypeSize(RetTy);
4269 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004270 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004271 else if (Size < 128) {
4272 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4273 return ABIArgInfo::getDirect(CoerceTy);
4274 }
4275 }
4276
Ulrich Weigandb7122372014-07-21 00:48:09 +00004277 if (isAggregateTypeForABI(RetTy)) {
4278 // ELFv2 homogeneous aggregates are returned as array types.
4279 const Type *Base = nullptr;
4280 uint64_t Members = 0;
4281 if (Kind == ELFv2 &&
4282 isHomogeneousAggregate(RetTy, Base, Members)) {
4283 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4284 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4285 return ABIArgInfo::getDirect(CoerceTy);
4286 }
4287
4288 // ELFv2 small aggregates are returned in up to two registers.
4289 uint64_t Bits = getContext().getTypeSize(RetTy);
4290 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4291 if (Bits == 0)
4292 return ABIArgInfo::getIgnore();
4293
4294 llvm::Type *CoerceTy;
4295 if (Bits > GPRBits) {
4296 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004297 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004298 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004299 CoerceTy =
4300 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004301 return ABIArgInfo::getDirect(CoerceTy);
4302 }
4303
4304 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004305 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004306 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004307
4308 return (isPromotableTypeForABI(RetTy) ?
4309 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4310}
4311
Bill Schmidt25cb3492012-10-03 19:18:57 +00004312// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004313Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4314 QualType Ty) const {
4315 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4316 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004317
John McCall7f416cc2015-09-08 08:05:57 +00004318 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004319
Bill Schmidt924c4782013-01-14 17:45:36 +00004320 // If we have a complex type and the base type is smaller than 8 bytes,
4321 // the ABI calls for the real and imaginary parts to be right-adjusted
4322 // in separate doublewords. However, Clang expects us to produce a
4323 // pointer to a structure with the two parts packed tightly. So generate
4324 // loads of the real and imaginary parts relative to the va_list pointer,
4325 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004326 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4327 CharUnits EltSize = TypeInfo.first / 2;
4328 if (EltSize < SlotSize) {
4329 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4330 SlotSize * 2, SlotSize,
4331 SlotSize, /*AllowHigher*/ true);
4332
4333 Address RealAddr = Addr;
4334 Address ImagAddr = RealAddr;
4335 if (CGF.CGM.getDataLayout().isBigEndian()) {
4336 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4337 SlotSize - EltSize);
4338 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4339 2 * SlotSize - EltSize);
4340 } else {
4341 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4342 }
4343
4344 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4345 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4346 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4347 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4348 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4349
4350 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4351 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4352 /*init*/ true);
4353 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004354 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004355 }
4356
John McCall7f416cc2015-09-08 08:05:57 +00004357 // Otherwise, just use the general rule.
4358 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4359 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004360}
4361
4362static bool
4363PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4364 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004365 // This is calculated from the LLVM and GCC tables and verified
4366 // against gcc output. AFAIK all ABIs use the same encoding.
4367
4368 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4369
4370 llvm::IntegerType *i8 = CGF.Int8Ty;
4371 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4372 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4373 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4374
4375 // 0-31: r0-31, the 8-byte general-purpose registers
4376 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4377
4378 // 32-63: fp0-31, the 8-byte floating-point registers
4379 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4380
4381 // 64-76 are various 4-byte special-purpose registers:
4382 // 64: mq
4383 // 65: lr
4384 // 66: ctr
4385 // 67: ap
4386 // 68-75 cr0-7
4387 // 76: xer
4388 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4389
4390 // 77-108: v0-31, the 16-byte vector registers
4391 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4392
4393 // 109: vrsave
4394 // 110: vscr
4395 // 111: spe_acc
4396 // 112: spefscr
4397 // 113: sfp
4398 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4399
4400 return false;
4401}
John McCallea8d8bb2010-03-11 00:10:12 +00004402
Bill Schmidt25cb3492012-10-03 19:18:57 +00004403bool
4404PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4405 CodeGen::CodeGenFunction &CGF,
4406 llvm::Value *Address) const {
4407
4408 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4409}
4410
4411bool
4412PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4413 llvm::Value *Address) const {
4414
4415 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4416}
4417
Chris Lattner0cf24192010-06-28 20:05:43 +00004418//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004419// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004420//===----------------------------------------------------------------------===//
4421
4422namespace {
4423
John McCall12f23522016-04-04 18:33:08 +00004424class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004425public:
4426 enum ABIKind {
4427 AAPCS = 0,
4428 DarwinPCS
4429 };
4430
4431private:
4432 ABIKind Kind;
4433
4434public:
John McCall12f23522016-04-04 18:33:08 +00004435 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4436 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004437
4438private:
4439 ABIKind getABIKind() const { return Kind; }
4440 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4441
4442 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004443 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004444 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4445 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4446 uint64_t Members) const override;
4447
Tim Northovera2ee4332014-03-29 15:09:45 +00004448 bool isIllegalVectorType(QualType Ty) const;
4449
David Blaikie1cbb9712014-11-14 19:09:44 +00004450 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004451 if (!getCXXABI().classifyReturnType(FI))
4452 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004453
Tim Northoverb047bfa2014-11-27 21:02:49 +00004454 for (auto &it : FI.arguments())
4455 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004456 }
4457
John McCall7f416cc2015-09-08 08:05:57 +00004458 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4459 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004460
John McCall7f416cc2015-09-08 08:05:57 +00004461 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4462 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004463
John McCall7f416cc2015-09-08 08:05:57 +00004464 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4465 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004466 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4467 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4468 }
John McCall12f23522016-04-04 18:33:08 +00004469
4470 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4471 ArrayRef<llvm::Type*> scalars,
4472 bool asReturnValue) const override {
4473 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4474 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004475};
4476
Tim Northover573cbee2014-05-24 12:52:07 +00004477class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004478public:
Tim Northover573cbee2014-05-24 12:52:07 +00004479 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4480 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004481
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004482 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004483 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4484 }
4485
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004486 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4487 return 31;
4488 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004489
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004490 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004491};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004492}
Tim Northovera2ee4332014-03-29 15:09:45 +00004493
Tim Northoverb047bfa2014-11-27 21:02:49 +00004494ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004495 Ty = useFirstFieldIfTransparentUnion(Ty);
4496
Tim Northovera2ee4332014-03-29 15:09:45 +00004497 // Handle illegal vector types here.
4498 if (isIllegalVectorType(Ty)) {
4499 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004500 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004501 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004502 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4503 return ABIArgInfo::getDirect(ResType);
4504 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004505 if (Size <= 32) {
4506 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004507 return ABIArgInfo::getDirect(ResType);
4508 }
4509 if (Size == 64) {
4510 llvm::Type *ResType =
4511 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004512 return ABIArgInfo::getDirect(ResType);
4513 }
4514 if (Size == 128) {
4515 llvm::Type *ResType =
4516 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004517 return ABIArgInfo::getDirect(ResType);
4518 }
John McCall7f416cc2015-09-08 08:05:57 +00004519 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004520 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004521
4522 if (!isAggregateTypeForABI(Ty)) {
4523 // Treat an enum type as its underlying type.
4524 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4525 Ty = EnumTy->getDecl()->getIntegerType();
4526
Tim Northovera2ee4332014-03-29 15:09:45 +00004527 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4528 ? ABIArgInfo::getExtend()
4529 : ABIArgInfo::getDirect());
4530 }
4531
4532 // Structures with either a non-trivial destructor or a non-trivial
4533 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004534 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004535 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4536 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004537 }
4538
4539 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4540 // elsewhere for GNU compatibility.
4541 if (isEmptyRecord(getContext(), Ty, true)) {
4542 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4543 return ABIArgInfo::getIgnore();
4544
Tim Northovera2ee4332014-03-29 15:09:45 +00004545 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4546 }
4547
4548 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004549 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004550 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004551 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004552 return ABIArgInfo::getDirect(
4553 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004554 }
4555
4556 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4557 uint64_t Size = getContext().getTypeSize(Ty);
4558 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004559 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004560 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004561
Tim Northovera2ee4332014-03-29 15:09:45 +00004562 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4563 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004564 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004565 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4566 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4567 }
4568 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4569 }
4570
John McCall7f416cc2015-09-08 08:05:57 +00004571 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004572}
4573
Tim Northover573cbee2014-05-24 12:52:07 +00004574ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004575 if (RetTy->isVoidType())
4576 return ABIArgInfo::getIgnore();
4577
4578 // Large vector types should be returned via memory.
4579 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004580 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004581
4582 if (!isAggregateTypeForABI(RetTy)) {
4583 // Treat an enum type as its underlying type.
4584 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4585 RetTy = EnumTy->getDecl()->getIntegerType();
4586
Tim Northover4dab6982014-04-18 13:46:08 +00004587 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4588 ? ABIArgInfo::getExtend()
4589 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004590 }
4591
Tim Northovera2ee4332014-03-29 15:09:45 +00004592 if (isEmptyRecord(getContext(), RetTy, true))
4593 return ABIArgInfo::getIgnore();
4594
Craig Topper8a13c412014-05-21 05:09:00 +00004595 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004596 uint64_t Members = 0;
4597 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004598 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4599 return ABIArgInfo::getDirect();
4600
4601 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4602 uint64_t Size = getContext().getTypeSize(RetTy);
4603 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004604 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004605 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004606
4607 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4608 // For aggregates with 16-byte alignment, we use i128.
4609 if (Alignment < 128 && Size == 128) {
4610 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4611 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4612 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004613 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4614 }
4615
John McCall7f416cc2015-09-08 08:05:57 +00004616 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004617}
4618
Tim Northover573cbee2014-05-24 12:52:07 +00004619/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4620bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004621 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4622 // Check whether VT is legal.
4623 unsigned NumElements = VT->getNumElements();
4624 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004625 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004626 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004627 return true;
4628 return Size != 64 && (Size != 128 || NumElements == 1);
4629 }
4630 return false;
4631}
4632
Reid Klecknere9f6a712014-10-31 17:10:41 +00004633bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4634 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4635 // point type or a short-vector type. This is the same as the 32-bit ABI,
4636 // but with the difference that any floating-point type is allowed,
4637 // including __fp16.
4638 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4639 if (BT->isFloatingPoint())
4640 return true;
4641 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4642 unsigned VecSize = getContext().getTypeSize(VT);
4643 if (VecSize == 64 || VecSize == 128)
4644 return true;
4645 }
4646 return false;
4647}
4648
4649bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4650 uint64_t Members) const {
4651 return Members <= 4;
4652}
4653
John McCall7f416cc2015-09-08 08:05:57 +00004654Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004655 QualType Ty,
4656 CodeGenFunction &CGF) const {
4657 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004658 bool IsIndirect = AI.isIndirect();
4659
Tim Northoverb047bfa2014-11-27 21:02:49 +00004660 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4661 if (IsIndirect)
4662 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4663 else if (AI.getCoerceToType())
4664 BaseTy = AI.getCoerceToType();
4665
4666 unsigned NumRegs = 1;
4667 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4668 BaseTy = ArrTy->getElementType();
4669 NumRegs = ArrTy->getNumElements();
4670 }
4671 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4672
Tim Northovera2ee4332014-03-29 15:09:45 +00004673 // The AArch64 va_list type and handling is specified in the Procedure Call
4674 // Standard, section B.4:
4675 //
4676 // struct {
4677 // void *__stack;
4678 // void *__gr_top;
4679 // void *__vr_top;
4680 // int __gr_offs;
4681 // int __vr_offs;
4682 // };
4683
4684 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4685 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4686 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4687 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004688
John McCall7f416cc2015-09-08 08:05:57 +00004689 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4690 CharUnits TyAlign = TyInfo.second;
4691
4692 Address reg_offs_p = Address::invalid();
4693 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004694 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004695 CharUnits reg_top_offset;
4696 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004697 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004699 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004700 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4701 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004702 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4703 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004704 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004705 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004706 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004707 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004708 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004709 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4710 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004711 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4712 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004713 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004714 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004715 }
4716
4717 //=======================================
4718 // Find out where argument was passed
4719 //=======================================
4720
4721 // If reg_offs >= 0 we're already using the stack for this type of
4722 // argument. We don't want to keep updating reg_offs (in case it overflows,
4723 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4724 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004725 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004726 UsingStack = CGF.Builder.CreateICmpSGE(
4727 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4728
4729 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4730
4731 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004732 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004733 CGF.EmitBlock(MaybeRegBlock);
4734
4735 // Integer arguments may need to correct register alignment (for example a
4736 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4737 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004738 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4739 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004740
4741 reg_offs = CGF.Builder.CreateAdd(
4742 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4743 "align_regoffs");
4744 reg_offs = CGF.Builder.CreateAnd(
4745 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4746 "aligned_regoffs");
4747 }
4748
4749 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004750 // The fact that this is done unconditionally reflects the fact that
4751 // allocating an argument to the stack also uses up all the remaining
4752 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004753 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004754 NewOffset = CGF.Builder.CreateAdd(
4755 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4756 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4757
4758 // Now we're in a position to decide whether this argument really was in
4759 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004760 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004761 InRegs = CGF.Builder.CreateICmpSLE(
4762 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4763
4764 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4765
4766 //=======================================
4767 // Argument was in registers
4768 //=======================================
4769
4770 // Now we emit the code for if the argument was originally passed in
4771 // registers. First start the appropriate block:
4772 CGF.EmitBlock(InRegBlock);
4773
John McCall7f416cc2015-09-08 08:05:57 +00004774 llvm::Value *reg_top = nullptr;
4775 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4776 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004777 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004778 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4779 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4780 Address RegAddr = Address::invalid();
4781 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004782
4783 if (IsIndirect) {
4784 // If it's been passed indirectly (actually a struct), whatever we find from
4785 // stored registers or on the stack will actually be a struct **.
4786 MemTy = llvm::PointerType::getUnqual(MemTy);
4787 }
4788
Craig Topper8a13c412014-05-21 05:09:00 +00004789 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004790 uint64_t NumMembers = 0;
4791 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004792 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004793 // Homogeneous aggregates passed in registers will have their elements split
4794 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4795 // qN+1, ...). We reload and store into a temporary local variable
4796 // contiguously.
4797 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004798 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004799 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4800 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004801 Address Tmp = CGF.CreateTempAlloca(HFATy,
4802 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004803
John McCall7f416cc2015-09-08 08:05:57 +00004804 // On big-endian platforms, the value will be right-aligned in its slot.
4805 int Offset = 0;
4806 if (CGF.CGM.getDataLayout().isBigEndian() &&
4807 BaseTyInfo.first.getQuantity() < 16)
4808 Offset = 16 - BaseTyInfo.first.getQuantity();
4809
Tim Northovera2ee4332014-03-29 15:09:45 +00004810 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004811 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4812 Address LoadAddr =
4813 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4814 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4815
4816 Address StoreAddr =
4817 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004818
4819 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4820 CGF.Builder.CreateStore(Elem, StoreAddr);
4821 }
4822
John McCall7f416cc2015-09-08 08:05:57 +00004823 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004824 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004825 // Otherwise the object is contiguous in memory.
4826
4827 // It might be right-aligned in its slot.
4828 CharUnits SlotSize = BaseAddr.getAlignment();
4829 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004830 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004831 TyInfo.first < SlotSize) {
4832 CharUnits Offset = SlotSize - TyInfo.first;
4833 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004834 }
4835
John McCall7f416cc2015-09-08 08:05:57 +00004836 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004837 }
4838
4839 CGF.EmitBranch(ContBlock);
4840
4841 //=======================================
4842 // Argument was on the stack
4843 //=======================================
4844 CGF.EmitBlock(OnStackBlock);
4845
John McCall7f416cc2015-09-08 08:05:57 +00004846 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4847 CharUnits::Zero(), "stack_p");
4848 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004849
John McCall7f416cc2015-09-08 08:05:57 +00004850 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004851 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004852 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4853 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004854
John McCall7f416cc2015-09-08 08:05:57 +00004855 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004856
John McCall7f416cc2015-09-08 08:05:57 +00004857 OnStackPtr = CGF.Builder.CreateAdd(
4858 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004859 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004860 OnStackPtr = CGF.Builder.CreateAnd(
4861 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004862 "align_stack");
4863
John McCall7f416cc2015-09-08 08:05:57 +00004864 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004865 }
John McCall7f416cc2015-09-08 08:05:57 +00004866 Address OnStackAddr(OnStackPtr,
4867 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004868
John McCall7f416cc2015-09-08 08:05:57 +00004869 // All stack slots are multiples of 8 bytes.
4870 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4871 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004872 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004873 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004874 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004875 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004876
John McCall7f416cc2015-09-08 08:05:57 +00004877 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004878 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004879 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004880
4881 // Write the new value of __stack for the next call to va_arg
4882 CGF.Builder.CreateStore(NewStack, stack_p);
4883
4884 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004885 TyInfo.first < StackSlotSize) {
4886 CharUnits Offset = StackSlotSize - TyInfo.first;
4887 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004888 }
4889
John McCall7f416cc2015-09-08 08:05:57 +00004890 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004891
4892 CGF.EmitBranch(ContBlock);
4893
4894 //=======================================
4895 // Tidy up
4896 //=======================================
4897 CGF.EmitBlock(ContBlock);
4898
John McCall7f416cc2015-09-08 08:05:57 +00004899 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4900 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004901
4902 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004903 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4904 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004905
4906 return ResAddr;
4907}
4908
John McCall7f416cc2015-09-08 08:05:57 +00004909Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4910 CodeGenFunction &CGF) const {
4911 // The backend's lowering doesn't support va_arg for aggregates or
4912 // illegal vector types. Lower VAArg here for these cases and use
4913 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004914 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00004915 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004916
John McCall7f416cc2015-09-08 08:05:57 +00004917 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004918
John McCall7f416cc2015-09-08 08:05:57 +00004919 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004920 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004921 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4922 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4923 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004924 }
4925
John McCall7f416cc2015-09-08 08:05:57 +00004926 // The size of the actual thing passed, which might end up just
4927 // being a pointer for indirect types.
4928 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4929
4930 // Arguments bigger than 16 bytes which aren't homogeneous
4931 // aggregates should be passed indirectly.
4932 bool IsIndirect = false;
4933 if (TyInfo.first.getQuantity() > 16) {
4934 const Type *Base = nullptr;
4935 uint64_t Members = 0;
4936 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004937 }
4938
John McCall7f416cc2015-09-08 08:05:57 +00004939 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4940 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004941}
4942
4943//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004944// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004945//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004946
4947namespace {
4948
John McCall12f23522016-04-04 18:33:08 +00004949class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004950public:
4951 enum ABIKind {
4952 APCS = 0,
4953 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004954 AAPCS_VFP = 2,
4955 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004956 };
4957
4958private:
4959 ABIKind Kind;
4960
4961public:
John McCall12f23522016-04-04 18:33:08 +00004962 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
4963 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004964 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004965 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004966
John McCall3480ef22011-08-30 01:42:09 +00004967 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004968 switch (getTarget().getTriple().getEnvironment()) {
4969 case llvm::Triple::Android:
4970 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004971 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004972 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004973 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00004974 case llvm::Triple::MuslEABI:
4975 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004976 return true;
4977 default:
4978 return false;
4979 }
John McCall3480ef22011-08-30 01:42:09 +00004980 }
4981
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004982 bool isEABIHF() const {
4983 switch (getTarget().getTriple().getEnvironment()) {
4984 case llvm::Triple::EABIHF:
4985 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00004986 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004987 return true;
4988 default:
4989 return false;
4990 }
4991 }
4992
Daniel Dunbar020daa92009-09-12 01:00:39 +00004993 ABIKind getABIKind() const { return Kind; }
4994
Tim Northovera484bc02013-10-01 14:34:25 +00004995private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004996 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004997 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004998 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004999
Reid Klecknere9f6a712014-10-31 17:10:41 +00005000 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5001 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5002 uint64_t Members) const override;
5003
Craig Topper4f12f102014-03-12 06:41:41 +00005004 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005005
John McCall7f416cc2015-09-08 08:05:57 +00005006 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5007 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005008
5009 llvm::CallingConv::ID getLLVMDefaultCC() const;
5010 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005011 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005012
5013 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5014 ArrayRef<llvm::Type*> scalars,
5015 bool asReturnValue) const override {
5016 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5017 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005018};
5019
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005020class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5021public:
Chris Lattner2b037972010-07-29 02:01:43 +00005022 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5023 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005024
John McCall3480ef22011-08-30 01:42:09 +00005025 const ARMABIInfo &getABIInfo() const {
5026 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5027 }
5028
Craig Topper4f12f102014-03-12 06:41:41 +00005029 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005030 return 13;
5031 }
Roman Divackyc1617352011-05-18 19:36:54 +00005032
Craig Topper4f12f102014-03-12 06:41:41 +00005033 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005034 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5035 }
5036
Roman Divackyc1617352011-05-18 19:36:54 +00005037 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005038 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005039 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005040
5041 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005042 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005043 return false;
5044 }
John McCall3480ef22011-08-30 01:42:09 +00005045
Craig Topper4f12f102014-03-12 06:41:41 +00005046 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005047 if (getABIInfo().isEABI()) return 88;
5048 return TargetCodeGenInfo::getSizeOfUnwindException();
5049 }
Tim Northovera484bc02013-10-01 14:34:25 +00005050
Eric Christopher162c91c2015-06-05 22:03:00 +00005051 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005052 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005053 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005054 if (!FD)
5055 return;
5056
5057 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5058 if (!Attr)
5059 return;
5060
5061 const char *Kind;
5062 switch (Attr->getInterrupt()) {
5063 case ARMInterruptAttr::Generic: Kind = ""; break;
5064 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5065 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5066 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5067 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5068 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5069 }
5070
5071 llvm::Function *Fn = cast<llvm::Function>(GV);
5072
5073 Fn->addFnAttr("interrupt", Kind);
5074
Tim Northover5627d392015-10-30 16:30:45 +00005075 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5076 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005077 return;
5078
5079 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5080 // however this is not necessarily true on taking any interrupt. Instruct
5081 // the backend to perform a realignment as part of the function prologue.
5082 llvm::AttrBuilder B;
5083 B.addStackAlignmentAttr(8);
5084 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5085 llvm::AttributeSet::get(CGM.getLLVMContext(),
5086 llvm::AttributeSet::FunctionIndex,
5087 B));
5088 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005089};
5090
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005091class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005092public:
5093 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5094 : ARMTargetCodeGenInfo(CGT, K) {}
5095
Eric Christopher162c91c2015-06-05 22:03:00 +00005096 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005097 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005098
5099 void getDependentLibraryOption(llvm::StringRef Lib,
5100 llvm::SmallString<24> &Opt) const override {
5101 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5102 }
5103
5104 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5105 llvm::SmallString<32> &Opt) const override {
5106 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5107 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005108};
5109
Eric Christopher162c91c2015-06-05 22:03:00 +00005110void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005111 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005112 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005113 addStackProbeSizeTargetAttribute(D, GV, CGM);
5114}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005115}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005116
Chris Lattner22326a12010-07-29 02:31:05 +00005117void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005118 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005119 FI.getReturnInfo() =
5120 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005121
Tim Northoverbc784d12015-02-24 17:22:40 +00005122 for (auto &I : FI.arguments())
5123 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005124
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005125 // Always honor user-specified calling convention.
5126 if (FI.getCallingConvention() != llvm::CallingConv::C)
5127 return;
5128
John McCall882987f2013-02-28 19:01:20 +00005129 llvm::CallingConv::ID cc = getRuntimeCC();
5130 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005131 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005132}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005133
John McCall882987f2013-02-28 19:01:20 +00005134/// Return the default calling convention that LLVM will use.
5135llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5136 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005137 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005138 return llvm::CallingConv::ARM_AAPCS_VFP;
5139 else if (isEABI())
5140 return llvm::CallingConv::ARM_AAPCS;
5141 else
5142 return llvm::CallingConv::ARM_APCS;
5143}
5144
5145/// Return the calling convention that our ABI would like us to use
5146/// as the C calling convention.
5147llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005148 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005149 case APCS: return llvm::CallingConv::ARM_APCS;
5150 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5151 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005152 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005153 }
John McCall882987f2013-02-28 19:01:20 +00005154 llvm_unreachable("bad ABI kind");
5155}
5156
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005157void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005158 assert(getRuntimeCC() == llvm::CallingConv::C);
5159
5160 // Don't muddy up the IR with a ton of explicit annotations if
5161 // they'd just match what LLVM will infer from the triple.
5162 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5163 if (abiCC != getLLVMDefaultCC())
5164 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005165
Tim Northover5627d392015-10-30 16:30:45 +00005166 // AAPCS apparently requires runtime support functions to be soft-float, but
5167 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5168 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5169 switch (getABIKind()) {
5170 case APCS:
5171 case AAPCS16_VFP:
5172 if (abiCC != getLLVMDefaultCC())
5173 BuiltinCC = abiCC;
5174 break;
5175 case AAPCS:
5176 case AAPCS_VFP:
5177 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5178 break;
5179 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005180}
5181
Tim Northoverbc784d12015-02-24 17:22:40 +00005182ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5183 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005184 // 6.1.2.1 The following argument types are VFP CPRCs:
5185 // A single-precision floating-point type (including promoted
5186 // half-precision types); A double-precision floating-point type;
5187 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5188 // with a Base Type of a single- or double-precision floating-point type,
5189 // 64-bit containerized vectors or 128-bit containerized vectors with one
5190 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005191 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005192
Reid Klecknerb1be6832014-11-15 01:41:41 +00005193 Ty = useFirstFieldIfTransparentUnion(Ty);
5194
Manman Renfef9e312012-10-16 19:18:39 +00005195 // Handle illegal vector types here.
5196 if (isIllegalVectorType(Ty)) {
5197 uint64_t Size = getContext().getTypeSize(Ty);
5198 if (Size <= 32) {
5199 llvm::Type *ResType =
5200 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005201 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005202 }
5203 if (Size == 64) {
5204 llvm::Type *ResType = llvm::VectorType::get(
5205 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005206 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005207 }
5208 if (Size == 128) {
5209 llvm::Type *ResType = llvm::VectorType::get(
5210 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005211 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005212 }
John McCall7f416cc2015-09-08 08:05:57 +00005213 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005214 }
5215
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005216 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5217 // unspecified. This is not done for OpenCL as it handles the half type
5218 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005219 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005220 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5221 llvm::Type::getFloatTy(getVMContext()) :
5222 llvm::Type::getInt32Ty(getVMContext());
5223 return ABIArgInfo::getDirect(ResType);
5224 }
5225
John McCalla1dee5302010-08-22 10:59:02 +00005226 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005227 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005228 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005229 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005230 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005231
Tim Northover5a1558e2014-11-07 22:30:50 +00005232 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5233 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005234 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005235
Oliver Stannard405bded2014-02-11 09:25:50 +00005236 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005237 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005238 }
Tim Northover1060eae2013-06-21 22:49:34 +00005239
Daniel Dunbar09d33622009-09-14 21:54:03 +00005240 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005241 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005242 return ABIArgInfo::getIgnore();
5243
Tim Northover5a1558e2014-11-07 22:30:50 +00005244 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005245 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5246 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005247 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005248 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005249 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005250 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005251 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005252 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005253 }
Tim Northover5627d392015-10-30 16:30:45 +00005254 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5255 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5256 // this convention even for a variadic function: the backend will use GPRs
5257 // if needed.
5258 const Type *Base = nullptr;
5259 uint64_t Members = 0;
5260 if (isHomogeneousAggregate(Ty, Base, Members)) {
5261 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5262 llvm::Type *Ty =
5263 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5264 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5265 }
5266 }
5267
5268 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5269 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5270 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5271 // bigger than 128-bits, they get placed in space allocated by the caller,
5272 // and a pointer is passed.
5273 return ABIArgInfo::getIndirect(
5274 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005275 }
5276
Manman Ren6c30e132012-08-13 21:23:55 +00005277 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005278 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5279 // most 8-byte. We realign the indirect argument if type alignment is bigger
5280 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005281 uint64_t ABIAlign = 4;
5282 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5283 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005284 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005285 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005286
Manman Ren8cd99812012-11-06 04:58:01 +00005287 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005288 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005289 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5290 /*ByVal=*/true,
5291 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005292 }
5293
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005294 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005295 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005296 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005297 // FIXME: Try to match the types of the arguments more accurately where
5298 // we can.
5299 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005300 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5301 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005302 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005303 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5304 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005305 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005306
Tim Northover5a1558e2014-11-07 22:30:50 +00005307 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005308}
5309
Chris Lattner458b2aa2010-07-29 02:16:43 +00005310static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005311 llvm::LLVMContext &VMContext) {
5312 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5313 // is called integer-like if its size is less than or equal to one word, and
5314 // the offset of each of its addressable sub-fields is zero.
5315
5316 uint64_t Size = Context.getTypeSize(Ty);
5317
5318 // Check that the type fits in a word.
5319 if (Size > 32)
5320 return false;
5321
5322 // FIXME: Handle vector types!
5323 if (Ty->isVectorType())
5324 return false;
5325
Daniel Dunbard53bac72009-09-14 02:20:34 +00005326 // Float types are never treated as "integer like".
5327 if (Ty->isRealFloatingType())
5328 return false;
5329
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005330 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005331 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005332 return true;
5333
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005334 // Small complex integer types are "integer like".
5335 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5336 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005337
5338 // Single element and zero sized arrays should be allowed, by the definition
5339 // above, but they are not.
5340
5341 // Otherwise, it must be a record type.
5342 const RecordType *RT = Ty->getAs<RecordType>();
5343 if (!RT) return false;
5344
5345 // Ignore records with flexible arrays.
5346 const RecordDecl *RD = RT->getDecl();
5347 if (RD->hasFlexibleArrayMember())
5348 return false;
5349
5350 // Check that all sub-fields are at offset 0, and are themselves "integer
5351 // like".
5352 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5353
5354 bool HadField = false;
5355 unsigned idx = 0;
5356 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5357 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005358 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005359
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005360 // Bit-fields are not addressable, we only need to verify they are "integer
5361 // like". We still have to disallow a subsequent non-bitfield, for example:
5362 // struct { int : 0; int x }
5363 // is non-integer like according to gcc.
5364 if (FD->isBitField()) {
5365 if (!RD->isUnion())
5366 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005367
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005368 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5369 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005370
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005371 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005372 }
5373
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005374 // Check if this field is at offset 0.
5375 if (Layout.getFieldOffset(idx) != 0)
5376 return false;
5377
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005378 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5379 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005380
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005381 // Only allow at most one field in a structure. This doesn't match the
5382 // wording above, but follows gcc in situations with a field following an
5383 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005384 if (!RD->isUnion()) {
5385 if (HadField)
5386 return false;
5387
5388 HadField = true;
5389 }
5390 }
5391
5392 return true;
5393}
5394
Oliver Stannard405bded2014-02-11 09:25:50 +00005395ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5396 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005397 bool IsEffectivelyAAPCS_VFP =
5398 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005399
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005400 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005401 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005402
Daniel Dunbar19964db2010-09-23 01:54:32 +00005403 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005404 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005405 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005406 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005407
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005408 // __fp16 gets returned as if it were an int or float, but with the top 16
5409 // bits unspecified. This is not done for OpenCL as it handles the half type
5410 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005411 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005412 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5413 llvm::Type::getFloatTy(getVMContext()) :
5414 llvm::Type::getInt32Ty(getVMContext());
5415 return ABIArgInfo::getDirect(ResType);
5416 }
5417
John McCalla1dee5302010-08-22 10:59:02 +00005418 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005419 // Treat an enum type as its underlying type.
5420 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5421 RetTy = EnumTy->getDecl()->getIntegerType();
5422
Tim Northover5a1558e2014-11-07 22:30:50 +00005423 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5424 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005425 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005426
5427 // Are we following APCS?
5428 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005429 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005430 return ABIArgInfo::getIgnore();
5431
Daniel Dunbareedf1512010-02-01 23:31:19 +00005432 // Complex types are all returned as packed integers.
5433 //
5434 // FIXME: Consider using 2 x vector types if the back end handles them
5435 // correctly.
5436 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005437 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5438 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005439
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005440 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005441 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005442 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005443 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005444 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005445 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005446 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005447 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5448 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005449 }
5450
5451 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005452 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005453 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005454
5455 // Otherwise this is an AAPCS variant.
5456
Chris Lattner458b2aa2010-07-29 02:16:43 +00005457 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005458 return ABIArgInfo::getIgnore();
5459
Bob Wilson1d9269a2011-11-02 04:51:36 +00005460 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005461 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005462 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005463 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005464 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005465 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005466 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005467 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005468 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005469 }
5470
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005471 // Aggregates <= 4 bytes are returned in r0; other aggregates
5472 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005473 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005474 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005475 if (getDataLayout().isBigEndian())
5476 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005477 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005478
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005479 // Return in the smallest viable integer type.
5480 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005481 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005482 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005483 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5484 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005485 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5486 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5487 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005488 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005489 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005490 }
5491
John McCall7f416cc2015-09-08 08:05:57 +00005492 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005493}
5494
Manman Renfef9e312012-10-16 19:18:39 +00005495/// isIllegalVector - check whether Ty is an illegal vector type.
5496bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005497 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5498 if (isAndroid()) {
5499 // Android shipped using Clang 3.1, which supported a slightly different
5500 // vector ABI. The primary differences were that 3-element vector types
5501 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5502 // accepts that legacy behavior for Android only.
5503 // Check whether VT is legal.
5504 unsigned NumElements = VT->getNumElements();
5505 // NumElements should be power of 2 or equal to 3.
5506 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5507 return true;
5508 } else {
5509 // Check whether VT is legal.
5510 unsigned NumElements = VT->getNumElements();
5511 uint64_t Size = getContext().getTypeSize(VT);
5512 // NumElements should be power of 2.
5513 if (!llvm::isPowerOf2_32(NumElements))
5514 return true;
5515 // Size should be greater than 32 bits.
5516 return Size <= 32;
5517 }
Manman Renfef9e312012-10-16 19:18:39 +00005518 }
5519 return false;
5520}
5521
Reid Klecknere9f6a712014-10-31 17:10:41 +00005522bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5523 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5524 // double, or 64-bit or 128-bit vectors.
5525 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5526 if (BT->getKind() == BuiltinType::Float ||
5527 BT->getKind() == BuiltinType::Double ||
5528 BT->getKind() == BuiltinType::LongDouble)
5529 return true;
5530 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5531 unsigned VecSize = getContext().getTypeSize(VT);
5532 if (VecSize == 64 || VecSize == 128)
5533 return true;
5534 }
5535 return false;
5536}
5537
5538bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5539 uint64_t Members) const {
5540 return Members <= 4;
5541}
5542
John McCall7f416cc2015-09-08 08:05:57 +00005543Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5544 QualType Ty) const {
5545 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005546
John McCall7f416cc2015-09-08 08:05:57 +00005547 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005548 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005549 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5550 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5551 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005552 }
5553
John McCall7f416cc2015-09-08 08:05:57 +00005554 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5555 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005556
John McCall7f416cc2015-09-08 08:05:57 +00005557 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5558 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005559 const Type *Base = nullptr;
5560 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005561 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5562 IsIndirect = true;
5563
Tim Northover5627d392015-10-30 16:30:45 +00005564 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5565 // allocated by the caller.
5566 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5567 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5568 !isHomogeneousAggregate(Ty, Base, Members)) {
5569 IsIndirect = true;
5570
John McCall7f416cc2015-09-08 08:05:57 +00005571 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005572 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5573 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005574 // Our callers should be prepared to handle an under-aligned address.
5575 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5576 getABIKind() == ARMABIInfo::AAPCS) {
5577 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5578 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005579 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5580 // ARMv7k allows type alignment up to 16 bytes.
5581 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5582 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005583 } else {
5584 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005585 }
John McCall7f416cc2015-09-08 08:05:57 +00005586 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005587
John McCall7f416cc2015-09-08 08:05:57 +00005588 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5589 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005590}
5591
Chris Lattner0cf24192010-06-28 20:05:43 +00005592//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005593// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005594//===----------------------------------------------------------------------===//
5595
5596namespace {
5597
Justin Holewinski83e96682012-05-24 17:43:12 +00005598class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005599public:
Justin Holewinski36837432013-03-30 14:38:24 +00005600 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005601
5602 ABIArgInfo classifyReturnType(QualType RetTy) const;
5603 ABIArgInfo classifyArgumentType(QualType Ty) const;
5604
Craig Topper4f12f102014-03-12 06:41:41 +00005605 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005606 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5607 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005608};
5609
Justin Holewinski83e96682012-05-24 17:43:12 +00005610class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005611public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005612 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5613 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005614
Eric Christopher162c91c2015-06-05 22:03:00 +00005615 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005616 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005617private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005618 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5619 // resulting MDNode to the nvvm.annotations MDNode.
5620 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005621};
5622
Justin Holewinski83e96682012-05-24 17:43:12 +00005623ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005624 if (RetTy->isVoidType())
5625 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005626
5627 // note: this is different from default ABI
5628 if (!RetTy->isScalarType())
5629 return ABIArgInfo::getDirect();
5630
5631 // Treat an enum type as its underlying type.
5632 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5633 RetTy = EnumTy->getDecl()->getIntegerType();
5634
5635 return (RetTy->isPromotableIntegerType() ?
5636 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005637}
5638
Justin Holewinski83e96682012-05-24 17:43:12 +00005639ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005640 // Treat an enum type as its underlying type.
5641 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5642 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005643
Eli Bendersky95338a02014-10-29 13:43:21 +00005644 // Return aggregates type as indirect by value
5645 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005646 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005647
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005648 return (Ty->isPromotableIntegerType() ?
5649 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005650}
5651
Justin Holewinski83e96682012-05-24 17:43:12 +00005652void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005653 if (!getCXXABI().classifyReturnType(FI))
5654 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005655 for (auto &I : FI.arguments())
5656 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005657
5658 // Always honor user-specified calling convention.
5659 if (FI.getCallingConvention() != llvm::CallingConv::C)
5660 return;
5661
John McCall882987f2013-02-28 19:01:20 +00005662 FI.setEffectiveCallingConvention(getRuntimeCC());
5663}
5664
John McCall7f416cc2015-09-08 08:05:57 +00005665Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5666 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005667 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005668}
5669
Justin Holewinski83e96682012-05-24 17:43:12 +00005670void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005671setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005672 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005673 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005674 if (!FD) return;
5675
5676 llvm::Function *F = cast<llvm::Function>(GV);
5677
5678 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005679 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005680 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005681 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005682 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005683 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005684 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5685 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005686 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005687 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005688 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005689 }
Justin Holewinski38031972011-10-05 17:58:44 +00005690
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005691 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005692 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005693 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005694 // __global__ functions cannot be called from the device, we do not
5695 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005696 if (FD->hasAttr<CUDAGlobalAttr>()) {
5697 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5698 addNVVMMetadata(F, "kernel", 1);
5699 }
Artem Belevich7093e402015-04-21 22:55:54 +00005700 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005701 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005702 llvm::APSInt MaxThreads(32);
5703 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5704 if (MaxThreads > 0)
5705 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5706
5707 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5708 // not specified in __launch_bounds__ or if the user specified a 0 value,
5709 // we don't have to add a PTX directive.
5710 if (Attr->getMinBlocks()) {
5711 llvm::APSInt MinBlocks(32);
5712 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5713 if (MinBlocks > 0)
5714 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5715 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005716 }
5717 }
Justin Holewinski38031972011-10-05 17:58:44 +00005718 }
5719}
5720
Eli Benderskye06a2c42014-04-15 16:57:05 +00005721void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5722 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005723 llvm::Module *M = F->getParent();
5724 llvm::LLVMContext &Ctx = M->getContext();
5725
5726 // Get "nvvm.annotations" metadata node
5727 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5728
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005729 llvm::Metadata *MDVals[] = {
5730 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5731 llvm::ConstantAsMetadata::get(
5732 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005733 // Append metadata to nvvm.annotations
5734 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5735}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005736}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005737
5738//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005739// SystemZ ABI Implementation
5740//===----------------------------------------------------------------------===//
5741
5742namespace {
5743
Bryan Chane3f1ed52016-04-28 13:56:43 +00005744class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005745 bool HasVector;
5746
Ulrich Weigand47445072013-05-06 16:26:41 +00005747public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005748 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005749 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005750
5751 bool isPromotableIntegerType(QualType Ty) const;
5752 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005753 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005754 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005755 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005756
5757 ABIArgInfo classifyReturnType(QualType RetTy) const;
5758 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5759
Craig Topper4f12f102014-03-12 06:41:41 +00005760 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005761 if (!getCXXABI().classifyReturnType(FI))
5762 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005763 for (auto &I : FI.arguments())
5764 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005765 }
5766
John McCall7f416cc2015-09-08 08:05:57 +00005767 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5768 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005769
5770 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5771 ArrayRef<llvm::Type*> scalars,
5772 bool asReturnValue) const override {
5773 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5774 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005775};
5776
5777class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5778public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005779 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5780 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005781};
5782
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005783}
Ulrich Weigand47445072013-05-06 16:26:41 +00005784
5785bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5786 // Treat an enum type as its underlying type.
5787 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5788 Ty = EnumTy->getDecl()->getIntegerType();
5789
5790 // Promotable integer types are required to be promoted by the ABI.
5791 if (Ty->isPromotableIntegerType())
5792 return true;
5793
5794 // 32-bit values must also be promoted.
5795 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5796 switch (BT->getKind()) {
5797 case BuiltinType::Int:
5798 case BuiltinType::UInt:
5799 return true;
5800 default:
5801 return false;
5802 }
5803 return false;
5804}
5805
5806bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005807 return (Ty->isAnyComplexType() ||
5808 Ty->isVectorType() ||
5809 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005810}
5811
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005812bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5813 return (HasVector &&
5814 Ty->isVectorType() &&
5815 getContext().getTypeSize(Ty) <= 128);
5816}
5817
Ulrich Weigand47445072013-05-06 16:26:41 +00005818bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5819 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5820 switch (BT->getKind()) {
5821 case BuiltinType::Float:
5822 case BuiltinType::Double:
5823 return true;
5824 default:
5825 return false;
5826 }
5827
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005828 return false;
5829}
5830
5831QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005832 if (const RecordType *RT = Ty->getAsStructureType()) {
5833 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005834 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005835
5836 // If this is a C++ record, check the bases first.
5837 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005838 for (const auto &I : CXXRD->bases()) {
5839 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005840
5841 // Empty bases don't affect things either way.
5842 if (isEmptyRecord(getContext(), Base, true))
5843 continue;
5844
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005845 if (!Found.isNull())
5846 return Ty;
5847 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005848 }
5849
5850 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005851 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005852 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005853 // Unlike isSingleElementStruct(), empty structure and array fields
5854 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005855 if (getContext().getLangOpts().CPlusPlus &&
5856 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5857 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005858
5859 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005860 // Nested structures still do though.
5861 if (!Found.isNull())
5862 return Ty;
5863 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005864 }
5865
5866 // Unlike isSingleElementStruct(), trailing padding is allowed.
5867 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005868 if (!Found.isNull())
5869 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005870 }
5871
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005872 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005873}
5874
John McCall7f416cc2015-09-08 08:05:57 +00005875Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5876 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005877 // Assume that va_list type is correct; should be pointer to LLVM type:
5878 // struct {
5879 // i64 __gpr;
5880 // i64 __fpr;
5881 // i8 *__overflow_arg_area;
5882 // i8 *__reg_save_area;
5883 // };
5884
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005885 // Every non-vector argument occupies 8 bytes and is passed by preference
5886 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5887 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005888 Ty = getContext().getCanonicalType(Ty);
5889 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005890 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005891 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005892 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005893 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005894 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005895 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005896 CharUnits UnpaddedSize;
5897 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005898 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005899 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5900 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005901 } else {
5902 if (AI.getCoerceToType())
5903 ArgTy = AI.getCoerceToType();
5904 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005905 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005906 UnpaddedSize = TyInfo.first;
5907 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005908 }
John McCall7f416cc2015-09-08 08:05:57 +00005909 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5910 if (IsVector && UnpaddedSize > PaddedSize)
5911 PaddedSize = CharUnits::fromQuantity(16);
5912 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005913
John McCall7f416cc2015-09-08 08:05:57 +00005914 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005915
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005916 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005917 llvm::Value *PaddedSizeV =
5918 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005919
5920 if (IsVector) {
5921 // Work out the address of a vector argument on the stack.
5922 // Vector arguments are always passed in the high bits of a
5923 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005924 Address OverflowArgAreaPtr =
5925 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005926 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005927 Address OverflowArgArea =
5928 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5929 TyInfo.second);
5930 Address MemAddr =
5931 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005932
5933 // Update overflow_arg_area_ptr pointer
5934 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005935 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5936 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005937 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5938
5939 return MemAddr;
5940 }
5941
John McCall7f416cc2015-09-08 08:05:57 +00005942 assert(PaddedSize.getQuantity() == 8);
5943
5944 unsigned MaxRegs, RegCountField, RegSaveIndex;
5945 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005946 if (InFPRs) {
5947 MaxRegs = 4; // Maximum of 4 FPR arguments
5948 RegCountField = 1; // __fpr
5949 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005950 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005951 } else {
5952 MaxRegs = 5; // Maximum of 5 GPR arguments
5953 RegCountField = 0; // __gpr
5954 RegSaveIndex = 2; // save offset for r2
5955 RegPadding = Padding; // values are passed in the low bits of a GPR
5956 }
5957
John McCall7f416cc2015-09-08 08:05:57 +00005958 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5959 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5960 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005961 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005962 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5963 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005964 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005965
5966 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5967 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5968 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5969 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5970
5971 // Emit code to load the value if it was passed in registers.
5972 CGF.EmitBlock(InRegBlock);
5973
5974 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005975 llvm::Value *ScaledRegCount =
5976 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5977 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005978 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5979 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005980 llvm::Value *RegOffset =
5981 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005982 Address RegSaveAreaPtr =
5983 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5984 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005985 llvm::Value *RegSaveArea =
5986 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005987 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5988 "raw_reg_addr"),
5989 PaddedSize);
5990 Address RegAddr =
5991 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005992
5993 // Update the register count
5994 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5995 llvm::Value *NewRegCount =
5996 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5997 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5998 CGF.EmitBranch(ContBlock);
5999
6000 // Emit code to load the value if it was passed in memory.
6001 CGF.EmitBlock(InMemBlock);
6002
6003 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006004 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6005 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6006 Address OverflowArgArea =
6007 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6008 PaddedSize);
6009 Address RawMemAddr =
6010 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6011 Address MemAddr =
6012 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006013
6014 // Update overflow_arg_area_ptr pointer
6015 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006016 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6017 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006018 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6019 CGF.EmitBranch(ContBlock);
6020
6021 // Return the appropriate result.
6022 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006023 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6024 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006025
6026 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006027 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6028 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006029
6030 return ResAddr;
6031}
6032
Ulrich Weigand47445072013-05-06 16:26:41 +00006033ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6034 if (RetTy->isVoidType())
6035 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006036 if (isVectorArgumentType(RetTy))
6037 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006038 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006039 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006040 return (isPromotableIntegerType(RetTy) ?
6041 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6042}
6043
6044ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6045 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006046 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006047 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006048
6049 // Integers and enums are extended to full register width.
6050 if (isPromotableIntegerType(Ty))
6051 return ABIArgInfo::getExtend();
6052
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006053 // Handle vector types and vector-like structure types. Note that
6054 // as opposed to float-like structure types, we do not allow any
6055 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006056 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006057 QualType SingleElementTy = GetSingleElementType(Ty);
6058 if (isVectorArgumentType(SingleElementTy) &&
6059 getContext().getTypeSize(SingleElementTy) == Size)
6060 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6061
6062 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006063 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006064 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006065
6066 // Handle small structures.
6067 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6068 // Structures with flexible arrays have variable length, so really
6069 // fail the size test above.
6070 const RecordDecl *RD = RT->getDecl();
6071 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006072 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006073
6074 // The structure is passed as an unextended integer, a float, or a double.
6075 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006076 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006077 assert(Size == 32 || Size == 64);
6078 if (Size == 32)
6079 PassTy = llvm::Type::getFloatTy(getVMContext());
6080 else
6081 PassTy = llvm::Type::getDoubleTy(getVMContext());
6082 } else
6083 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6084 return ABIArgInfo::getDirect(PassTy);
6085 }
6086
6087 // Non-structure compounds are passed indirectly.
6088 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006089 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006090
Craig Topper8a13c412014-05-21 05:09:00 +00006091 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006092}
6093
6094//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006095// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006096//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006097
6098namespace {
6099
6100class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6101public:
Chris Lattner2b037972010-07-29 02:01:43 +00006102 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6103 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006104 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006105 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006106};
6107
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006108}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006109
Eric Christopher162c91c2015-06-05 22:03:00 +00006110void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006111 llvm::GlobalValue *GV,
6112 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006113 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006114 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6115 // Handle 'interrupt' attribute:
6116 llvm::Function *F = cast<llvm::Function>(GV);
6117
6118 // Step 1: Set ISR calling convention.
6119 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6120
6121 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006122 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006123
6124 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006125 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006126 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6127 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006128 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006129 }
6130}
6131
Chris Lattner0cf24192010-06-28 20:05:43 +00006132//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006133// MIPS ABI Implementation. This works for both little-endian and
6134// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006135//===----------------------------------------------------------------------===//
6136
John McCall943fae92010-05-27 06:19:26 +00006137namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006138class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006139 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006140 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6141 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006142 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006143 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006144 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006145 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006146public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006147 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006148 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006149 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006150
6151 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006152 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006153 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006154 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6155 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006156 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006157};
6158
John McCall943fae92010-05-27 06:19:26 +00006159class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006160 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006161public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006162 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6163 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006164 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006165
Craig Topper4f12f102014-03-12 06:41:41 +00006166 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006167 return 29;
6168 }
6169
Eric Christopher162c91c2015-06-05 22:03:00 +00006170 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006171 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006172 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006173 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006174 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006175 if (FD->hasAttr<Mips16Attr>()) {
6176 Fn->addFnAttr("mips16");
6177 }
6178 else if (FD->hasAttr<NoMips16Attr>()) {
6179 Fn->addFnAttr("nomips16");
6180 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006181
6182 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6183 if (!Attr)
6184 return;
6185
6186 const char *Kind;
6187 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006188 case MipsInterruptAttr::eic: Kind = "eic"; break;
6189 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6190 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6191 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6192 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6193 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6194 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6195 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6196 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6197 }
6198
6199 Fn->addFnAttr("interrupt", Kind);
6200
Reed Kotler373feca2013-01-16 17:10:28 +00006201 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006202
John McCall943fae92010-05-27 06:19:26 +00006203 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006204 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006205
Craig Topper4f12f102014-03-12 06:41:41 +00006206 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006207 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006208 }
John McCall943fae92010-05-27 06:19:26 +00006209};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006210}
John McCall943fae92010-05-27 06:19:26 +00006211
Eric Christopher7565e0d2015-05-29 23:09:49 +00006212void MipsABIInfo::CoerceToIntArgs(
6213 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006214 llvm::IntegerType *IntTy =
6215 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006216
6217 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6218 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6219 ArgList.push_back(IntTy);
6220
6221 // If necessary, add one more integer type to ArgList.
6222 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6223
6224 if (R)
6225 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006226}
6227
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006228// In N32/64, an aligned double precision floating point field is passed in
6229// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006230llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006231 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6232
6233 if (IsO32) {
6234 CoerceToIntArgs(TySize, ArgList);
6235 return llvm::StructType::get(getVMContext(), ArgList);
6236 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006237
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006238 if (Ty->isComplexType())
6239 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006240
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006241 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006242
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006243 // Unions/vectors are passed in integer registers.
6244 if (!RT || !RT->isStructureOrClassType()) {
6245 CoerceToIntArgs(TySize, ArgList);
6246 return llvm::StructType::get(getVMContext(), ArgList);
6247 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006248
6249 const RecordDecl *RD = RT->getDecl();
6250 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006251 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006252
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006253 uint64_t LastOffset = 0;
6254 unsigned idx = 0;
6255 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6256
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006257 // Iterate over fields in the struct/class and check if there are any aligned
6258 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006259 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6260 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006261 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006262 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6263
6264 if (!BT || BT->getKind() != BuiltinType::Double)
6265 continue;
6266
6267 uint64_t Offset = Layout.getFieldOffset(idx);
6268 if (Offset % 64) // Ignore doubles that are not aligned.
6269 continue;
6270
6271 // Add ((Offset - LastOffset) / 64) args of type i64.
6272 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6273 ArgList.push_back(I64);
6274
6275 // Add double type.
6276 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6277 LastOffset = Offset + 64;
6278 }
6279
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006280 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6281 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006282
6283 return llvm::StructType::get(getVMContext(), ArgList);
6284}
6285
Akira Hatanakaddd66342013-10-29 18:41:15 +00006286llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6287 uint64_t Offset) const {
6288 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006289 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006290
Akira Hatanakaddd66342013-10-29 18:41:15 +00006291 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006292}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006293
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006294ABIArgInfo
6295MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006296 Ty = useFirstFieldIfTransparentUnion(Ty);
6297
Akira Hatanaka1632af62012-01-09 19:31:25 +00006298 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006299 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006300 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006301
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006302 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6303 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006304 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6305 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006306
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006307 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006308 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006309 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006310 return ABIArgInfo::getIgnore();
6311
Mark Lacey3825e832013-10-06 01:33:34 +00006312 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006313 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006314 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006315 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006316
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006317 // If we have reached here, aggregates are passed directly by coercing to
6318 // another structure type. Padding is inserted if the offset of the
6319 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006320 ABIArgInfo ArgInfo =
6321 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6322 getPaddingType(OrigOffset, CurrOffset));
6323 ArgInfo.setInReg(true);
6324 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006325 }
6326
6327 // Treat an enum type as its underlying type.
6328 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6329 Ty = EnumTy->getDecl()->getIntegerType();
6330
Daniel Sanders5b445b32014-10-24 14:42:42 +00006331 // All integral types are promoted to the GPR width.
6332 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006333 return ABIArgInfo::getExtend();
6334
Akira Hatanakaddd66342013-10-29 18:41:15 +00006335 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006336 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006337}
6338
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006339llvm::Type*
6340MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006341 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006342 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006343
Akira Hatanakab6f74432012-02-09 18:49:26 +00006344 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006345 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006346 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6347 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006348
Akira Hatanakab6f74432012-02-09 18:49:26 +00006349 // N32/64 returns struct/classes in floating point registers if the
6350 // following conditions are met:
6351 // 1. The size of the struct/class is no larger than 128-bit.
6352 // 2. The struct/class has one or two fields all of which are floating
6353 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006354 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006355 //
6356 // Any other composite results are returned in integer registers.
6357 //
6358 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6359 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6360 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006361 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006362
Akira Hatanakab6f74432012-02-09 18:49:26 +00006363 if (!BT || !BT->isFloatingPoint())
6364 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006365
David Blaikie2d7c57e2012-04-30 02:36:29 +00006366 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006367 }
6368
6369 if (b == e)
6370 return llvm::StructType::get(getVMContext(), RTList,
6371 RD->hasAttr<PackedAttr>());
6372
6373 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006374 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006375 }
6376
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006377 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006378 return llvm::StructType::get(getVMContext(), RTList);
6379}
6380
Akira Hatanakab579fe52011-06-02 00:09:17 +00006381ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006382 uint64_t Size = getContext().getTypeSize(RetTy);
6383
Daniel Sandersed39f582014-09-04 13:28:14 +00006384 if (RetTy->isVoidType())
6385 return ABIArgInfo::getIgnore();
6386
6387 // O32 doesn't treat zero-sized structs differently from other structs.
6388 // However, N32/N64 ignores zero sized return values.
6389 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006390 return ABIArgInfo::getIgnore();
6391
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006392 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006393 if (Size <= 128) {
6394 if (RetTy->isAnyComplexType())
6395 return ABIArgInfo::getDirect();
6396
Daniel Sanderse5018b62014-09-04 15:05:39 +00006397 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006398 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006399 if (!IsO32 ||
6400 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6401 ABIArgInfo ArgInfo =
6402 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6403 ArgInfo.setInReg(true);
6404 return ArgInfo;
6405 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006406 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006407
John McCall7f416cc2015-09-08 08:05:57 +00006408 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006409 }
6410
6411 // Treat an enum type as its underlying type.
6412 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6413 RetTy = EnumTy->getDecl()->getIntegerType();
6414
6415 return (RetTy->isPromotableIntegerType() ?
6416 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6417}
6418
6419void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006420 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006421 if (!getCXXABI().classifyReturnType(FI))
6422 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006423
Eric Christopher7565e0d2015-05-29 23:09:49 +00006424 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006425 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006426
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006427 for (auto &I : FI.arguments())
6428 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006429}
6430
John McCall7f416cc2015-09-08 08:05:57 +00006431Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6432 QualType OrigTy) const {
6433 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006434
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006435 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6436 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006437 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006438 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006439 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006440 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006441 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006442 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006443 DidPromote = true;
6444 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6445 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006446 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006447
John McCall7f416cc2015-09-08 08:05:57 +00006448 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006449
John McCall7f416cc2015-09-08 08:05:57 +00006450 // The alignment of things in the argument area is never larger than
6451 // StackAlignInBytes.
6452 TyInfo.second =
6453 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6454
6455 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6456 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6457
6458 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6459 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6460
6461
6462 // If there was a promotion, "unpromote" into a temporary.
6463 // TODO: can we just use a pointer into a subset of the original slot?
6464 if (DidPromote) {
6465 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6466 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6467
6468 // Truncate down to the right width.
6469 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6470 : CGF.IntPtrTy);
6471 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6472 if (OrigTy->isPointerType())
6473 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6474
6475 CGF.Builder.CreateStore(V, Temp);
6476 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006477 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006478
John McCall7f416cc2015-09-08 08:05:57 +00006479 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006480}
6481
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006482bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6483 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006484
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006485 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6486 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6487 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006488
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006489 return false;
6490}
6491
John McCall943fae92010-05-27 06:19:26 +00006492bool
6493MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6494 llvm::Value *Address) const {
6495 // This information comes from gcc's implementation, which seems to
6496 // as canonical as it gets.
6497
John McCall943fae92010-05-27 06:19:26 +00006498 // Everything on MIPS is 4 bytes. Double-precision FP registers
6499 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006500 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006501
6502 // 0-31 are the general purpose registers, $0 - $31.
6503 // 32-63 are the floating-point registers, $f0 - $f31.
6504 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6505 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006506 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006507
6508 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6509 // They are one bit wide and ignored here.
6510
6511 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6512 // (coprocessor 1 is the FP unit)
6513 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6514 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6515 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006516 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006517 return false;
6518}
6519
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006520//===----------------------------------------------------------------------===//
6521// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006522// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006523// handling.
6524//===----------------------------------------------------------------------===//
6525
6526namespace {
6527
6528class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6529public:
6530 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6531 : DefaultTargetCodeGenInfo(CGT) {}
6532
Eric Christopher162c91c2015-06-05 22:03:00 +00006533 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006534 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006535};
6536
Eric Christopher162c91c2015-06-05 22:03:00 +00006537void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006538 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006539 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006540 if (!FD) return;
6541
6542 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006543
David Blaikiebbafb8a2012-03-11 07:00:24 +00006544 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006545 if (FD->hasAttr<OpenCLKernelAttr>()) {
6546 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006547 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006548 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6549 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006550 // Convert the reqd_work_group_size() attributes to metadata.
6551 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006552 llvm::NamedMDNode *OpenCLMetadata =
6553 M.getModule().getOrInsertNamedMetadata(
6554 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006555
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006556 SmallVector<llvm::Metadata *, 5> Operands;
6557 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006558
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006559 Operands.push_back(
6560 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6561 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6562 Operands.push_back(
6563 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6564 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6565 Operands.push_back(
6566 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6567 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006568
Eric Christopher7565e0d2015-05-29 23:09:49 +00006569 // Add a boolean constant operand for "required" (true) or "hint"
6570 // (false) for implementing the work_group_size_hint attr later.
6571 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006572 Operands.push_back(
6573 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006574 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6575 }
6576 }
6577 }
6578}
6579
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006580}
John McCall943fae92010-05-27 06:19:26 +00006581
Tony Linthicum76329bf2011-12-12 21:14:55 +00006582//===----------------------------------------------------------------------===//
6583// Hexagon ABI Implementation
6584//===----------------------------------------------------------------------===//
6585
6586namespace {
6587
6588class HexagonABIInfo : public ABIInfo {
6589
6590
6591public:
6592 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6593
6594private:
6595
6596 ABIArgInfo classifyReturnType(QualType RetTy) const;
6597 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6598
Craig Topper4f12f102014-03-12 06:41:41 +00006599 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006600
John McCall7f416cc2015-09-08 08:05:57 +00006601 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6602 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006603};
6604
6605class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6606public:
6607 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6608 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6609
Craig Topper4f12f102014-03-12 06:41:41 +00006610 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006611 return 29;
6612 }
6613};
6614
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006615}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006616
6617void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006618 if (!getCXXABI().classifyReturnType(FI))
6619 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006620 for (auto &I : FI.arguments())
6621 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006622}
6623
6624ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6625 if (!isAggregateTypeForABI(Ty)) {
6626 // Treat an enum type as its underlying type.
6627 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6628 Ty = EnumTy->getDecl()->getIntegerType();
6629
6630 return (Ty->isPromotableIntegerType() ?
6631 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6632 }
6633
6634 // Ignore empty records.
6635 if (isEmptyRecord(getContext(), Ty, true))
6636 return ABIArgInfo::getIgnore();
6637
Mark Lacey3825e832013-10-06 01:33:34 +00006638 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006639 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006640
6641 uint64_t Size = getContext().getTypeSize(Ty);
6642 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006643 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006644 // Pass in the smallest viable integer type.
6645 else if (Size > 32)
6646 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6647 else if (Size > 16)
6648 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6649 else if (Size > 8)
6650 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6651 else
6652 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6653}
6654
6655ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6656 if (RetTy->isVoidType())
6657 return ABIArgInfo::getIgnore();
6658
6659 // Large vector types should be returned via memory.
6660 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006661 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006662
6663 if (!isAggregateTypeForABI(RetTy)) {
6664 // Treat an enum type as its underlying type.
6665 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6666 RetTy = EnumTy->getDecl()->getIntegerType();
6667
6668 return (RetTy->isPromotableIntegerType() ?
6669 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6670 }
6671
Tony Linthicum76329bf2011-12-12 21:14:55 +00006672 if (isEmptyRecord(getContext(), RetTy, true))
6673 return ABIArgInfo::getIgnore();
6674
6675 // Aggregates <= 8 bytes are returned in r0; other aggregates
6676 // are returned indirectly.
6677 uint64_t Size = getContext().getTypeSize(RetTy);
6678 if (Size <= 64) {
6679 // Return in the smallest viable integer type.
6680 if (Size <= 8)
6681 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6682 if (Size <= 16)
6683 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6684 if (Size <= 32)
6685 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6686 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6687 }
6688
John McCall7f416cc2015-09-08 08:05:57 +00006689 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006690}
6691
John McCall7f416cc2015-09-08 08:05:57 +00006692Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6693 QualType Ty) const {
6694 // FIXME: Someone needs to audit that this handle alignment correctly.
6695 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6696 getContext().getTypeInfoInChars(Ty),
6697 CharUnits::fromQuantity(4),
6698 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006699}
6700
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006701//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006702// Lanai ABI Implementation
6703//===----------------------------------------------------------------------===//
6704
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006705namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006706class LanaiABIInfo : public DefaultABIInfo {
6707public:
6708 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6709
6710 bool shouldUseInReg(QualType Ty, CCState &State) const;
6711
6712 void computeInfo(CGFunctionInfo &FI) const override {
6713 CCState State(FI.getCallingConvention());
6714 // Lanai uses 4 registers to pass arguments unless the function has the
6715 // regparm attribute set.
6716 if (FI.getHasRegParm()) {
6717 State.FreeRegs = FI.getRegParm();
6718 } else {
6719 State.FreeRegs = 4;
6720 }
6721
6722 if (!getCXXABI().classifyReturnType(FI))
6723 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6724 for (auto &I : FI.arguments())
6725 I.info = classifyArgumentType(I.type, State);
6726 }
6727
Jacques Pienaare74d9132016-04-26 00:09:29 +00006728 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006729 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6730};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006731} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006732
6733bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6734 unsigned Size = getContext().getTypeSize(Ty);
6735 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6736
6737 if (SizeInRegs == 0)
6738 return false;
6739
6740 if (SizeInRegs > State.FreeRegs) {
6741 State.FreeRegs = 0;
6742 return false;
6743 }
6744
6745 State.FreeRegs -= SizeInRegs;
6746
6747 return true;
6748}
6749
Jacques Pienaare74d9132016-04-26 00:09:29 +00006750ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6751 CCState &State) const {
6752 if (!ByVal) {
6753 if (State.FreeRegs) {
6754 --State.FreeRegs; // Non-byval indirects just use one pointer.
6755 return getNaturalAlignIndirectInReg(Ty);
6756 }
6757 return getNaturalAlignIndirect(Ty, false);
6758 }
6759
6760 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006761 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006762 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6763 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6764 /*Realign=*/TypeAlign >
6765 MinABIStackAlignInBytes);
6766}
6767
Jacques Pienaard964cc22016-03-28 21:02:54 +00006768ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6769 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006770 // Check with the C++ ABI first.
6771 const RecordType *RT = Ty->getAs<RecordType>();
6772 if (RT) {
6773 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6774 if (RAA == CGCXXABI::RAA_Indirect) {
6775 return getIndirectResult(Ty, /*ByVal=*/false, State);
6776 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6777 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6778 }
6779 }
6780
6781 if (isAggregateTypeForABI(Ty)) {
6782 // Structures with flexible arrays are always indirect.
6783 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6784 return getIndirectResult(Ty, /*ByVal=*/true, State);
6785
6786 // Ignore empty structs/unions.
6787 if (isEmptyRecord(getContext(), Ty, true))
6788 return ABIArgInfo::getIgnore();
6789
6790 llvm::LLVMContext &LLVMContext = getVMContext();
6791 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6792 if (SizeInRegs <= State.FreeRegs) {
6793 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6794 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6795 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6796 State.FreeRegs -= SizeInRegs;
6797 return ABIArgInfo::getDirectInReg(Result);
6798 } else {
6799 State.FreeRegs = 0;
6800 }
6801 return getIndirectResult(Ty, true, State);
6802 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00006803
6804 // Treat an enum type as its underlying type.
6805 if (const auto *EnumTy = Ty->getAs<EnumType>())
6806 Ty = EnumTy->getDecl()->getIntegerType();
6807
Jacques Pienaare74d9132016-04-26 00:09:29 +00006808 bool InReg = shouldUseInReg(Ty, State);
6809 if (Ty->isPromotableIntegerType()) {
6810 if (InReg)
6811 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006812 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00006813 }
6814 if (InReg)
6815 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00006816 return ABIArgInfo::getDirect();
6817}
6818
6819namespace {
6820class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
6821public:
6822 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
6823 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
6824};
6825}
6826
6827//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006828// AMDGPU ABI Implementation
6829//===----------------------------------------------------------------------===//
6830
6831namespace {
6832
6833class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6834public:
6835 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6836 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006837 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006838 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00006839 unsigned getOpenCLKernelCallingConv() const override;
Yaxun Liu37ceede2016-07-20 19:21:11 +00006840 unsigned getOpenCLImageAddrSpace(CodeGen::CodeGenModule &CGM) const override;
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006841};
6842
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006843}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006844
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00006845static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
6846
Eric Christopher162c91c2015-06-05 22:03:00 +00006847void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006848 const Decl *D,
6849 llvm::GlobalValue *GV,
6850 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006851 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006852 if (!FD)
6853 return;
6854
6855 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6856 llvm::Function *F = cast<llvm::Function>(GV);
6857 uint32_t NumVGPR = Attr->getNumVGPR();
6858 if (NumVGPR != 0)
6859 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6860 }
6861
6862 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6863 llvm::Function *F = cast<llvm::Function>(GV);
6864 unsigned NumSGPR = Attr->getNumSGPR();
6865 if (NumSGPR != 0)
6866 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6867 }
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006868
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00006869 appendOpenCLVersionMD(M);
6870}
6871
Tony Linthicum76329bf2011-12-12 21:14:55 +00006872
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00006873unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
6874 return llvm::CallingConv::AMDGPU_KERNEL;
6875}
6876
Yaxun Liu37ceede2016-07-20 19:21:11 +00006877unsigned AMDGPUTargetCodeGenInfo::getOpenCLImageAddrSpace(CodeGen::CodeGenModule &CGM) const {
6878 return CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
6879}
6880
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006881//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00006882// SPARC v8 ABI Implementation.
6883// Based on the SPARC Compliance Definition version 2.4.1.
6884//
6885// Ensures that complex values are passed in registers.
6886//
6887namespace {
6888class SparcV8ABIInfo : public DefaultABIInfo {
6889public:
6890 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6891
6892private:
6893 ABIArgInfo classifyReturnType(QualType RetTy) const;
6894 void computeInfo(CGFunctionInfo &FI) const override;
6895};
6896} // end anonymous namespace
6897
6898
6899ABIArgInfo
6900SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
6901 if (Ty->isAnyComplexType()) {
6902 return ABIArgInfo::getDirect();
6903 }
6904 else {
6905 return DefaultABIInfo::classifyReturnType(Ty);
6906 }
6907}
6908
6909void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6910
6911 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6912 for (auto &Arg : FI.arguments())
6913 Arg.info = classifyArgumentType(Arg.type);
6914}
6915
6916namespace {
6917class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
6918public:
6919 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
6920 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
6921};
6922} // end anonymous namespace
6923
6924//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006925// SPARC v9 ABI Implementation.
6926// Based on the SPARC Compliance Definition version 2.4.1.
6927//
6928// Function arguments a mapped to a nominal "parameter array" and promoted to
6929// registers depending on their type. Each argument occupies 8 or 16 bytes in
6930// the array, structs larger than 16 bytes are passed indirectly.
6931//
6932// One case requires special care:
6933//
6934// struct mixed {
6935// int i;
6936// float f;
6937// };
6938//
6939// When a struct mixed is passed by value, it only occupies 8 bytes in the
6940// parameter array, but the int is passed in an integer register, and the float
6941// is passed in a floating point register. This is represented as two arguments
6942// with the LLVM IR inreg attribute:
6943//
6944// declare void f(i32 inreg %i, float inreg %f)
6945//
6946// The code generator will only allocate 4 bytes from the parameter array for
6947// the inreg arguments. All other arguments are allocated a multiple of 8
6948// bytes.
6949//
6950namespace {
6951class SparcV9ABIInfo : public ABIInfo {
6952public:
6953 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6954
6955private:
6956 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006957 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006958 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6959 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006960
6961 // Coercion type builder for structs passed in registers. The coercion type
6962 // serves two purposes:
6963 //
6964 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6965 // in registers.
6966 // 2. Expose aligned floating point elements as first-level elements, so the
6967 // code generator knows to pass them in floating point registers.
6968 //
6969 // We also compute the InReg flag which indicates that the struct contains
6970 // aligned 32-bit floats.
6971 //
6972 struct CoerceBuilder {
6973 llvm::LLVMContext &Context;
6974 const llvm::DataLayout &DL;
6975 SmallVector<llvm::Type*, 8> Elems;
6976 uint64_t Size;
6977 bool InReg;
6978
6979 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6980 : Context(c), DL(dl), Size(0), InReg(false) {}
6981
6982 // Pad Elems with integers until Size is ToSize.
6983 void pad(uint64_t ToSize) {
6984 assert(ToSize >= Size && "Cannot remove elements");
6985 if (ToSize == Size)
6986 return;
6987
6988 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006989 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006990 if (Aligned > Size && Aligned <= ToSize) {
6991 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6992 Size = Aligned;
6993 }
6994
6995 // Add whole 64-bit words.
6996 while (Size + 64 <= ToSize) {
6997 Elems.push_back(llvm::Type::getInt64Ty(Context));
6998 Size += 64;
6999 }
7000
7001 // Final in-word padding.
7002 if (Size < ToSize) {
7003 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7004 Size = ToSize;
7005 }
7006 }
7007
7008 // Add a floating point element at Offset.
7009 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7010 // Unaligned floats are treated as integers.
7011 if (Offset % Bits)
7012 return;
7013 // The InReg flag is only required if there are any floats < 64 bits.
7014 if (Bits < 64)
7015 InReg = true;
7016 pad(Offset);
7017 Elems.push_back(Ty);
7018 Size = Offset + Bits;
7019 }
7020
7021 // Add a struct type to the coercion type, starting at Offset (in bits).
7022 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7023 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7024 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7025 llvm::Type *ElemTy = StrTy->getElementType(i);
7026 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7027 switch (ElemTy->getTypeID()) {
7028 case llvm::Type::StructTyID:
7029 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7030 break;
7031 case llvm::Type::FloatTyID:
7032 addFloat(ElemOffset, ElemTy, 32);
7033 break;
7034 case llvm::Type::DoubleTyID:
7035 addFloat(ElemOffset, ElemTy, 64);
7036 break;
7037 case llvm::Type::FP128TyID:
7038 addFloat(ElemOffset, ElemTy, 128);
7039 break;
7040 case llvm::Type::PointerTyID:
7041 if (ElemOffset % 64 == 0) {
7042 pad(ElemOffset);
7043 Elems.push_back(ElemTy);
7044 Size += 64;
7045 }
7046 break;
7047 default:
7048 break;
7049 }
7050 }
7051 }
7052
7053 // Check if Ty is a usable substitute for the coercion type.
7054 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007055 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007056 }
7057
7058 // Get the coercion type as a literal struct type.
7059 llvm::Type *getType() const {
7060 if (Elems.size() == 1)
7061 return Elems.front();
7062 else
7063 return llvm::StructType::get(Context, Elems);
7064 }
7065 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007066};
7067} // end anonymous namespace
7068
7069ABIArgInfo
7070SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7071 if (Ty->isVoidType())
7072 return ABIArgInfo::getIgnore();
7073
7074 uint64_t Size = getContext().getTypeSize(Ty);
7075
7076 // Anything too big to fit in registers is passed with an explicit indirect
7077 // pointer / sret pointer.
7078 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007079 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007080
7081 // Treat an enum type as its underlying type.
7082 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7083 Ty = EnumTy->getDecl()->getIntegerType();
7084
7085 // Integer types smaller than a register are extended.
7086 if (Size < 64 && Ty->isIntegerType())
7087 return ABIArgInfo::getExtend();
7088
7089 // Other non-aggregates go in registers.
7090 if (!isAggregateTypeForABI(Ty))
7091 return ABIArgInfo::getDirect();
7092
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007093 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7094 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7095 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007096 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007097
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007098 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007099 // Build a coercion type from the LLVM struct type.
7100 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7101 if (!StrTy)
7102 return ABIArgInfo::getDirect();
7103
7104 CoerceBuilder CB(getVMContext(), getDataLayout());
7105 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007106 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007107
7108 // Try to use the original type for coercion.
7109 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7110
7111 if (CB.InReg)
7112 return ABIArgInfo::getDirectInReg(CoerceTy);
7113 else
7114 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007115}
7116
John McCall7f416cc2015-09-08 08:05:57 +00007117Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7118 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007119 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7120 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7121 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7122 AI.setCoerceToType(ArgTy);
7123
John McCall7f416cc2015-09-08 08:05:57 +00007124 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007125
John McCall7f416cc2015-09-08 08:05:57 +00007126 CGBuilderTy &Builder = CGF.Builder;
7127 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7128 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7129
7130 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7131
7132 Address ArgAddr = Address::invalid();
7133 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007134 switch (AI.getKind()) {
7135 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007136 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007137 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007138 llvm_unreachable("Unsupported ABI kind for va_arg");
7139
John McCall7f416cc2015-09-08 08:05:57 +00007140 case ABIArgInfo::Extend: {
7141 Stride = SlotSize;
7142 CharUnits Offset = SlotSize - TypeInfo.first;
7143 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007144 break;
John McCall7f416cc2015-09-08 08:05:57 +00007145 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007146
John McCall7f416cc2015-09-08 08:05:57 +00007147 case ABIArgInfo::Direct: {
7148 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007149 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007150 ArgAddr = Addr;
7151 break;
John McCall7f416cc2015-09-08 08:05:57 +00007152 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007153
7154 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007155 Stride = SlotSize;
7156 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7157 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7158 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007159 break;
7160
7161 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007162 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007163 }
7164
7165 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007166 llvm::Value *NextPtr =
7167 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7168 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007169
John McCall7f416cc2015-09-08 08:05:57 +00007170 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007171}
7172
7173void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7174 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007175 for (auto &I : FI.arguments())
7176 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007177}
7178
7179namespace {
7180class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7181public:
7182 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7183 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007184
Craig Topper4f12f102014-03-12 06:41:41 +00007185 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007186 return 14;
7187 }
7188
7189 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007190 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007191};
7192} // end anonymous namespace
7193
Roman Divackyf02c9942014-02-24 18:46:27 +00007194bool
7195SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7196 llvm::Value *Address) const {
7197 // This is calculated from the LLVM and GCC tables and verified
7198 // against gcc output. AFAIK all ABIs use the same encoding.
7199
7200 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7201
7202 llvm::IntegerType *i8 = CGF.Int8Ty;
7203 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7204 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7205
7206 // 0-31: the 8-byte general-purpose registers
7207 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7208
7209 // 32-63: f0-31, the 4-byte floating-point registers
7210 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7211
7212 // Y = 64
7213 // PSR = 65
7214 // WIM = 66
7215 // TBR = 67
7216 // PC = 68
7217 // NPC = 69
7218 // FSR = 70
7219 // CSR = 71
7220 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007221
Roman Divackyf02c9942014-02-24 18:46:27 +00007222 // 72-87: d0-15, the 8-byte floating-point registers
7223 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7224
7225 return false;
7226}
7227
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007228
Robert Lytton0e076492013-08-13 09:43:10 +00007229//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007230// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007231//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007232
Robert Lytton0e076492013-08-13 09:43:10 +00007233namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007234
7235/// A SmallStringEnc instance is used to build up the TypeString by passing
7236/// it by reference between functions that append to it.
7237typedef llvm::SmallString<128> SmallStringEnc;
7238
7239/// TypeStringCache caches the meta encodings of Types.
7240///
7241/// The reason for caching TypeStrings is two fold:
7242/// 1. To cache a type's encoding for later uses;
7243/// 2. As a means to break recursive member type inclusion.
7244///
7245/// A cache Entry can have a Status of:
7246/// NonRecursive: The type encoding is not recursive;
7247/// Recursive: The type encoding is recursive;
7248/// Incomplete: An incomplete TypeString;
7249/// IncompleteUsed: An incomplete TypeString that has been used in a
7250/// Recursive type encoding.
7251///
7252/// A NonRecursive entry will have all of its sub-members expanded as fully
7253/// as possible. Whilst it may contain types which are recursive, the type
7254/// itself is not recursive and thus its encoding may be safely used whenever
7255/// the type is encountered.
7256///
7257/// A Recursive entry will have all of its sub-members expanded as fully as
7258/// possible. The type itself is recursive and it may contain other types which
7259/// are recursive. The Recursive encoding must not be used during the expansion
7260/// of a recursive type's recursive branch. For simplicity the code uses
7261/// IncompleteCount to reject all usage of Recursive encodings for member types.
7262///
7263/// An Incomplete entry is always a RecordType and only encodes its
7264/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7265/// are placed into the cache during type expansion as a means to identify and
7266/// handle recursive inclusion of types as sub-members. If there is recursion
7267/// the entry becomes IncompleteUsed.
7268///
7269/// During the expansion of a RecordType's members:
7270///
7271/// If the cache contains a NonRecursive encoding for the member type, the
7272/// cached encoding is used;
7273///
7274/// If the cache contains a Recursive encoding for the member type, the
7275/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7276///
7277/// If the member is a RecordType, an Incomplete encoding is placed into the
7278/// cache to break potential recursive inclusion of itself as a sub-member;
7279///
7280/// Once a member RecordType has been expanded, its temporary incomplete
7281/// entry is removed from the cache. If a Recursive encoding was swapped out
7282/// it is swapped back in;
7283///
7284/// If an incomplete entry is used to expand a sub-member, the incomplete
7285/// entry is marked as IncompleteUsed. The cache keeps count of how many
7286/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7287///
7288/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7289/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7290/// Else the member is part of a recursive type and thus the recursion has
7291/// been exited too soon for the encoding to be correct for the member.
7292///
7293class TypeStringCache {
7294 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7295 struct Entry {
7296 std::string Str; // The encoded TypeString for the type.
7297 enum Status State; // Information about the encoding in 'Str'.
7298 std::string Swapped; // A temporary place holder for a Recursive encoding
7299 // during the expansion of RecordType's members.
7300 };
7301 std::map<const IdentifierInfo *, struct Entry> Map;
7302 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7303 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7304public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007305 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007306 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7307 bool removeIncomplete(const IdentifierInfo *ID);
7308 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7309 bool IsRecursive);
7310 StringRef lookupStr(const IdentifierInfo *ID);
7311};
7312
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007313/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007314/// FieldEncoding is a helper for this ordering process.
7315class FieldEncoding {
7316 bool HasName;
7317 std::string Enc;
7318public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007319 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
7320 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007321 bool operator<(const FieldEncoding &rhs) const {
7322 if (HasName != rhs.HasName) return HasName;
7323 return Enc < rhs.Enc;
7324 }
7325};
7326
Robert Lytton7d1db152013-08-19 09:46:39 +00007327class XCoreABIInfo : public DefaultABIInfo {
7328public:
7329 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007330 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7331 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007332};
7333
Robert Lyttond21e2d72014-03-03 13:45:29 +00007334class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007335 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007336public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007337 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007338 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007339 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7340 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007341};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007342
Robert Lytton2d196952013-10-11 10:29:34 +00007343} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007344
James Y Knight29b5f082016-02-24 02:59:33 +00007345// TODO: this implementation is likely now redundant with the default
7346// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007347Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7348 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007349 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007350
Robert Lytton2d196952013-10-11 10:29:34 +00007351 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007352 CharUnits SlotSize = CharUnits::fromQuantity(4);
7353 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007354
Robert Lytton2d196952013-10-11 10:29:34 +00007355 // Handle the argument.
7356 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007357 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007358 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7359 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7360 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007361 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007362
7363 Address Val = Address::invalid();
7364 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007365 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007366 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007367 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007368 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007369 llvm_unreachable("Unsupported ABI kind for va_arg");
7370 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007371 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7372 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007373 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007374 case ABIArgInfo::Extend:
7375 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007376 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7377 ArgSize = CharUnits::fromQuantity(
7378 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007379 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007380 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007381 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007382 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7383 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7384 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007385 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007386 }
Robert Lytton2d196952013-10-11 10:29:34 +00007387
7388 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007389 if (!ArgSize.isZero()) {
7390 llvm::Value *APN =
7391 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7392 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007393 }
John McCall7f416cc2015-09-08 08:05:57 +00007394
Robert Lytton2d196952013-10-11 10:29:34 +00007395 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007396}
Robert Lytton0e076492013-08-13 09:43:10 +00007397
Robert Lytton844aeeb2014-05-02 09:33:20 +00007398/// During the expansion of a RecordType, an incomplete TypeString is placed
7399/// into the cache as a means to identify and break recursion.
7400/// If there is a Recursive encoding in the cache, it is swapped out and will
7401/// be reinserted by removeIncomplete().
7402/// All other types of encoding should have been used rather than arriving here.
7403void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7404 std::string StubEnc) {
7405 if (!ID)
7406 return;
7407 Entry &E = Map[ID];
7408 assert( (E.Str.empty() || E.State == Recursive) &&
7409 "Incorrectly use of addIncomplete");
7410 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7411 E.Swapped.swap(E.Str); // swap out the Recursive
7412 E.Str.swap(StubEnc);
7413 E.State = Incomplete;
7414 ++IncompleteCount;
7415}
7416
7417/// Once the RecordType has been expanded, the temporary incomplete TypeString
7418/// must be removed from the cache.
7419/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7420/// Returns true if the RecordType was defined recursively.
7421bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7422 if (!ID)
7423 return false;
7424 auto I = Map.find(ID);
7425 assert(I != Map.end() && "Entry not present");
7426 Entry &E = I->second;
7427 assert( (E.State == Incomplete ||
7428 E.State == IncompleteUsed) &&
7429 "Entry must be an incomplete type");
7430 bool IsRecursive = false;
7431 if (E.State == IncompleteUsed) {
7432 // We made use of our Incomplete encoding, thus we are recursive.
7433 IsRecursive = true;
7434 --IncompleteUsedCount;
7435 }
7436 if (E.Swapped.empty())
7437 Map.erase(I);
7438 else {
7439 // Swap the Recursive back.
7440 E.Swapped.swap(E.Str);
7441 E.Swapped.clear();
7442 E.State = Recursive;
7443 }
7444 --IncompleteCount;
7445 return IsRecursive;
7446}
7447
7448/// Add the encoded TypeString to the cache only if it is NonRecursive or
7449/// Recursive (viz: all sub-members were expanded as fully as possible).
7450void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7451 bool IsRecursive) {
7452 if (!ID || IncompleteUsedCount)
7453 return; // No key or it is is an incomplete sub-type so don't add.
7454 Entry &E = Map[ID];
7455 if (IsRecursive && !E.Str.empty()) {
7456 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7457 "This is not the same Recursive entry");
7458 // The parent container was not recursive after all, so we could have used
7459 // this Recursive sub-member entry after all, but we assumed the worse when
7460 // we started viz: IncompleteCount!=0.
7461 return;
7462 }
7463 assert(E.Str.empty() && "Entry already present");
7464 E.Str = Str.str();
7465 E.State = IsRecursive? Recursive : NonRecursive;
7466}
7467
7468/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7469/// are recursively expanding a type (IncompleteCount != 0) and the cached
7470/// encoding is Recursive, return an empty StringRef.
7471StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7472 if (!ID)
7473 return StringRef(); // We have no key.
7474 auto I = Map.find(ID);
7475 if (I == Map.end())
7476 return StringRef(); // We have no encoding.
7477 Entry &E = I->second;
7478 if (E.State == Recursive && IncompleteCount)
7479 return StringRef(); // We don't use Recursive encodings for member types.
7480
7481 if (E.State == Incomplete) {
7482 // The incomplete type is being used to break out of recursion.
7483 E.State = IncompleteUsed;
7484 ++IncompleteUsedCount;
7485 }
7486 return E.Str.c_str();
7487}
7488
7489/// The XCore ABI includes a type information section that communicates symbol
7490/// type information to the linker. The linker uses this information to verify
7491/// safety/correctness of things such as array bound and pointers et al.
7492/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7493/// This type information (TypeString) is emitted into meta data for all global
7494/// symbols: definitions, declarations, functions & variables.
7495///
7496/// The TypeString carries type, qualifier, name, size & value details.
7497/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007498/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007499/// The output is tested by test/CodeGen/xcore-stringtype.c.
7500///
7501static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7502 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7503
7504/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7505void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7506 CodeGen::CodeGenModule &CGM) const {
7507 SmallStringEnc Enc;
7508 if (getTypeString(Enc, D, CGM, TSC)) {
7509 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00007510 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
7511 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007512 llvm::NamedMDNode *MD =
7513 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7514 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7515 }
7516}
7517
Xiuli Pan972bea82016-03-24 03:57:17 +00007518//===----------------------------------------------------------------------===//
7519// SPIR ABI Implementation
7520//===----------------------------------------------------------------------===//
7521
7522namespace {
7523class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7524public:
7525 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7526 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7527 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7528 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007529 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00007530};
7531} // End anonymous namespace.
7532
7533/// Emit SPIR specific metadata: OpenCL and SPIR version.
7534void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7535 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007536 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7537 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7538 llvm::Module &M = CGM.getModule();
7539 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7540 // opencl.spir.version named metadata.
7541 llvm::Metadata *SPIRVerElts[] = {
7542 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7544 llvm::NamedMDNode *SPIRVerMD =
7545 M.getOrInsertNamedMetadata("opencl.spir.version");
7546 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007547 appendOpenCLVersionMD(CGM);
7548}
7549
7550static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM) {
7551 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7552 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7553 llvm::Module &M = CGM.getModule();
Xiuli Pan972bea82016-03-24 03:57:17 +00007554 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7555 // opencl.ocl.version named metadata node.
7556 llvm::Metadata *OCLVerElts[] = {
7557 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7558 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7559 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7560 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7561 llvm::NamedMDNode *OCLVerMD =
7562 M.getOrInsertNamedMetadata("opencl.ocl.version");
7563 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7564}
7565
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007566unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7567 return llvm::CallingConv::SPIR_KERNEL;
7568}
7569
Robert Lytton844aeeb2014-05-02 09:33:20 +00007570static bool appendType(SmallStringEnc &Enc, QualType QType,
7571 const CodeGen::CodeGenModule &CGM,
7572 TypeStringCache &TSC);
7573
7574/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007575/// Builds a SmallVector containing the encoded field types in declaration
7576/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007577static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7578 const RecordDecl *RD,
7579 const CodeGen::CodeGenModule &CGM,
7580 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007581 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007582 SmallStringEnc Enc;
7583 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007584 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007585 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007586 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007587 Enc += "b(";
7588 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007589 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007590 Enc += ':';
7591 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007592 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007593 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007594 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007595 Enc += ')';
7596 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007597 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007598 }
7599 return true;
7600}
7601
7602/// Appends structure and union types to Enc and adds encoding to cache.
7603/// Recursively calls appendType (via extractFieldType) for each field.
7604/// Union types have their fields ordered according to the ABI.
7605static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7606 const CodeGen::CodeGenModule &CGM,
7607 TypeStringCache &TSC, const IdentifierInfo *ID) {
7608 // Append the cached TypeString if we have one.
7609 StringRef TypeString = TSC.lookupStr(ID);
7610 if (!TypeString.empty()) {
7611 Enc += TypeString;
7612 return true;
7613 }
7614
7615 // Start to emit an incomplete TypeString.
7616 size_t Start = Enc.size();
7617 Enc += (RT->isUnionType()? 'u' : 's');
7618 Enc += '(';
7619 if (ID)
7620 Enc += ID->getName();
7621 Enc += "){";
7622
7623 // We collect all encoded fields and order as necessary.
7624 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007625 const RecordDecl *RD = RT->getDecl()->getDefinition();
7626 if (RD && !RD->field_empty()) {
7627 // An incomplete TypeString stub is placed in the cache for this RecordType
7628 // so that recursive calls to this RecordType will use it whilst building a
7629 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007630 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007631 std::string StubEnc(Enc.substr(Start).str());
7632 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7633 TSC.addIncomplete(ID, std::move(StubEnc));
7634 if (!extractFieldType(FE, RD, CGM, TSC)) {
7635 (void) TSC.removeIncomplete(ID);
7636 return false;
7637 }
7638 IsRecursive = TSC.removeIncomplete(ID);
7639 // The ABI requires unions to be sorted but not structures.
7640 // See FieldEncoding::operator< for sort algorithm.
7641 if (RT->isUnionType())
7642 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007643 // We can now complete the TypeString.
7644 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007645 for (unsigned I = 0; I != E; ++I) {
7646 if (I)
7647 Enc += ',';
7648 Enc += FE[I].str();
7649 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007650 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007651 Enc += '}';
7652 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7653 return true;
7654}
7655
7656/// Appends enum types to Enc and adds the encoding to the cache.
7657static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7658 TypeStringCache &TSC,
7659 const IdentifierInfo *ID) {
7660 // Append the cached TypeString if we have one.
7661 StringRef TypeString = TSC.lookupStr(ID);
7662 if (!TypeString.empty()) {
7663 Enc += TypeString;
7664 return true;
7665 }
7666
7667 size_t Start = Enc.size();
7668 Enc += "e(";
7669 if (ID)
7670 Enc += ID->getName();
7671 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007672
7673 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007674 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007675 SmallVector<FieldEncoding, 16> FE;
7676 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7677 ++I) {
7678 SmallStringEnc EnumEnc;
7679 EnumEnc += "m(";
7680 EnumEnc += I->getName();
7681 EnumEnc += "){";
7682 I->getInitVal().toString(EnumEnc);
7683 EnumEnc += '}';
7684 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7685 }
7686 std::sort(FE.begin(), FE.end());
7687 unsigned E = FE.size();
7688 for (unsigned I = 0; I != E; ++I) {
7689 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007690 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007691 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007692 }
7693 }
7694 Enc += '}';
7695 TSC.addIfComplete(ID, Enc.substr(Start), false);
7696 return true;
7697}
7698
7699/// Appends type's qualifier to Enc.
7700/// This is done prior to appending the type's encoding.
7701static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7702 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007703 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007704 int Lookup = 0;
7705 if (QT.isConstQualified())
7706 Lookup += 1<<0;
7707 if (QT.isRestrictQualified())
7708 Lookup += 1<<1;
7709 if (QT.isVolatileQualified())
7710 Lookup += 1<<2;
7711 Enc += Table[Lookup];
7712}
7713
7714/// Appends built-in types to Enc.
7715static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7716 const char *EncType;
7717 switch (BT->getKind()) {
7718 case BuiltinType::Void:
7719 EncType = "0";
7720 break;
7721 case BuiltinType::Bool:
7722 EncType = "b";
7723 break;
7724 case BuiltinType::Char_U:
7725 EncType = "uc";
7726 break;
7727 case BuiltinType::UChar:
7728 EncType = "uc";
7729 break;
7730 case BuiltinType::SChar:
7731 EncType = "sc";
7732 break;
7733 case BuiltinType::UShort:
7734 EncType = "us";
7735 break;
7736 case BuiltinType::Short:
7737 EncType = "ss";
7738 break;
7739 case BuiltinType::UInt:
7740 EncType = "ui";
7741 break;
7742 case BuiltinType::Int:
7743 EncType = "si";
7744 break;
7745 case BuiltinType::ULong:
7746 EncType = "ul";
7747 break;
7748 case BuiltinType::Long:
7749 EncType = "sl";
7750 break;
7751 case BuiltinType::ULongLong:
7752 EncType = "ull";
7753 break;
7754 case BuiltinType::LongLong:
7755 EncType = "sll";
7756 break;
7757 case BuiltinType::Float:
7758 EncType = "ft";
7759 break;
7760 case BuiltinType::Double:
7761 EncType = "d";
7762 break;
7763 case BuiltinType::LongDouble:
7764 EncType = "ld";
7765 break;
7766 default:
7767 return false;
7768 }
7769 Enc += EncType;
7770 return true;
7771}
7772
7773/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7774static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7775 const CodeGen::CodeGenModule &CGM,
7776 TypeStringCache &TSC) {
7777 Enc += "p(";
7778 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7779 return false;
7780 Enc += ')';
7781 return true;
7782}
7783
7784/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007785static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7786 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007787 const CodeGen::CodeGenModule &CGM,
7788 TypeStringCache &TSC, StringRef NoSizeEnc) {
7789 if (AT->getSizeModifier() != ArrayType::Normal)
7790 return false;
7791 Enc += "a(";
7792 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7793 CAT->getSize().toStringUnsigned(Enc);
7794 else
7795 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7796 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007797 // The Qualifiers should be attached to the type rather than the array.
7798 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007799 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7800 return false;
7801 Enc += ')';
7802 return true;
7803}
7804
7805/// Appends a function encoding to Enc, calling appendType for the return type
7806/// and the arguments.
7807static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7808 const CodeGen::CodeGenModule &CGM,
7809 TypeStringCache &TSC) {
7810 Enc += "f{";
7811 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7812 return false;
7813 Enc += "}(";
7814 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7815 // N.B. we are only interested in the adjusted param types.
7816 auto I = FPT->param_type_begin();
7817 auto E = FPT->param_type_end();
7818 if (I != E) {
7819 do {
7820 if (!appendType(Enc, *I, CGM, TSC))
7821 return false;
7822 ++I;
7823 if (I != E)
7824 Enc += ',';
7825 } while (I != E);
7826 if (FPT->isVariadic())
7827 Enc += ",va";
7828 } else {
7829 if (FPT->isVariadic())
7830 Enc += "va";
7831 else
7832 Enc += '0';
7833 }
7834 }
7835 Enc += ')';
7836 return true;
7837}
7838
7839/// Handles the type's qualifier before dispatching a call to handle specific
7840/// type encodings.
7841static bool appendType(SmallStringEnc &Enc, QualType QType,
7842 const CodeGen::CodeGenModule &CGM,
7843 TypeStringCache &TSC) {
7844
7845 QualType QT = QType.getCanonicalType();
7846
Robert Lytton6adb20f2014-06-05 09:06:21 +00007847 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7848 // The Qualifiers should be attached to the type rather than the array.
7849 // Thus we don't call appendQualifier() here.
7850 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7851
Robert Lytton844aeeb2014-05-02 09:33:20 +00007852 appendQualifier(Enc, QT);
7853
7854 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7855 return appendBuiltinType(Enc, BT);
7856
Robert Lytton844aeeb2014-05-02 09:33:20 +00007857 if (const PointerType *PT = QT->getAs<PointerType>())
7858 return appendPointerType(Enc, PT, CGM, TSC);
7859
7860 if (const EnumType *ET = QT->getAs<EnumType>())
7861 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7862
7863 if (const RecordType *RT = QT->getAsStructureType())
7864 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7865
7866 if (const RecordType *RT = QT->getAsUnionType())
7867 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7868
7869 if (const FunctionType *FT = QT->getAs<FunctionType>())
7870 return appendFunctionType(Enc, FT, CGM, TSC);
7871
7872 return false;
7873}
7874
7875static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7876 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7877 if (!D)
7878 return false;
7879
7880 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7881 if (FD->getLanguageLinkage() != CLanguageLinkage)
7882 return false;
7883 return appendType(Enc, FD->getType(), CGM, TSC);
7884 }
7885
7886 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7887 if (VD->getLanguageLinkage() != CLanguageLinkage)
7888 return false;
7889 QualType QT = VD->getType().getCanonicalType();
7890 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7891 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007892 // The Qualifiers should be attached to the type rather than the array.
7893 // Thus we don't call appendQualifier() here.
7894 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007895 }
7896 return appendType(Enc, QT, CGM, TSC);
7897 }
7898 return false;
7899}
7900
7901
Robert Lytton0e076492013-08-13 09:43:10 +00007902//===----------------------------------------------------------------------===//
7903// Driver code
7904//===----------------------------------------------------------------------===//
7905
Rafael Espindola9f834732014-09-19 01:54:22 +00007906const llvm::Triple &CodeGenModule::getTriple() const {
7907 return getTarget().getTriple();
7908}
7909
7910bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00007911 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00007912}
7913
Chris Lattner2b037972010-07-29 02:01:43 +00007914const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007915 if (TheTargetCodeGenInfo)
7916 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007917
Reid Kleckner9305fd12016-04-13 23:37:17 +00007918 // Helper to set the unique_ptr while still keeping the return value.
7919 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
7920 this->TheTargetCodeGenInfo.reset(P);
7921 return *P;
7922 };
7923
John McCallc8e01702013-04-16 22:48:15 +00007924 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007925 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007926 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007927 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007928
Derek Schuff09338a22012-09-06 17:37:28 +00007929 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007930 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007931 case llvm::Triple::mips:
7932 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007933 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00007934 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
7935 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007936
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007937 case llvm::Triple::mips64:
7938 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007939 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007940
Tim Northover25e8a672014-05-24 12:51:25 +00007941 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007942 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007943 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007944 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007945 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007946
Reid Kleckner9305fd12016-04-13 23:37:17 +00007947 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007948 }
7949
Dan Gohmanc2853072015-09-03 22:51:53 +00007950 case llvm::Triple::wasm32:
7951 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007952 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00007953
Daniel Dunbard59655c2009-09-12 00:59:49 +00007954 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007955 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007956 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007957 case llvm::Triple::thumbeb: {
7958 if (Triple.getOS() == llvm::Triple::Win32) {
7959 return SetCGInfo(
7960 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007961 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007962
Reid Kleckner9305fd12016-04-13 23:37:17 +00007963 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
7964 StringRef ABIStr = getTarget().getABI();
7965 if (ABIStr == "apcs-gnu")
7966 Kind = ARMABIInfo::APCS;
7967 else if (ABIStr == "aapcs16")
7968 Kind = ARMABIInfo::AAPCS16_VFP;
7969 else if (CodeGenOpts.FloatABI == "hard" ||
7970 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007971 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00007972 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00007973 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00007974 Kind = ARMABIInfo::AAPCS_VFP;
7975
7976 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
7977 }
7978
John McCallea8d8bb2010-03-11 00:10:12 +00007979 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00007980 return SetCGInfo(
7981 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007982 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007983 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007984 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007985 if (getTarget().getABI() == "elfv2")
7986 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007987 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007988
Reid Kleckner9305fd12016-04-13 23:37:17 +00007989 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007990 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00007991 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007992 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007993 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007994 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007995 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007996 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007997 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007998
Reid Kleckner9305fd12016-04-13 23:37:17 +00007999 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008000 }
John McCallea8d8bb2010-03-11 00:10:12 +00008001
Peter Collingbournec947aae2012-05-20 23:28:41 +00008002 case llvm::Triple::nvptx:
8003 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008004 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008005
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008006 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008007 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008008
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008009 case llvm::Triple::systemz: {
8010 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008011 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008012 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008013
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008014 case llvm::Triple::tce:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008015 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008016
Eli Friedman33465822011-07-08 23:31:17 +00008017 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008018 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008019 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008020 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008021 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008022
John McCall1fe2a8c2013-06-18 02:46:29 +00008023 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008024 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8025 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8026 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008027 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008028 return SetCGInfo(new X86_32TargetCodeGenInfo(
8029 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8030 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8031 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008032 }
Eli Friedman33465822011-07-08 23:31:17 +00008033 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008034
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008035 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008036 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008037 X86AVXABILevel AVXLevel =
8038 (ABI == "avx512"
8039 ? X86AVXABILevel::AVX512
8040 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008041
Chris Lattner04dc9572010-08-31 16:44:54 +00008042 switch (Triple.getOS()) {
8043 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008044 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008045 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008046 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008047 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008048 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008049 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008050 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008051 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008052 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008053 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008054 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008055 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008056 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008057 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008058 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008059 case llvm::Triple::sparc:
8060 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008061 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008062 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008063 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008064 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008065 case llvm::Triple::spir:
8066 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008067 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008068 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008069}