blob: 458b9a6025bfe3ced96f80c954865fae089f60a6 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9// These classes wrap the information about a call or function
10// definition used to handle ABI compliancy.
11//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000014#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000015#include "ABIInfo.h"
Yaxun Liuc2a87a02017-10-14 12:23:50 +000016#include "CGBlocks.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"
Richard Trieu63688182018-12-11 03:18:39 +000021#include "clang/Basic/CodeGenOptions.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000022#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000023#include "clang/CodeGen/SwiftCallingConv.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000024#include "llvm/ADT/StringExtras.h"
Coby Tayree7b49dc92017-08-24 09:07:34 +000025#include "llvm/ADT/StringSwitch.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000026#include "llvm/ADT/Triple.h"
Yaxun Liu98f0c432017-10-14 12:51:52 +000027#include "llvm/ADT/Twine.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000030#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000031#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000032
Anton Korobeynikov244360d2009-06-05 22:08:42 +000033using namespace clang;
34using namespace CodeGen;
35
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000036// Helper for coercing an aggregate argument or return value into an integer
37// array of the same size (including padding) and alignment. This alternate
38// coercion happens only for the RenderScript ABI and can be removed after
39// runtimes that rely on it are no longer supported.
40//
41// RenderScript assumes that the size of the argument / return value in the IR
42// is the same as the size of the corresponding qualified type. This helper
43// coerces the aggregate type into an array of the same size (including
44// padding). This coercion is used in lieu of expansion of struct members or
45// other canonical coercions that return a coerced-type of larger size.
46//
47// Ty - The argument / return value type
48// Context - The associated ASTContext
49// LLVMContext - The associated LLVMContext
50static ABIArgInfo coerceToIntArray(QualType Ty,
51 ASTContext &Context,
52 llvm::LLVMContext &LLVMContext) {
53 // Alignment and Size are measured in bits.
54 const uint64_t Size = Context.getTypeSize(Ty);
55 const uint64_t Alignment = Context.getTypeAlign(Ty);
56 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
57 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
58 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
59}
60
John McCall943fae92010-05-27 06:19:26 +000061static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
62 llvm::Value *Array,
63 llvm::Value *Value,
64 unsigned FirstIndex,
65 unsigned LastIndex) {
66 // Alternatively, we could emit this as a loop in the source.
67 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000068 llvm::Value *Cell =
69 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000070 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000071 }
72}
73
John McCalla1dee5302010-08-22 10:59:02 +000074static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000075 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000076 T->isMemberFunctionPointerType();
77}
78
John McCall7f416cc2015-09-08 08:05:57 +000079ABIArgInfo
80ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
81 llvm::Type *Padding) const {
82 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
83 ByRef, Realign, Padding);
84}
85
86ABIArgInfo
87ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
88 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
89 /*ByRef*/ false, Realign);
90}
91
Charles Davisc7d5c942015-09-17 20:55:33 +000092Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
93 QualType Ty) const {
94 return Address::invalid();
95}
96
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000097ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000098
John McCall12f23522016-04-04 18:33:08 +000099/// Does the given lowering require more than the given number of
100/// registers when expanded?
101///
102/// This is intended to be the basis of a reasonable basic implementation
103/// of should{Pass,Return}IndirectlyForSwift.
104///
105/// For most targets, a limit of four total registers is reasonable; this
106/// limits the amount of code required in order to move around the value
107/// in case it wasn't produced immediately prior to the call by the caller
108/// (or wasn't produced in exactly the right registers) or isn't used
109/// immediately within the callee. But some targets may need to further
110/// limit the register count due to an inability to support that many
111/// return registers.
112static bool occupiesMoreThan(CodeGenTypes &cgt,
113 ArrayRef<llvm::Type*> scalarTypes,
114 unsigned maxAllRegisters) {
115 unsigned intCount = 0, fpCount = 0;
116 for (llvm::Type *type : scalarTypes) {
117 if (type->isPointerTy()) {
118 intCount++;
119 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
120 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
121 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
122 } else {
123 assert(type->isVectorTy() || type->isFloatingPointTy());
124 fpCount++;
125 }
126 }
127
128 return (intCount + fpCount > maxAllRegisters);
129}
130
131bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
132 llvm::Type *eltTy,
133 unsigned numElts) const {
134 // The default implementation of this assumes that the target guarantees
135 // 128-bit SIMD support but nothing more.
136 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
137}
138
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000139static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000140 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000141 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Akira Hatanakad791e922018-03-19 17:38:40 +0000142 if (!RD) {
143 if (!RT->getDecl()->canPassInRegisters())
144 return CGCXXABI::RAA_Indirect;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000145 return CGCXXABI::RAA_Default;
Akira Hatanakad791e922018-03-19 17:38:40 +0000146 }
Mark Lacey3825e832013-10-06 01:33:34 +0000147 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000148}
149
150static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000151 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000152 const RecordType *RT = T->getAs<RecordType>();
153 if (!RT)
154 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000155 return getRecordArgABI(RT, CXXABI);
156}
157
Akira Hatanakad791e922018-03-19 17:38:40 +0000158static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
159 const ABIInfo &Info) {
160 QualType Ty = FI.getReturnType();
161
162 if (const auto *RT = Ty->getAs<RecordType>())
163 if (!isa<CXXRecordDecl>(RT->getDecl()) &&
164 !RT->getDecl()->canPassInRegisters()) {
165 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
166 return true;
167 }
168
169 return CXXABI.classifyReturnType(FI);
170}
171
Reid Klecknerb1be6832014-11-15 01:41:41 +0000172/// Pass transparent unions as if they were the type of the first element. Sema
173/// should ensure that all elements of the union have the same "machine type".
174static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
175 if (const RecordType *UT = Ty->getAsUnionType()) {
176 const RecordDecl *UD = UT->getDecl();
177 if (UD->hasAttr<TransparentUnionAttr>()) {
178 assert(!UD->field_empty() && "sema created an empty transparent union");
179 return UD->field_begin()->getType();
180 }
181 }
182 return Ty;
183}
184
Mark Lacey3825e832013-10-06 01:33:34 +0000185CGCXXABI &ABIInfo::getCXXABI() const {
186 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000187}
188
Chris Lattner2b037972010-07-29 02:01:43 +0000189ASTContext &ABIInfo::getContext() const {
190 return CGT.getContext();
191}
192
193llvm::LLVMContext &ABIInfo::getVMContext() const {
194 return CGT.getLLVMContext();
195}
196
Micah Villmowdd31ca12012-10-08 16:25:52 +0000197const llvm::DataLayout &ABIInfo::getDataLayout() const {
198 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000199}
200
John McCallc8e01702013-04-16 22:48:15 +0000201const TargetInfo &ABIInfo::getTarget() const {
202 return CGT.getTarget();
203}
Chris Lattner2b037972010-07-29 02:01:43 +0000204
Richard Smithf667ad52017-08-26 01:04:35 +0000205const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
206 return CGT.getCodeGenOpts();
207}
208
209bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000210
Reid Klecknere9f6a712014-10-31 17:10:41 +0000211bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
212 return false;
213}
214
215bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
216 uint64_t Members) const {
217 return false;
218}
219
Yaron Kerencdae9412016-01-29 19:38:18 +0000220LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000221 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000222 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000223 switch (TheKind) {
224 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000225 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000226 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000227 Ty->print(OS);
228 else
229 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000230 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000231 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000232 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000233 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000234 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000235 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000236 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000237 case InAlloca:
238 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
239 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000240 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000241 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000242 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000243 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000244 break;
245 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000246 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000247 break;
John McCallf26e73d2016-03-11 04:30:43 +0000248 case CoerceAndExpand:
249 OS << "CoerceAndExpand Type=";
250 getCoerceAndExpandType()->print(OS);
251 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000252 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000253 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000254}
255
Petar Jovanovic402257b2015-12-04 00:26:47 +0000256// Dynamically round a pointer up to a multiple of the given alignment.
257static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
258 llvm::Value *Ptr,
259 CharUnits Align) {
260 llvm::Value *PtrAsInt = Ptr;
261 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
262 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
263 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
264 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
265 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
266 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
267 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
268 Ptr->getType(),
269 Ptr->getName() + ".aligned");
270 return PtrAsInt;
271}
272
John McCall7f416cc2015-09-08 08:05:57 +0000273/// Emit va_arg for a platform using the common void* representation,
274/// where arguments are simply emitted in an array of slots on the stack.
275///
276/// This version implements the core direct-value passing rules.
277///
278/// \param SlotSize - The size and alignment of a stack slot.
279/// Each argument will be allocated to a multiple of this number of
280/// slots, and all the slots will be aligned to this value.
281/// \param AllowHigherAlign - The slot alignment is not a cap;
282/// an argument type with an alignment greater than the slot size
283/// will be emitted on a higher-alignment address, potentially
284/// leaving one or more empty slots behind as padding. If this
285/// is false, the returned address might be less-aligned than
286/// DirectAlign.
287static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
288 Address VAListAddr,
289 llvm::Type *DirectTy,
290 CharUnits DirectSize,
291 CharUnits DirectAlign,
292 CharUnits SlotSize,
293 bool AllowHigherAlign) {
294 // Cast the element type to i8* if necessary. Some platforms define
295 // va_list as a struct containing an i8* instead of just an i8*.
296 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
297 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
298
299 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
300
301 // If the CC aligns values higher than the slot size, do so if needed.
302 Address Addr = Address::invalid();
303 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000304 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
305 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000306 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000307 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000308 }
309
310 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000311 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
James Y Knight3d2df5a2019-02-05 19:01:33 +0000312 Address NextPtr =
313 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
314 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
John McCall7f416cc2015-09-08 08:05:57 +0000315
316 // If the argument is smaller than a slot, and this is a big-endian
317 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000318 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
319 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000320 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
321 }
322
323 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
324 return Addr;
325}
326
327/// Emit va_arg for a platform using the common void* representation,
328/// where arguments are simply emitted in an array of slots on the stack.
329///
330/// \param IsIndirect - Values of this type are passed indirectly.
331/// \param ValueInfo - The size and alignment of this type, generally
332/// computed with getContext().getTypeInfoInChars(ValueTy).
333/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
334/// Each argument will be allocated to a multiple of this number of
335/// slots, and all the slots will be aligned to this value.
336/// \param AllowHigherAlign - The slot alignment is not a cap;
337/// an argument type with an alignment greater than the slot size
338/// will be emitted on a higher-alignment address, potentially
339/// leaving one or more empty slots behind as padding.
340static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
341 QualType ValueTy, bool IsIndirect,
342 std::pair<CharUnits, CharUnits> ValueInfo,
343 CharUnits SlotSizeAndAlign,
344 bool AllowHigherAlign) {
345 // The size and alignment of the value that was passed directly.
346 CharUnits DirectSize, DirectAlign;
347 if (IsIndirect) {
348 DirectSize = CGF.getPointerSize();
349 DirectAlign = CGF.getPointerAlign();
350 } else {
351 DirectSize = ValueInfo.first;
352 DirectAlign = ValueInfo.second;
353 }
354
355 // Cast the address we've calculated to the right type.
356 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
357 if (IsIndirect)
358 DirectTy = DirectTy->getPointerTo(0);
359
360 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
361 DirectSize, DirectAlign,
362 SlotSizeAndAlign,
363 AllowHigherAlign);
364
365 if (IsIndirect) {
366 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
367 }
368
369 return Addr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000370
John McCall7f416cc2015-09-08 08:05:57 +0000371}
372
373static Address emitMergePHI(CodeGenFunction &CGF,
374 Address Addr1, llvm::BasicBlock *Block1,
375 Address Addr2, llvm::BasicBlock *Block2,
376 const llvm::Twine &Name = "") {
377 assert(Addr1.getType() == Addr2.getType());
378 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
379 PHI->addIncoming(Addr1.getPointer(), Block1);
380 PHI->addIncoming(Addr2.getPointer(), Block2);
381 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
382 return Address(PHI, Align);
383}
384
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000385TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
386
John McCall3480ef22011-08-30 01:42:09 +0000387// If someone can figure out a general rule for this, that would be great.
388// It's probably just doomed to be platform-dependent, though.
389unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
390 // Verified for:
391 // x86-64 FreeBSD, Linux, Darwin
392 // x86-32 FreeBSD, Linux, Darwin
393 // PowerPC Linux, Darwin
394 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000395 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000396 return 32;
397}
398
John McCalla729c622012-02-17 03:33:10 +0000399bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
400 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000401 // The following conventions are known to require this to be false:
402 // x86_stdcall
403 // MIPS
404 // For everything else, we just prefer false unless we opt out.
405 return false;
406}
407
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000408void
409TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
410 llvm::SmallString<24> &Opt) const {
411 // This assumes the user is passing a library name like "rt" instead of a
412 // filename like "librt.a/so", and that they don't care whether it's static or
413 // dynamic.
414 Opt = "-l";
415 Opt += Lib;
416}
417
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000418unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000419 // OpenCL kernels are called via an explicit runtime API with arguments
420 // set with clSetKernelArg(), not as normal sub-functions.
421 // Return SPIR_KERNEL by default as the kernel calling convention to
422 // ensure the fingerprint is fixed such way that each OpenCL argument
423 // gets one matching argument in the produced kernel function argument
424 // list to enable feasible implementation of clSetKernelArg() with
425 // aggregates etc. In case we would use the default C calling conv here,
426 // clSetKernelArg() might break depending on the target-specific
427 // conventions; different targets might split structs passed as values
428 // to multiple function arguments etc.
429 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000430}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000431
Yaxun Liu402804b2016-12-15 08:09:08 +0000432llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
433 llvm::PointerType *T, QualType QT) const {
434 return llvm::ConstantPointerNull::get(T);
435}
436
Alexander Richardson6d989432017-10-15 18:48:14 +0000437LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
438 const VarDecl *D) const {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000439 assert(!CGM.getLangOpts().OpenCL &&
440 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
441 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +0000442 return D ? D->getType().getAddressSpace() : LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000443}
444
Yaxun Liu402804b2016-12-15 08:09:08 +0000445llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Alexander Richardson6d989432017-10-15 18:48:14 +0000446 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
447 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000448 // Since target may map different address spaces in AST to the same address
449 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000450 if (auto *C = dyn_cast<llvm::Constant>(Src))
451 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Vyacheslav Zakharinde811d12019-07-10 17:10:05 +0000452 // Try to preserve the source's name to make IR more readable.
453 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
454 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
Yaxun Liu402804b2016-12-15 08:09:08 +0000455}
456
Yaxun Liucbf647c2017-07-08 13:24:52 +0000457llvm::Constant *
458TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
Alexander Richardson6d989432017-10-15 18:48:14 +0000459 LangAS SrcAddr, LangAS DestAddr,
Yaxun Liucbf647c2017-07-08 13:24:52 +0000460 llvm::Type *DestTy) const {
461 // Since target may map different address spaces in AST to the same address
462 // space, an address space conversion may end up as a bitcast.
463 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
464}
465
Yaxun Liu39195062017-08-04 18:16:31 +0000466llvm::SyncScope::ID
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +0000467TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
468 SyncScope Scope,
469 llvm::AtomicOrdering Ordering,
470 llvm::LLVMContext &Ctx) const {
471 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
Yaxun Liu39195062017-08-04 18:16:31 +0000472}
473
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000474static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000475
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000476/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000477/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000478static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
479 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000480 if (FD->isUnnamedBitfield())
481 return true;
482
483 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000484
Eli Friedman0b3f2012011-11-18 03:47:20 +0000485 // Constant arrays of empty records count as empty, strip them off.
486 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000487 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000488 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
489 if (AT->getSize() == 0)
490 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000491 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000492 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000493
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000494 const RecordType *RT = FT->getAs<RecordType>();
495 if (!RT)
496 return false;
497
498 // C++ record fields are never empty, at least in the Itanium ABI.
499 //
500 // FIXME: We should use a predicate for whether this behavior is true in the
501 // current ABI.
502 if (isa<CXXRecordDecl>(RT->getDecl()))
503 return false;
504
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000505 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000506}
507
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000508/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000509/// fields. Note that a structure with a flexible array member is not
510/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000511static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000512 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000513 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000514 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000515 const RecordDecl *RD = RT->getDecl();
516 if (RD->hasFlexibleArrayMember())
517 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000518
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000519 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000520 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000521 for (const auto &I : CXXRD->bases())
522 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000523 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000524
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000525 for (const auto *I : RD->fields())
526 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000527 return false;
528 return true;
529}
530
531/// isSingleElementStruct - Determine if a structure is a "single
532/// element struct", i.e. it has exactly one non-empty field or
533/// exactly one field which is itself a single element
534/// struct. Structures with flexible array members are never
535/// considered single element structs.
536///
537/// \return The field declaration for the single non-empty field, if
538/// it exists.
539static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000540 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000541 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000542 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000543
544 const RecordDecl *RD = RT->getDecl();
545 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000546 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000547
Craig Topper8a13c412014-05-21 05:09:00 +0000548 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000549
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000550 // If this is a C++ record, check the bases first.
551 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000552 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000553 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000554 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000555 continue;
556
557 // If we already found an element then this isn't a single-element struct.
558 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000559 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000560
561 // If this is non-empty and not a single element struct, the composite
562 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000563 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000564 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000565 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000566 }
567 }
568
569 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000570 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000571 QualType FT = FD->getType();
572
573 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000574 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000575 continue;
576
577 // If we already found an element then this isn't a single-element
578 // struct.
579 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000580 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000581
582 // Treat single element arrays as the element.
583 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
584 if (AT->getSize().getZExtValue() != 1)
585 break;
586 FT = AT->getElementType();
587 }
588
John McCalla1dee5302010-08-22 10:59:02 +0000589 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000590 Found = FT.getTypePtr();
591 } else {
592 Found = isSingleElementStruct(FT, Context);
593 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000594 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000595 }
596 }
597
Eli Friedmanee945342011-11-18 01:25:50 +0000598 // We don't consider a struct a single-element struct if it has
599 // padding beyond the element type.
600 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000601 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000602
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000603 return Found;
604}
605
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000606namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000607Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
608 const ABIArgInfo &AI) {
609 // This default implementation defers to the llvm backend's va_arg
610 // instruction. It can handle only passing arguments directly
611 // (typically only handled in the backend for primitive types), or
612 // aggregates passed indirectly by pointer (NOTE: if the "byval"
613 // flag has ABI impact in the callee, this implementation cannot
614 // work.)
615
616 // Only a few cases are covered here at the moment -- those needed
617 // by the default abi.
618 llvm::Value *Val;
619
620 if (AI.isIndirect()) {
621 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000622 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000623 assert(
624 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000625 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000626
627 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
628 CharUnits TyAlignForABI = TyInfo.second;
629
630 llvm::Type *BaseTy =
631 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
632 llvm::Value *Addr =
633 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
634 return Address(Addr, TyAlignForABI);
635 } else {
636 assert((AI.isDirect() || AI.isExtend()) &&
637 "Unexpected ArgInfo Kind in generic VAArg emitter!");
638
639 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000640 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000641 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000642 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000643 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000644 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000645 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000646 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000647
648 Address Temp = CGF.CreateMemTemp(Ty, "varet");
649 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
650 CGF.Builder.CreateStore(Val, Temp);
651 return Temp;
652 }
653}
654
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000655/// DefaultABIInfo - The default implementation for ABI specific
656/// details. This implementation provides information which results in
657/// self-consistent and sensible LLVM IR generation, but does not
658/// conform to any particular ABI.
659class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000660public:
661 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000662
Chris Lattner458b2aa2010-07-29 02:16:43 +0000663 ABIArgInfo classifyReturnType(QualType RetTy) const;
664 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000665
Craig Topper4f12f102014-03-12 06:41:41 +0000666 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000667 if (!getCXXABI().classifyReturnType(FI))
668 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000669 for (auto &I : FI.arguments())
670 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000671 }
672
John McCall7f416cc2015-09-08 08:05:57 +0000673 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000674 QualType Ty) const override {
675 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
676 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000677};
678
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000679class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
680public:
Chris Lattner2b037972010-07-29 02:01:43 +0000681 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
682 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000683};
684
Chris Lattner458b2aa2010-07-29 02:16:43 +0000685ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000686 Ty = useFirstFieldIfTransparentUnion(Ty);
687
688 if (isAggregateTypeForABI(Ty)) {
689 // Records with non-trivial destructors/copy-constructors should not be
690 // passed by value.
691 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000692 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000693
John McCall7f416cc2015-09-08 08:05:57 +0000694 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000695 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000696
Chris Lattner9723d6c2010-03-11 18:19:55 +0000697 // Treat an enum type as its underlying type.
698 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
699 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000700
Alex Bradburye41a5e22018-01-12 20:08:16 +0000701 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
702 : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000703}
704
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000705ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
706 if (RetTy->isVoidType())
707 return ABIArgInfo::getIgnore();
708
709 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000710 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000711
712 // Treat an enum type as its underlying type.
713 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
714 RetTy = EnumTy->getDecl()->getIntegerType();
715
Alex Bradburye41a5e22018-01-12 20:08:16 +0000716 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
717 : ABIArgInfo::getDirect());
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000718}
719
Derek Schuff09338a22012-09-06 17:37:28 +0000720//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000721// WebAssembly ABI Implementation
722//
723// This is a very simple ABI that relies a lot on DefaultABIInfo.
724//===----------------------------------------------------------------------===//
725
Daniel Dunbara39bab32019-01-03 23:24:50 +0000726class WebAssemblyABIInfo final : public SwiftABIInfo {
727 DefaultABIInfo defaultInfo;
728
Dan Gohmanc2853072015-09-03 22:51:53 +0000729public:
730 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
Daniel Dunbara39bab32019-01-03 23:24:50 +0000731 : SwiftABIInfo(CGT), defaultInfo(CGT) {}
Dan Gohmanc2853072015-09-03 22:51:53 +0000732
733private:
734 ABIArgInfo classifyReturnType(QualType RetTy) const;
735 ABIArgInfo classifyArgumentType(QualType Ty) const;
736
737 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000738 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000739 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000740 void computeInfo(CGFunctionInfo &FI) const override {
741 if (!getCXXABI().classifyReturnType(FI))
742 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
743 for (auto &Arg : FI.arguments())
744 Arg.info = classifyArgumentType(Arg.type);
745 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000746
747 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
748 QualType Ty) const override;
Daniel Dunbara39bab32019-01-03 23:24:50 +0000749
750 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
751 bool asReturnValue) const override {
752 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
753 }
754
755 bool isSwiftErrorInRegister() const override {
756 return false;
757 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000758};
759
760class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
761public:
762 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
763 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
Sam Clegg6fd7d682018-06-25 18:47:32 +0000764
765 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
766 CodeGen::CodeGenModule &CGM) const override {
Dan Gohmanb4323692019-01-24 21:08:30 +0000767 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
768 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
769 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
770 llvm::Function *Fn = cast<llvm::Function>(GV);
771 llvm::AttrBuilder B;
Dan Gohmancae84592019-02-01 22:25:23 +0000772 B.addAttribute("wasm-import-module", Attr->getImportModule());
773 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
774 }
775 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
776 llvm::Function *Fn = cast<llvm::Function>(GV);
777 llvm::AttrBuilder B;
778 B.addAttribute("wasm-import-name", Attr->getImportName());
Dan Gohmanb4323692019-01-24 21:08:30 +0000779 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
780 }
781 }
782
Sam Clegg6fd7d682018-06-25 18:47:32 +0000783 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
784 llvm::Function *Fn = cast<llvm::Function>(GV);
785 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
786 Fn->addFnAttr("no-prototype");
787 }
788 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000789};
790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000791/// Classify argument of given type \p Ty.
Dan Gohmanc2853072015-09-03 22:51:53 +0000792ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
793 Ty = useFirstFieldIfTransparentUnion(Ty);
794
795 if (isAggregateTypeForABI(Ty)) {
796 // Records with non-trivial destructors/copy-constructors should not be
797 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000798 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000799 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000800 // Ignore empty structs/unions.
801 if (isEmptyRecord(getContext(), Ty, true))
802 return ABIArgInfo::getIgnore();
803 // Lower single-element structs to just pass a regular value. TODO: We
804 // could do reasonable-size multiple-element structs too, using getExpand(),
805 // though watch out for things like bitfields.
806 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
807 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000808 }
809
810 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000811 return defaultInfo.classifyArgumentType(Ty);
Dan Gohmanc2853072015-09-03 22:51:53 +0000812}
813
814ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
815 if (isAggregateTypeForABI(RetTy)) {
816 // Records with non-trivial destructors/copy-constructors should not be
817 // returned by value.
818 if (!getRecordArgABI(RetTy, getCXXABI())) {
819 // Ignore empty structs/unions.
820 if (isEmptyRecord(getContext(), RetTy, true))
821 return ABIArgInfo::getIgnore();
822 // Lower single-element structs to just return a regular value. TODO: We
823 // could do reasonable-size multiple-element structs too, using
824 // ABIArgInfo::getDirect().
825 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
826 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
827 }
828 }
829
830 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000831 return defaultInfo.classifyReturnType(RetTy);
Dan Gohmanc2853072015-09-03 22:51:53 +0000832}
833
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000834Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
835 QualType Ty) const {
836 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
837 getContext().getTypeInfoInChars(Ty),
838 CharUnits::fromQuantity(4),
839 /*AllowHigherAlign=*/ true);
840}
841
Dan Gohmanc2853072015-09-03 22:51:53 +0000842//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000843// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000844//
845// This is a simplified version of the x86_32 ABI. Arguments and return values
846// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000847//===----------------------------------------------------------------------===//
848
849class PNaClABIInfo : public ABIInfo {
850 public:
851 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
852
853 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000854 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000855
Craig Topper4f12f102014-03-12 06:41:41 +0000856 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000857 Address EmitVAArg(CodeGenFunction &CGF,
858 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000859};
860
861class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
862 public:
863 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
864 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
865};
866
867void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000868 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000869 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
870
Reid Kleckner40ca9132014-05-13 22:05:45 +0000871 for (auto &I : FI.arguments())
872 I.info = classifyArgumentType(I.type);
873}
Derek Schuff09338a22012-09-06 17:37:28 +0000874
John McCall7f416cc2015-09-08 08:05:57 +0000875Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
876 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000877 // The PNaCL ABI is a bit odd, in that varargs don't use normal
878 // function classification. Structs get passed directly for varargs
879 // functions, through a rewriting transform in
880 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
881 // this target to actually support a va_arg instructions with an
882 // aggregate type, unlike other targets.
883 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000884}
885
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000886/// Classify argument of given type \p Ty.
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000887ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000888 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000889 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000890 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
891 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000892 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
893 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000894 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000895 } else if (Ty->isFloatingType()) {
896 // Floating-point types don't go inreg.
897 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000898 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000899
Alex Bradburye41a5e22018-01-12 20:08:16 +0000900 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
901 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000902}
903
904ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
905 if (RetTy->isVoidType())
906 return ABIArgInfo::getIgnore();
907
Eli Benderskye20dad62013-04-04 22:49:35 +0000908 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000909 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000910 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000911
912 // Treat an enum type as its underlying type.
913 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
914 RetTy = EnumTy->getDecl()->getIntegerType();
915
Alex Bradburye41a5e22018-01-12 20:08:16 +0000916 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
917 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000918}
919
Hans Wennborgd874c052019-06-19 11:34:08 +0000920/// IsX86_MMXType - Return true if this is an MMX type.
921bool IsX86_MMXType(llvm::Type *IRType) {
922 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
923 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
924 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
925 IRType->getScalarSizeInBits() != 64;
926}
927
Jay Foad7c57be32011-07-11 09:56:20 +0000928static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000929 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000930 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000931 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
932 .Cases("y", "&y", "^Ym", true)
933 .Default(false);
934 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000935 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
936 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000937 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000938 }
939
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000940 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000941 }
942
943 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000944 return Ty;
945}
946
Reid Kleckner80944df2014-10-31 22:00:51 +0000947/// Returns true if this type can be passed in SSE registers with the
948/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
949static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
950 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000951 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
952 if (BT->getKind() == BuiltinType::LongDouble) {
953 if (&Context.getTargetInfo().getLongDoubleFormat() ==
954 &llvm::APFloat::x87DoubleExtended())
955 return false;
956 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000957 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000958 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000959 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
960 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
961 // registers specially.
962 unsigned VecSize = Context.getTypeSize(VT);
963 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
964 return true;
965 }
966 return false;
967}
968
969/// Returns true if this aggregate is small enough to be passed in SSE registers
970/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
971static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
972 return NumMembers <= 4;
973}
974
Erich Keane521ed962017-01-05 00:20:51 +0000975/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
976static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
977 auto AI = ABIArgInfo::getDirect(T);
978 AI.setInReg(true);
979 AI.setCanBeFlattened(false);
980 return AI;
981}
982
Chris Lattner0cf24192010-06-28 20:05:43 +0000983//===----------------------------------------------------------------------===//
984// X86-32 ABI Implementation
985//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000986
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000987/// Similar to llvm::CCState, but for Clang.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000988struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000989 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000990
991 unsigned CC;
992 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000993 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000994};
995
Erich Keane521ed962017-01-05 00:20:51 +0000996enum {
997 // Vectorcall only allows the first 6 parameters to be passed in registers.
998 VectorcallMaxParamNumAsReg = 6
999};
1000
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001001/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001002class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001003 enum Class {
1004 Integer,
1005 Float
1006 };
1007
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001008 static const unsigned MinABIStackAlignInBytes = 4;
1009
David Chisnallde3a0692009-08-17 23:08:21 +00001010 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +00001011 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001012 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001013 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +00001014 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001015 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001016
1017 static bool isRegisterSize(unsigned Size) {
1018 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1019 }
1020
Reid Kleckner80944df2014-10-31 22:00:51 +00001021 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1022 // FIXME: Assumes vectorcall is in use.
1023 return isX86VectorTypeForVectorCall(getContext(), Ty);
1024 }
1025
1026 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1027 uint64_t NumMembers) const override {
1028 // FIXME: Assumes vectorcall is in use.
1029 return isX86VectorCallAggregateSmallEnough(NumMembers);
1030 }
1031
Reid Kleckner40ca9132014-05-13 22:05:45 +00001032 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001033
Daniel Dunbar557893d2010-04-21 19:10:51 +00001034 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1035 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +00001036 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1037
John McCall7f416cc2015-09-08 08:05:57 +00001038 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +00001039
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001040 /// Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001041 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001042
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001043 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +00001044 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001045 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +00001046
Fangrui Song6907ce22018-07-30 19:24:48 +00001047 /// Updates the number of available free registers, returns
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001048 /// true if any registers were allocated.
1049 bool updateFreeRegs(QualType Ty, CCState &State) const;
1050
1051 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1052 bool &NeedsPadding) const;
1053 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001054
Reid Kleckner04046052016-05-02 17:41:07 +00001055 bool canExpandIndirectArgument(QualType Ty) const;
1056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001057 /// Rewrite the function info so that all memory arguments use
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001058 /// inalloca.
1059 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1060
1061 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001062 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001063 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001064 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1065 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001066
Rafael Espindola75419dc2012-07-23 23:30:29 +00001067public:
1068
Craig Topper4f12f102014-03-12 06:41:41 +00001069 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001070 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1071 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001072
Michael Kupersteindc745202015-10-19 07:52:25 +00001073 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1074 bool RetSmallStructInRegABI, bool Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001075 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001076 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Fangrui Song6907ce22018-07-30 19:24:48 +00001077 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001078 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001079 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001080 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Hans Wennborgd874c052019-06-19 11:34:08 +00001081 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001082
John McCall56331e22018-01-07 06:28:49 +00001083 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001084 bool asReturnValue) const override {
1085 // LLVM's x86-32 lowering currently only assigns up to three
1086 // integer registers and three fp registers. Oddly, it'll use up to
1087 // four vector registers for vectors, but those can overlap with the
1088 // scalar registers.
1089 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
Fangrui Song6907ce22018-07-30 19:24:48 +00001090 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001091
1092 bool isSwiftErrorInRegister() const override {
1093 // x86-32 lowering does not support passing swifterror in a register.
1094 return false;
1095 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001096};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001097
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001098class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1099public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001100 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1101 bool RetSmallStructInRegABI, bool Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001102 unsigned NumRegisterParameters, bool SoftFloatABI)
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001103 : TargetCodeGenInfo(new X86_32ABIInfo(
1104 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001105 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001106
John McCall1fe2a8c2013-06-18 02:46:29 +00001107 static bool isStructReturnInRegABI(
1108 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1109
Eric Christopher162c91c2015-06-05 22:03:00 +00001110 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001111 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001112
Craig Topper4f12f102014-03-12 06:41:41 +00001113 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001114 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001115 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001116 return 4;
1117 }
1118
1119 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001120 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001121
Jay Foad7c57be32011-07-11 09:56:20 +00001122 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001123 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001124 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001125 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1126 }
1127
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001128 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1129 std::string &Constraints,
1130 std::vector<llvm::Type *> &ResultRegTypes,
1131 std::vector<llvm::Type *> &ResultTruncRegTypes,
1132 std::vector<LValue> &ResultRegDests,
1133 std::string &AsmString,
1134 unsigned NumOutputs) const override;
1135
Craig Topper4f12f102014-03-12 06:41:41 +00001136 llvm::Constant *
1137 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001138 unsigned Sig = (0xeb << 0) | // jmp rel8
1139 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001140 ('v' << 16) |
1141 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001142 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1143 }
John McCall01391782016-02-05 21:37:38 +00001144
1145 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1146 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001147 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001148 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001149};
1150
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001151}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001152
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001153/// Rewrite input constraint references after adding some output constraints.
1154/// In the case where there is one output and one input and we add one output,
1155/// we need to replace all operand references greater than or equal to 1:
1156/// mov $0, $1
1157/// mov eax, $1
1158/// The result will be:
1159/// mov $0, $2
1160/// mov eax, $2
1161static void rewriteInputConstraintReferences(unsigned FirstIn,
1162 unsigned NumNewOuts,
1163 std::string &AsmString) {
1164 std::string Buf;
1165 llvm::raw_string_ostream OS(Buf);
1166 size_t Pos = 0;
1167 while (Pos < AsmString.size()) {
1168 size_t DollarStart = AsmString.find('$', Pos);
1169 if (DollarStart == std::string::npos)
1170 DollarStart = AsmString.size();
1171 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1172 if (DollarEnd == std::string::npos)
1173 DollarEnd = AsmString.size();
1174 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1175 Pos = DollarEnd;
1176 size_t NumDollars = DollarEnd - DollarStart;
1177 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1178 // We have an operand reference.
1179 size_t DigitStart = Pos;
1180 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1181 if (DigitEnd == std::string::npos)
1182 DigitEnd = AsmString.size();
1183 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1184 unsigned OperandIndex;
1185 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1186 if (OperandIndex >= FirstIn)
1187 OperandIndex += NumNewOuts;
1188 OS << OperandIndex;
1189 } else {
1190 OS << OperandStr;
1191 }
1192 Pos = DigitEnd;
1193 }
1194 }
1195 AsmString = std::move(OS.str());
1196}
1197
1198/// Add output constraints for EAX:EDX because they are return registers.
1199void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1200 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1201 std::vector<llvm::Type *> &ResultRegTypes,
1202 std::vector<llvm::Type *> &ResultTruncRegTypes,
1203 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1204 unsigned NumOutputs) const {
1205 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1206
1207 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1208 // larger.
1209 if (!Constraints.empty())
1210 Constraints += ',';
1211 if (RetWidth <= 32) {
1212 Constraints += "={eax}";
1213 ResultRegTypes.push_back(CGF.Int32Ty);
1214 } else {
1215 // Use the 'A' constraint for EAX:EDX.
1216 Constraints += "=A";
1217 ResultRegTypes.push_back(CGF.Int64Ty);
1218 }
1219
1220 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1221 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1222 ResultTruncRegTypes.push_back(CoerceTy);
1223
1224 // Coerce the integer by bitcasting the return slot pointer.
1225 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1226 CoerceTy->getPointerTo()));
1227 ResultRegDests.push_back(ReturnSlot);
1228
1229 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1230}
1231
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001232/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001233/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001234bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1235 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001236 uint64_t Size = Context.getTypeSize(Ty);
1237
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001238 // For i386, type must be register sized.
1239 // For the MCU ABI, it only needs to be <= 8-byte
1240 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1241 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001242
1243 if (Ty->isVectorType()) {
1244 // 64- and 128- bit vectors inside structures are not returned in
1245 // registers.
1246 if (Size == 64 || Size == 128)
1247 return false;
1248
1249 return true;
1250 }
1251
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001252 // If this is a builtin, pointer, enum, complex type, member pointer, or
1253 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001254 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001255 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001256 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001257 return true;
1258
1259 // Arrays are treated like records.
1260 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001261 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001262
1263 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001264 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001265 if (!RT) return false;
1266
Anders Carlsson40446e82010-01-27 03:25:19 +00001267 // FIXME: Traverse bases here too.
1268
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001269 // Structure types are passed in register if all fields would be
1270 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001271 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001272 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001273 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001274 continue;
1275
1276 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001277 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278 return false;
1279 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001280 return true;
1281}
1282
Reid Kleckner04046052016-05-02 17:41:07 +00001283static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1284 // Treat complex types as the element type.
1285 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1286 Ty = CTy->getElementType();
1287
1288 // Check for a type which we know has a simple scalar argument-passing
1289 // convention without any padding. (We're specifically looking for 32
1290 // and 64-bit integer and integer-equivalents, float, and double.)
1291 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1292 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1293 return false;
1294
1295 uint64_t Size = Context.getTypeSize(Ty);
1296 return Size == 32 || Size == 64;
1297}
1298
Reid Kleckner791bbf62017-01-13 17:18:19 +00001299static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1300 uint64_t &Size) {
1301 for (const auto *FD : RD->fields()) {
1302 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1303 // argument is smaller than 32-bits, expanding the struct will create
1304 // alignment padding.
1305 if (!is32Or64BitBasicType(FD->getType(), Context))
1306 return false;
1307
1308 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1309 // how to expand them yet, and the predicate for telling if a bitfield still
1310 // counts as "basic" is more complicated than what we were doing previously.
1311 if (FD->isBitField())
1312 return false;
1313
1314 Size += Context.getTypeSize(FD->getType());
1315 }
1316 return true;
1317}
1318
1319static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1320 uint64_t &Size) {
1321 // Don't do this if there are any non-empty bases.
1322 for (const CXXBaseSpecifier &Base : RD->bases()) {
1323 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1324 Size))
1325 return false;
1326 }
1327 if (!addFieldSizes(Context, RD, Size))
1328 return false;
1329 return true;
1330}
1331
Reid Kleckner04046052016-05-02 17:41:07 +00001332/// Test whether an argument type which is to be passed indirectly (on the
1333/// stack) would have the equivalent layout if it was expanded into separate
1334/// arguments. If so, we prefer to do the latter to avoid inhibiting
1335/// optimizations.
1336bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1337 // We can only expand structure types.
1338 const RecordType *RT = Ty->getAs<RecordType>();
1339 if (!RT)
1340 return false;
1341 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001342 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001343 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001344 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001345 // On non-Windows, we have to conservatively match our old bitcode
1346 // prototypes in order to be ABI-compatible at the bitcode level.
1347 if (!CXXRD->isCLike())
1348 return false;
1349 } else {
1350 // Don't do this for dynamic classes.
1351 if (CXXRD->isDynamicClass())
1352 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001353 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001354 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001355 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001356 } else {
1357 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001358 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001359 }
1360
1361 // We can do this if there was no alignment padding.
1362 return Size == getContext().getTypeSize(Ty);
1363}
1364
John McCall7f416cc2015-09-08 08:05:57 +00001365ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001366 // If the return value is indirect, then the hidden argument is consuming one
1367 // integer register.
1368 if (State.FreeRegs) {
1369 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001370 if (!IsMCUABI)
1371 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001372 }
John McCall7f416cc2015-09-08 08:05:57 +00001373 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001374}
1375
Eric Christopher7565e0d2015-05-29 23:09:49 +00001376ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1377 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001378 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001379 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001380
Reid Kleckner80944df2014-10-31 22:00:51 +00001381 const Type *Base = nullptr;
1382 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001383 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1384 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001385 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1386 // The LLVM struct type for such an aggregate should lower properly.
1387 return ABIArgInfo::getDirect();
1388 }
1389
Chris Lattner458b2aa2010-07-29 02:16:43 +00001390 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001391 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001392 if (IsDarwinVectorABI) {
Hans Wennborgd874c052019-06-19 11:34:08 +00001393 uint64_t Size = getContext().getTypeSize(RetTy);
1394
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001395 // 128-bit vectors are a special case; they are returned in
1396 // registers and we need to make sure to pick a type the LLVM
1397 // backend will like.
1398 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001399 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001400 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001401
1402 // Always return in register if it fits in a general purpose
1403 // register, or if it is 64 bits and has a single element.
1404 if ((Size == 8 || Size == 16 || Size == 32) ||
1405 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001406 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001407 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001408
John McCall7f416cc2015-09-08 08:05:57 +00001409 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001410 }
1411
1412 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001413 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001414
John McCalla1dee5302010-08-22 10:59:02 +00001415 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001416 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001417 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001418 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001419 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001420 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001421
David Chisnallde3a0692009-08-17 23:08:21 +00001422 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001423 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001424 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001425
Denis Zobnin380b2242016-02-11 11:26:03 +00001426 // Ignore empty structs/unions.
1427 if (isEmptyRecord(getContext(), RetTy, true))
1428 return ABIArgInfo::getIgnore();
1429
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001430 // Small structures which are register sized are generally returned
1431 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001432 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001433 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001434
1435 // As a special-case, if the struct is a "single-element" struct, and
1436 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001437 // floating-point register. (MSVC does not apply this special case.)
1438 // We apply a similar transformation for pointer types to improve the
1439 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001440 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001441 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001442 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001443 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1444
1445 // FIXME: We should be able to narrow this integer in cases with dead
1446 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001447 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001448 }
1449
John McCall7f416cc2015-09-08 08:05:57 +00001450 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001451 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001452
Chris Lattner458b2aa2010-07-29 02:16:43 +00001453 // Treat an enum type as its underlying type.
1454 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1455 RetTy = EnumTy->getDecl()->getIntegerType();
1456
Alex Bradburye41a5e22018-01-12 20:08:16 +00001457 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1458 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001459}
1460
Eli Friedman7919bea2012-06-05 19:40:46 +00001461static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1462 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1463}
1464
Daniel Dunbared23de32010-09-16 20:42:00 +00001465static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1466 const RecordType *RT = Ty->getAs<RecordType>();
1467 if (!RT)
1468 return 0;
1469 const RecordDecl *RD = RT->getDecl();
1470
1471 // If this is a C++ record, check the bases first.
1472 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001473 for (const auto &I : CXXRD->bases())
1474 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001475 return false;
1476
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001477 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001478 QualType FT = i->getType();
1479
Eli Friedman7919bea2012-06-05 19:40:46 +00001480 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001481 return true;
1482
1483 if (isRecordWithSSEVectorType(Context, FT))
1484 return true;
1485 }
1486
1487 return false;
1488}
1489
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001490unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1491 unsigned Align) const {
1492 // Otherwise, if the alignment is less than or equal to the minimum ABI
1493 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001494 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001495 return 0; // Use default alignment.
1496
Pengfei Wang48387ec2019-05-31 01:50:07 +00001497 // On non-Darwin, the stack type alignment is always 4.
1498 if (!IsDarwinVectorABI) {
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001499 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001500 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001501 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001502
Daniel Dunbared23de32010-09-16 20:42:00 +00001503 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001504 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1505 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001506 return 16;
1507
1508 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001509}
1510
Rafael Espindola703c47f2012-10-19 05:04:37 +00001511ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001512 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001513 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001514 if (State.FreeRegs) {
1515 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001516 if (!IsMCUABI)
1517 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001518 }
John McCall7f416cc2015-09-08 08:05:57 +00001519 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001520 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001521
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001522 // Compute the byval alignment.
1523 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1524 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1525 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001526 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001527
1528 // If the stack alignment is less than the type alignment, realign the
1529 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001530 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001531 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1532 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001533}
1534
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001535X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1536 const Type *T = isSingleElementStruct(Ty, getContext());
1537 if (!T)
1538 T = Ty.getTypePtr();
1539
1540 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1541 BuiltinType::Kind K = BT->getKind();
1542 if (K == BuiltinType::Float || K == BuiltinType::Double)
1543 return Float;
1544 }
1545 return Integer;
1546}
1547
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001548bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001549 if (!IsSoftFloatABI) {
1550 Class C = classify(Ty);
1551 if (C == Float)
1552 return false;
1553 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001554
Rafael Espindola077dd592012-10-24 01:58:58 +00001555 unsigned Size = getContext().getTypeSize(Ty);
1556 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001557
1558 if (SizeInRegs == 0)
1559 return false;
1560
Michael Kuperstein68901882015-10-25 08:18:20 +00001561 if (!IsMCUABI) {
1562 if (SizeInRegs > State.FreeRegs) {
1563 State.FreeRegs = 0;
1564 return false;
1565 }
1566 } else {
1567 // The MCU psABI allows passing parameters in-reg even if there are
1568 // earlier parameters that are passed on the stack. Also,
1569 // it does not allow passing >8-byte structs in-register,
1570 // even if there are 3 free registers available.
1571 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1572 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001573 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001574
Reid Kleckner661f35b2014-01-18 01:12:41 +00001575 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001576 return true;
1577}
1578
Fangrui Song6907ce22018-07-30 19:24:48 +00001579bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001580 bool &InReg,
1581 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001582 // On Windows, aggregates other than HFAs are never passed in registers, and
1583 // they do not consume register slots. Homogenous floating-point aggregates
1584 // (HFAs) have already been dealt with at this point.
1585 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1586 return false;
1587
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001588 NeedsPadding = false;
1589 InReg = !IsMCUABI;
1590
1591 if (!updateFreeRegs(Ty, State))
1592 return false;
1593
1594 if (IsMCUABI)
1595 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001596
Reid Kleckner80944df2014-10-31 22:00:51 +00001597 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001598 State.CC == llvm::CallingConv::X86_VectorCall ||
1599 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001600 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001601 NeedsPadding = true;
1602
Rafael Espindola077dd592012-10-24 01:58:58 +00001603 return false;
1604 }
1605
Rafael Espindola703c47f2012-10-19 05:04:37 +00001606 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001607}
1608
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001609bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1610 if (!updateFreeRegs(Ty, State))
1611 return false;
1612
1613 if (IsMCUABI)
1614 return false;
1615
1616 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001617 State.CC == llvm::CallingConv::X86_VectorCall ||
1618 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001619 if (getContext().getTypeSize(Ty) > 32)
1620 return false;
1621
Fangrui Song6907ce22018-07-30 19:24:48 +00001622 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001623 Ty->isReferenceType());
1624 }
1625
1626 return true;
1627}
1628
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001629ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1630 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001631 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001632
Reid Klecknerb1be6832014-11-15 01:41:41 +00001633 Ty = useFirstFieldIfTransparentUnion(Ty);
1634
Reid Kleckner80944df2014-10-31 22:00:51 +00001635 // Check with the C++ ABI first.
1636 const RecordType *RT = Ty->getAs<RecordType>();
1637 if (RT) {
1638 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1639 if (RAA == CGCXXABI::RAA_Indirect) {
1640 return getIndirectResult(Ty, false, State);
1641 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1642 // The field index doesn't matter, we'll fix it up later.
1643 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1644 }
1645 }
1646
Erich Keane4bd39302017-06-21 16:37:22 +00001647 // Regcall uses the concept of a homogenous vector aggregate, similar
1648 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001649 const Type *Base = nullptr;
1650 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001651 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001652 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001653
Erich Keane4bd39302017-06-21 16:37:22 +00001654 if (State.FreeSSERegs >= NumElts) {
1655 State.FreeSSERegs -= NumElts;
1656 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001657 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001658 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001659 }
Erich Keane4bd39302017-06-21 16:37:22 +00001660 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001661 }
1662
1663 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001664 // Structures with flexible arrays are always indirect.
1665 // FIXME: This should not be byval!
1666 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1667 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001668
Reid Kleckner04046052016-05-02 17:41:07 +00001669 // Ignore empty structs/unions on non-Windows.
1670 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001671 return ABIArgInfo::getIgnore();
1672
Rafael Espindolafad28de2012-10-24 01:59:00 +00001673 llvm::LLVMContext &LLVMContext = getVMContext();
1674 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001675 bool NeedsPadding = false;
1676 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001677 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001678 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001679 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001680 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001681 if (InReg)
1682 return ABIArgInfo::getDirectInReg(Result);
1683 else
1684 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001685 }
Craig Topper8a13c412014-05-21 05:09:00 +00001686 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001687
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001688 // Expand small (<= 128-bit) record types when we know that the stack layout
1689 // of those arguments will match the struct. This is important because the
1690 // LLVM backend isn't smart enough to remove byval, which inhibits many
1691 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001692 // Don't do this for the MCU if there are still free integer registers
1693 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001694 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1695 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001696 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001697 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001698 State.CC == llvm::CallingConv::X86_VectorCall ||
1699 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001700 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001701
Reid Kleckner661f35b2014-01-18 01:12:41 +00001702 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001703 }
1704
Chris Lattnerd774ae92010-08-26 20:05:13 +00001705 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001706 // On Darwin, some vectors are passed in memory, we handle this by passing
1707 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001708 if (IsDarwinVectorABI) {
Hans Wennborgd874c052019-06-19 11:34:08 +00001709 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001710 if ((Size == 8 || Size == 16 || Size == 32) ||
1711 (Size == 64 && VT->getNumElements() == 1))
1712 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1713 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001714 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001715
Hans Wennborgd874c052019-06-19 11:34:08 +00001716 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1717 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1718
Chris Lattnerd774ae92010-08-26 20:05:13 +00001719 return ABIArgInfo::getDirect();
1720 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001721
Hans Wennborgd874c052019-06-19 11:34:08 +00001722
Chris Lattner458b2aa2010-07-29 02:16:43 +00001723 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1724 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001725
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001726 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001727
1728 if (Ty->isPromotableIntegerType()) {
1729 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001730 return ABIArgInfo::getExtendInReg(Ty);
1731 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001732 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001733
Rafael Espindola703c47f2012-10-19 05:04:37 +00001734 if (InReg)
1735 return ABIArgInfo::getDirectInReg();
1736 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001737}
1738
Erich Keane521ed962017-01-05 00:20:51 +00001739void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1740 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001741 // Vectorcall x86 works subtly different than in x64, so the format is
1742 // a bit different than the x64 version. First, all vector types (not HVAs)
1743 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1744 // This differs from the x64 implementation, where the first 6 by INDEX get
1745 // registers.
1746 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1747 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1748 // first take up the remaining YMM/XMM registers. If insufficient registers
1749 // remain but an integer register (ECX/EDX) is available, it will be passed
1750 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001751 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001752 // First pass do all the vector types.
1753 const Type *Base = nullptr;
1754 uint64_t NumElts = 0;
1755 const QualType& Ty = I.type;
1756 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1757 isHomogeneousAggregate(Ty, Base, NumElts)) {
1758 if (State.FreeSSERegs >= NumElts) {
1759 State.FreeSSERegs -= NumElts;
1760 I.info = ABIArgInfo::getDirect();
1761 } else {
1762 I.info = classifyArgumentType(Ty, State);
1763 }
1764 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1765 }
Erich Keane521ed962017-01-05 00:20:51 +00001766 }
Erich Keane4bd39302017-06-21 16:37:22 +00001767
Erich Keane521ed962017-01-05 00:20:51 +00001768 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001769 // Second pass, do the rest!
1770 const Type *Base = nullptr;
1771 uint64_t NumElts = 0;
1772 const QualType& Ty = I.type;
1773 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1774
1775 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1776 // Assign true HVAs (non vector/native FP types).
1777 if (State.FreeSSERegs >= NumElts) {
1778 State.FreeSSERegs -= NumElts;
1779 I.info = getDirectX86Hva();
1780 } else {
1781 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1782 }
1783 } else if (!IsHva) {
1784 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1785 I.info = classifyArgumentType(Ty, State);
1786 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1787 }
Erich Keane521ed962017-01-05 00:20:51 +00001788 }
1789}
1790
Rafael Espindolaa6472962012-07-24 00:01:07 +00001791void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001792 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001793 if (IsMCUABI)
1794 State.FreeRegs = 3;
1795 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001796 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001797 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1798 State.FreeRegs = 2;
1799 State.FreeSSERegs = 6;
1800 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001801 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001802 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1803 State.FreeRegs = 5;
1804 State.FreeSSERegs = 8;
1805 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001806 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001807
Akira Hatanakad791e922018-03-19 17:38:40 +00001808 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001809 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001810 } else if (FI.getReturnInfo().isIndirect()) {
1811 // The C++ ABI is not aware of register usage, so we have to check if the
1812 // return value was sret and put it in a register ourselves if appropriate.
1813 if (State.FreeRegs) {
1814 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001815 if (!IsMCUABI)
1816 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001817 }
1818 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001819
Peter Collingbournef7706832014-12-12 23:41:25 +00001820 // The chain argument effectively gives us another free register.
1821 if (FI.isChainCall())
1822 ++State.FreeRegs;
1823
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001824 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001825 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1826 computeVectorCallArgs(FI, State, UsedInAlloca);
1827 } else {
1828 // If not vectorcall, revert to normal behavior.
1829 for (auto &I : FI.arguments()) {
1830 I.info = classifyArgumentType(I.type, State);
1831 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1832 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001833 }
1834
1835 // If we needed to use inalloca for any argument, do a second pass and rewrite
1836 // all the memory arguments to use inalloca.
1837 if (UsedInAlloca)
1838 rewriteWithInAlloca(FI);
1839}
1840
1841void
1842X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001843 CharUnits &StackOffset, ABIArgInfo &Info,
1844 QualType Type) const {
1845 // Arguments are always 4-byte-aligned.
1846 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1847
1848 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001849 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1850 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001851 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001852
John McCall7f416cc2015-09-08 08:05:57 +00001853 // Insert padding bytes to respect alignment.
1854 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001855 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001856 if (StackOffset != FieldEnd) {
1857 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001858 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001859 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001860 FrameFields.push_back(Ty);
1861 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001862}
1863
Reid Kleckner852361d2014-07-26 00:12:26 +00001864static bool isArgInAlloca(const ABIArgInfo &Info) {
1865 // Leave ignored and inreg arguments alone.
1866 switch (Info.getKind()) {
1867 case ABIArgInfo::InAlloca:
1868 return true;
1869 case ABIArgInfo::Indirect:
1870 assert(Info.getIndirectByVal());
1871 return true;
1872 case ABIArgInfo::Ignore:
1873 return false;
1874 case ABIArgInfo::Direct:
1875 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001876 if (Info.getInReg())
1877 return false;
1878 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001879 case ABIArgInfo::Expand:
1880 case ABIArgInfo::CoerceAndExpand:
1881 // These are aggregate types which are never passed in registers when
1882 // inalloca is involved.
1883 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001884 }
1885 llvm_unreachable("invalid enum");
1886}
1887
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001888void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1889 assert(IsWin32StructABI && "inalloca only supported on win32");
1890
1891 // Build a packed struct type for all of the arguments in memory.
1892 SmallVector<llvm::Type *, 6> FrameFields;
1893
John McCall7f416cc2015-09-08 08:05:57 +00001894 // The stack alignment is always 4.
1895 CharUnits StackAlign = CharUnits::fromQuantity(4);
1896
1897 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001898 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1899
1900 // Put 'this' into the struct before 'sret', if necessary.
1901 bool IsThisCall =
1902 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1903 ABIArgInfo &Ret = FI.getReturnInfo();
1904 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1905 isArgInAlloca(I->info)) {
1906 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1907 ++I;
1908 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001909
1910 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001911 if (Ret.isIndirect() && !Ret.getInReg()) {
1912 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1913 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001914 // On Windows, the hidden sret parameter is always returned in eax.
1915 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001916 }
1917
1918 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001919 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001920 ++I;
1921
1922 // Put arguments passed in memory into the struct.
1923 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001924 if (isArgInAlloca(I->info))
1925 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001926 }
1927
1928 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001929 /*isPacked=*/true),
1930 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001931}
1932
John McCall7f416cc2015-09-08 08:05:57 +00001933Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1934 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001935
John McCall7f416cc2015-09-08 08:05:57 +00001936 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001937
John McCall7f416cc2015-09-08 08:05:57 +00001938 // x86-32 changes the alignment of certain arguments on the stack.
1939 //
1940 // Just messing with TypeInfo like this works because we never pass
1941 // anything indirectly.
1942 TypeInfo.second = CharUnits::fromQuantity(
1943 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001944
John McCall7f416cc2015-09-08 08:05:57 +00001945 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1946 TypeInfo, CharUnits::fromQuantity(4),
1947 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001948}
1949
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001950bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1951 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1952 assert(Triple.getArch() == llvm::Triple::x86);
1953
1954 switch (Opts.getStructReturnConvention()) {
1955 case CodeGenOptions::SRCK_Default:
1956 break;
1957 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1958 return false;
1959 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1960 return true;
1961 }
1962
Michael Kupersteind749f232015-10-27 07:46:22 +00001963 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001964 return true;
1965
1966 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001967 case llvm::Triple::DragonFly:
1968 case llvm::Triple::FreeBSD:
1969 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001970 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001971 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001972 default:
1973 return false;
1974 }
1975}
1976
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001977void X86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001978 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1979 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001980 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001981 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001982 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001983 llvm::Function *Fn = cast<llvm::Function>(GV);
Erich Keaneb127a3942018-04-19 14:27:05 +00001984 Fn->addFnAttr("stackrealign");
Charles Davis4ea31ab2010-02-13 15:54:06 +00001985 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001986 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1987 llvm::Function *Fn = cast<llvm::Function>(GV);
1988 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1989 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001990 }
1991}
1992
John McCallbeec5a02010-03-06 00:35:14 +00001993bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1994 CodeGen::CodeGenFunction &CGF,
1995 llvm::Value *Address) const {
1996 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001997
Chris Lattnerece04092012-02-07 00:39:47 +00001998 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001999
John McCallbeec5a02010-03-06 00:35:14 +00002000 // 0-7 are the eight integer registers; the order is different
2001 // on Darwin (for EH), but the range is the same.
2002 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00002003 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00002004
John McCallc8e01702013-04-16 22:48:15 +00002005 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00002006 // 12-16 are st(0..4). Not sure why we stop at 4.
2007 // These have size 16, which is sizeof(long double) on
2008 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002009 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00002010 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002011
John McCallbeec5a02010-03-06 00:35:14 +00002012 } else {
2013 // 9 is %eflags, which doesn't get a size on Darwin for some
2014 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00002015 Builder.CreateAlignedStore(
2016 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2017 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00002018
2019 // 11-16 are st(0..5). Not sure why we stop at 5.
2020 // These have size 12, which is sizeof(long double) on
2021 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002022 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00002023 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2024 }
John McCallbeec5a02010-03-06 00:35:14 +00002025
2026 return false;
2027}
2028
Chris Lattner0cf24192010-06-28 20:05:43 +00002029//===----------------------------------------------------------------------===//
2030// X86-64 ABI Implementation
2031//===----------------------------------------------------------------------===//
2032
2033
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002034namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002035/// The AVX ABI level for X86 targets.
2036enum class X86AVXABILevel {
2037 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002038 AVX,
2039 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002040};
2041
2042/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2043static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2044 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002045 case X86AVXABILevel::AVX512:
2046 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002047 case X86AVXABILevel::AVX:
2048 return 256;
2049 case X86AVXABILevel::None:
2050 return 128;
2051 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002052 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002053}
2054
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002055/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002056class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002057 enum Class {
2058 Integer = 0,
2059 SSE,
2060 SSEUp,
2061 X87,
2062 X87Up,
2063 ComplexX87,
2064 NoClass,
2065 Memory
2066 };
2067
2068 /// merge - Implement the X86_64 ABI merging algorithm.
2069 ///
2070 /// Merge an accumulating classification \arg Accum with a field
2071 /// classification \arg Field.
2072 ///
2073 /// \param Accum - The accumulating classification. This should
2074 /// always be either NoClass or the result of a previous merge
2075 /// call. In addition, this should never be Memory (the caller
2076 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002077 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002078
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002079 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2080 ///
2081 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2082 /// final MEMORY or SSE classes when necessary.
2083 ///
2084 /// \param AggregateSize - The size of the current aggregate in
2085 /// the classification process.
2086 ///
2087 /// \param Lo - The classification for the parts of the type
2088 /// residing in the low word of the containing object.
2089 ///
2090 /// \param Hi - The classification for the parts of the type
2091 /// residing in the higher words of the containing object.
2092 ///
2093 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2094
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002095 /// classify - Determine the x86_64 register classes in which the
2096 /// given type T should be passed.
2097 ///
2098 /// \param Lo - The classification for the parts of the type
2099 /// residing in the low word of the containing object.
2100 ///
2101 /// \param Hi - The classification for the parts of the type
2102 /// residing in the high word of the containing object.
2103 ///
2104 /// \param OffsetBase - The bit offset of this type in the
2105 /// containing object. Some parameters are classified different
2106 /// depending on whether they straddle an eightbyte boundary.
2107 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002108 /// \param isNamedArg - Whether the argument in question is a "named"
2109 /// argument, as used in AMD64-ABI 3.5.7.
2110 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002111 /// If a word is unused its result will be NoClass; if a type should
2112 /// be passed in Memory then at least the classification of \arg Lo
2113 /// will be Memory.
2114 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002115 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002116 ///
2117 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2118 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002119 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2120 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002121
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002122 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002123 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2124 unsigned IROffset, QualType SourceTy,
2125 unsigned SourceOffset) const;
2126 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2127 unsigned IROffset, QualType SourceTy,
2128 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002129
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002130 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002131 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002132 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002133
2134 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002135 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002136 ///
2137 /// \param freeIntRegs - The number of free integer registers remaining
2138 /// available.
2139 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002140
Chris Lattner458b2aa2010-07-29 02:16:43 +00002141 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002142
Erich Keane757d3172016-11-02 18:29:35 +00002143 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2144 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002145 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002146
Erich Keane757d3172016-11-02 18:29:35 +00002147 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2148 unsigned &NeededSSE) const;
2149
2150 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2151 unsigned &NeededSSE) const;
2152
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002153 bool IsIllegalVectorType(QualType Ty) const;
2154
John McCalle0fda732011-04-21 01:20:55 +00002155 /// The 0.98 ABI revision clarified a lot of ambiguities,
2156 /// unfortunately in ways that were not always consistent with
2157 /// certain previous compilers. In particular, platforms which
2158 /// required strict binary compatibility with older versions of GCC
2159 /// may need to exempt themselves.
2160 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002161 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002162 }
2163
Richard Smithf667ad52017-08-26 01:04:35 +00002164 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2165 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002166 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002167 // Clang <= 3.8 did not do this.
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002168 if (getContext().getLangOpts().getClangABICompat() <=
2169 LangOptions::ClangABI::Ver3_8)
Richard Smithf667ad52017-08-26 01:04:35 +00002170 return false;
2171
David Majnemere2ae2282016-03-04 05:26:16 +00002172 const llvm::Triple &Triple = getTarget().getTriple();
2173 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2174 return false;
2175 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2176 return false;
2177 return true;
2178 }
2179
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002180 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002181 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2182 // 64-bit hardware.
2183 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002184
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002185public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002186 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002187 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002188 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002189 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002190
John McCalla729c622012-02-17 03:33:10 +00002191 bool isPassedUsingAVXType(QualType type) const {
2192 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002193 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002194 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2195 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002196 if (info.isDirect()) {
2197 llvm::Type *ty = info.getCoerceToType();
2198 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2199 return (vectorTy->getBitWidth() > 128);
2200 }
2201 return false;
2202 }
2203
Craig Topper4f12f102014-03-12 06:41:41 +00002204 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002205
John McCall7f416cc2015-09-08 08:05:57 +00002206 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2207 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002208 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2209 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002210
2211 bool has64BitPointers() const {
2212 return Has64BitPointers;
2213 }
John McCall12f23522016-04-04 18:33:08 +00002214
John McCall56331e22018-01-07 06:28:49 +00002215 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002216 bool asReturnValue) const override {
2217 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002218 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002219 bool isSwiftErrorInRegister() const override {
2220 return true;
2221 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002222};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002223
Chris Lattner04dc9572010-08-31 16:44:54 +00002224/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002225class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002226public:
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002227 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2228 : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Reid Kleckner11a17192015-10-28 22:29:52 +00002229 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002230
Craig Topper4f12f102014-03-12 06:41:41 +00002231 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002232
John McCall7f416cc2015-09-08 08:05:57 +00002233 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2234 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002235
2236 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2237 // FIXME: Assumes vectorcall is in use.
2238 return isX86VectorTypeForVectorCall(getContext(), Ty);
2239 }
2240
2241 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2242 uint64_t NumMembers) const override {
2243 // FIXME: Assumes vectorcall is in use.
2244 return isX86VectorCallAggregateSmallEnough(NumMembers);
2245 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002246
John McCall56331e22018-01-07 06:28:49 +00002247 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002248 bool asReturnValue) const override {
2249 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2250 }
2251
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002252 bool isSwiftErrorInRegister() const override {
2253 return true;
2254 }
2255
Reid Kleckner11a17192015-10-28 22:29:52 +00002256private:
Erich Keane521ed962017-01-05 00:20:51 +00002257 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2258 bool IsVectorCall, bool IsRegCall) const;
2259 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2260 const ABIArgInfo &current) const;
2261 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2262 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002263
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002264 X86AVXABILevel AVXLevel;
2265
2266 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002267};
2268
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002269class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2270public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002271 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002272 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002273
John McCalla729c622012-02-17 03:33:10 +00002274 const X86_64ABIInfo &getABIInfo() const {
2275 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2276 }
2277
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002278 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2279 /// the autoreleaseRV/retainRV optimization.
2280 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2281 return true;
2282 }
2283
Craig Topper4f12f102014-03-12 06:41:41 +00002284 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002285 return 7;
2286 }
2287
2288 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002289 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002290 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002291
John McCall943fae92010-05-27 06:19:26 +00002292 // 0-15 are the 16 integer registers.
2293 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002294 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002295 return false;
2296 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002297
Jay Foad7c57be32011-07-11 09:56:20 +00002298 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002299 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002300 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002301 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2302 }
2303
John McCalla729c622012-02-17 03:33:10 +00002304 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002305 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002306 // The default CC on x86-64 sets %al to the number of SSA
2307 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002308 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002309 // that when AVX types are involved: the ABI explicitly states it is
2310 // undefined, and it doesn't work in practice because of how the ABI
2311 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002312 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002313 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002314 for (CallArgList::const_iterator
2315 it = args.begin(), ie = args.end(); it != ie; ++it) {
2316 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2317 HasAVXType = true;
2318 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002319 }
2320 }
John McCalla729c622012-02-17 03:33:10 +00002321
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002322 if (!HasAVXType)
2323 return true;
2324 }
John McCallcbc038a2011-09-21 08:08:30 +00002325
John McCalla729c622012-02-17 03:33:10 +00002326 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002327 }
2328
Craig Topper4f12f102014-03-12 06:41:41 +00002329 llvm::Constant *
2330 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002331 unsigned Sig = (0xeb << 0) | // jmp rel8
2332 (0x06 << 8) | // .+0x08
2333 ('v' << 16) |
2334 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002335 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2336 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002337
2338 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002339 CodeGen::CodeGenModule &CGM) const override {
2340 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002341 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002342 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002343 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002344 llvm::Function *Fn = cast<llvm::Function>(GV);
2345 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002346 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002347 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2348 llvm::Function *Fn = cast<llvm::Function>(GV);
2349 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2350 }
2351 }
2352 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002353};
2354
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002355static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002356 // If the argument does not end in .lib, automatically add the suffix.
2357 // If the argument contains a space, enclose it in quotes.
2358 // This matches the behavior of MSVC.
2359 bool Quote = (Lib.find(" ") != StringRef::npos);
2360 std::string ArgStr = Quote ? "\"" : "";
2361 ArgStr += Lib;
Martin Storsjo3cd67c92018-10-10 09:01:00 +00002362 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002363 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002364 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002365 return ArgStr;
2366}
2367
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002368class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2369public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002370 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002371 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2372 unsigned NumRegisterParameters)
2373 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002374 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002375
Eric Christopher162c91c2015-06-05 22:03:00 +00002376 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002377 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002378
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002379 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002380 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002381 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002382 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002383 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002384
2385 void getDetectMismatchOption(llvm::StringRef Name,
2386 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002387 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002388 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002389 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002390};
2391
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002392static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2393 CodeGen::CodeGenModule &CGM) {
2394 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002395
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002396 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Eric Christopher7565e0d2015-05-29 23:09:49 +00002397 Fn->addFnAttr("stack-probe-size",
2398 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002399 if (CGM.getCodeGenOpts().NoStackArgProbe)
2400 Fn->addFnAttr("no-stack-arg-probe");
Hans Wennborg77dc2362015-01-20 19:45:50 +00002401 }
2402}
2403
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002404void WinX86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002405 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2406 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2407 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002408 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002409 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002410}
2411
Chris Lattner04dc9572010-08-31 16:44:54 +00002412class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2413public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002414 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2415 X86AVXABILevel AVXLevel)
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002416 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002417
Eric Christopher162c91c2015-06-05 22:03:00 +00002418 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002419 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002420
Craig Topper4f12f102014-03-12 06:41:41 +00002421 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002422 return 7;
2423 }
2424
2425 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002426 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002427 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002428
Chris Lattner04dc9572010-08-31 16:44:54 +00002429 // 0-15 are the 16 integer registers.
2430 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002431 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002432 return false;
2433 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002434
2435 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002436 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002437 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002438 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002439 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002440
2441 void getDetectMismatchOption(llvm::StringRef Name,
2442 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002443 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002444 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002445 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002446};
2447
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002448void WinX86_64TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002449 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2450 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2451 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002452 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002453 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002454 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002455 llvm::Function *Fn = cast<llvm::Function>(GV);
2456 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002457 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002458 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2459 llvm::Function *Fn = cast<llvm::Function>(GV);
2460 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2461 }
2462 }
2463
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002464 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002465}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002466}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002467
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002468void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2469 Class &Hi) const {
2470 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2471 //
2472 // (a) If one of the classes is Memory, the whole argument is passed in
2473 // memory.
2474 //
2475 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2476 // memory.
2477 //
2478 // (c) If the size of the aggregate exceeds two eightbytes and the first
2479 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2480 // argument is passed in memory. NOTE: This is necessary to keep the
2481 // ABI working for processors that don't support the __m256 type.
2482 //
2483 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2484 //
2485 // Some of these are enforced by the merging logic. Others can arise
2486 // only with unions; for example:
2487 // union { _Complex double; unsigned; }
2488 //
2489 // Note that clauses (b) and (c) were added in 0.98.
2490 //
2491 if (Hi == Memory)
2492 Lo = Memory;
2493 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2494 Lo = Memory;
2495 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2496 Lo = Memory;
2497 if (Hi == SSEUp && Lo != SSE)
2498 Hi = SSE;
2499}
2500
Chris Lattnerd776fb12010-06-28 21:43:59 +00002501X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002502 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2503 // classified recursively so that always two fields are
2504 // considered. The resulting class is calculated according to
2505 // the classes of the fields in the eightbyte:
2506 //
2507 // (a) If both classes are equal, this is the resulting class.
2508 //
2509 // (b) If one of the classes is NO_CLASS, the resulting class is
2510 // the other class.
2511 //
2512 // (c) If one of the classes is MEMORY, the result is the MEMORY
2513 // class.
2514 //
2515 // (d) If one of the classes is INTEGER, the result is the
2516 // INTEGER.
2517 //
2518 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2519 // MEMORY is used as class.
2520 //
2521 // (f) Otherwise class SSE is used.
2522
2523 // Accum should never be memory (we should have returned) or
2524 // ComplexX87 (because this cannot be passed in a structure).
2525 assert((Accum != Memory && Accum != ComplexX87) &&
2526 "Invalid accumulated classification during merge.");
2527 if (Accum == Field || Field == NoClass)
2528 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002529 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002530 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002531 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002533 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002534 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002535 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2536 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002538 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002539}
2540
Chris Lattner5c740f12010-06-30 19:14:05 +00002541void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002542 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002543 // FIXME: This code can be simplified by introducing a simple value class for
2544 // Class pairs with appropriate constructor methods for the various
2545 // situations.
2546
2547 // FIXME: Some of the split computations are wrong; unaligned vectors
2548 // shouldn't be passed in registers for example, so there is no chance they
2549 // can straddle an eightbyte. Verify & simplify.
2550
2551 Lo = Hi = NoClass;
2552
2553 Class &Current = OffsetBase < 64 ? Lo : Hi;
2554 Current = Memory;
2555
John McCall9dd450b2009-09-21 23:43:11 +00002556 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002557 BuiltinType::Kind k = BT->getKind();
2558
2559 if (k == BuiltinType::Void) {
2560 Current = NoClass;
2561 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2562 Lo = Integer;
2563 Hi = Integer;
2564 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2565 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002566 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002567 Current = SSE;
2568 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002569 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002570 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002571 Lo = SSE;
2572 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002573 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002574 Lo = X87;
2575 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002576 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002577 Current = SSE;
2578 } else
2579 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002580 }
2581 // FIXME: _Decimal32 and _Decimal64 are SSE.
2582 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002583 return;
2584 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002585
Chris Lattnerd776fb12010-06-28 21:43:59 +00002586 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002587 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002588 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002589 return;
2590 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002591
Chris Lattnerd776fb12010-06-28 21:43:59 +00002592 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002593 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002594 return;
2595 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002596
Chris Lattnerd776fb12010-06-28 21:43:59 +00002597 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002598 if (Ty->isMemberFunctionPointerType()) {
2599 if (Has64BitPointers) {
2600 // If Has64BitPointers, this is an {i64, i64}, so classify both
2601 // Lo and Hi now.
2602 Lo = Hi = Integer;
2603 } else {
2604 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2605 // straddles an eightbyte boundary, Hi should be classified as well.
2606 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2607 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2608 if (EB_FuncPtr != EB_ThisAdj) {
2609 Lo = Hi = Integer;
2610 } else {
2611 Current = Integer;
2612 }
2613 }
2614 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002615 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002616 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002617 return;
2618 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002619
Chris Lattnerd776fb12010-06-28 21:43:59 +00002620 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002621 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002622 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2623 // gcc passes the following as integer:
2624 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2625 // 2 bytes - <2 x char>, <1 x short>
2626 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002627 Current = Integer;
2628
2629 // If this type crosses an eightbyte boundary, it should be
2630 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002631 uint64_t EB_Lo = (OffsetBase) / 64;
2632 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2633 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002634 Hi = Lo;
2635 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002636 QualType ElementType = VT->getElementType();
2637
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002638 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002639 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002640 return;
2641
David Majnemere2ae2282016-03-04 05:26:16 +00002642 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2643 // pass them as integer. For platforms where clang is the de facto
2644 // platform compiler, we must continue to use integer.
2645 if (!classifyIntegerMMXAsSSE() &&
2646 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2647 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2648 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2649 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002650 Current = Integer;
2651 else
2652 Current = SSE;
2653
2654 // If this type crosses an eightbyte boundary, it should be
2655 // split.
2656 if (OffsetBase && OffsetBase != 64)
2657 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002658 } else if (Size == 128 ||
2659 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002660 // Arguments of 256-bits are split into four eightbyte chunks. The
2661 // least significant one belongs to class SSE and all the others to class
2662 // SSEUP. The original Lo and Hi design considers that types can't be
2663 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2664 // This design isn't correct for 256-bits, but since there're no cases
2665 // where the upper parts would need to be inspected, avoid adding
2666 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002667 //
2668 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2669 // registers if they are "named", i.e. not part of the "..." of a
2670 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002671 //
2672 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2673 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674 Lo = SSE;
2675 Hi = SSEUp;
2676 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002677 return;
2678 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002679
Chris Lattnerd776fb12010-06-28 21:43:59 +00002680 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002681 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682
Chris Lattner2b037972010-07-29 02:01:43 +00002683 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002684 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685 if (Size <= 64)
2686 Current = Integer;
2687 else if (Size <= 128)
2688 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002689 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002691 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002693 } else if (ET == getContext().LongDoubleTy) {
2694 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002695 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002696 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002697 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002698 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002699 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002700 Lo = Hi = SSE;
2701 else
2702 llvm_unreachable("unexpected long double representation!");
2703 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002704
2705 // If this complex type crosses an eightbyte boundary then it
2706 // should be split.
2707 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002708 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002709 if (Hi == NoClass && EB_Real != EB_Imag)
2710 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002711
Chris Lattnerd776fb12010-06-28 21:43:59 +00002712 return;
2713 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002714
Chris Lattner2b037972010-07-29 02:01:43 +00002715 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002716 // Arrays are treated like structures.
2717
Chris Lattner2b037972010-07-29 02:01:43 +00002718 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719
2720 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002721 // than eight eightbytes, ..., it has class MEMORY.
2722 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002723 return;
2724
2725 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2726 // fields, it has class MEMORY.
2727 //
2728 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002729 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002730 return;
2731
2732 // Otherwise implement simplified merge. We could be smarter about
2733 // this, but it isn't worth it and would be harder to verify.
2734 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002735 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002736 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002737
2738 // The only case a 256-bit wide vector could be used is when the array
2739 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2740 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002741 //
2742 if (Size > 128 &&
2743 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002744 return;
2745
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002746 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2747 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002748 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002749 Lo = merge(Lo, FieldLo);
2750 Hi = merge(Hi, FieldHi);
2751 if (Lo == Memory || Hi == Memory)
2752 break;
2753 }
2754
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002755 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002756 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002757 return;
2758 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002759
Chris Lattnerd776fb12010-06-28 21:43:59 +00002760 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002761 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002762
2763 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002764 // than eight eightbytes, ..., it has class MEMORY.
2765 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002766 return;
2767
Anders Carlsson20759ad2009-09-16 15:53:40 +00002768 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2769 // copy constructor or a non-trivial destructor, it is passed by invisible
2770 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002771 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002772 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002773
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002774 const RecordDecl *RD = RT->getDecl();
2775
2776 // Assume variable sized types are passed in memory.
2777 if (RD->hasFlexibleArrayMember())
2778 return;
2779
Chris Lattner2b037972010-07-29 02:01:43 +00002780 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002781
2782 // Reset Lo class, this will be recomputed.
2783 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002784
2785 // If this is a C++ record, classify the bases first.
2786 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002787 for (const auto &I : CXXRD->bases()) {
2788 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002789 "Unexpected base class!");
2790 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002791 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002792
2793 // Classify this field.
2794 //
2795 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2796 // single eightbyte, each is classified separately. Each eightbyte gets
2797 // initialized to class NO_CLASS.
2798 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002799 uint64_t Offset =
2800 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002801 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002802 Lo = merge(Lo, FieldLo);
2803 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002804 if (Lo == Memory || Hi == Memory) {
2805 postMerge(Size, Lo, Hi);
2806 return;
2807 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002808 }
2809 }
2810
2811 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002812 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002813 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002814 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002815 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2816 bool BitField = i->isBitField();
2817
David Majnemerb439dfe2016-08-15 07:20:40 +00002818 // Ignore padding bit-fields.
2819 if (BitField && i->isUnnamedBitfield())
2820 continue;
2821
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002822 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2823 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002824 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002825 // The only case a 256-bit wide vector could be used is when the struct
2826 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2827 // to work for sizes wider than 128, early check and fallback to memory.
2828 //
David Majnemerb229cb02016-08-15 06:39:18 +00002829 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2830 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002831 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002832 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002833 return;
2834 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002835 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002836 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002837 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002838 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002839 return;
2840 }
2841
2842 // Classify this field.
2843 //
2844 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2845 // exceeds a single eightbyte, each is classified
2846 // separately. Each eightbyte gets initialized to class
2847 // NO_CLASS.
2848 Class FieldLo, FieldHi;
2849
2850 // Bit-fields require special handling, they do not force the
2851 // structure to be passed in memory even if unaligned, and
2852 // therefore they can straddle an eightbyte.
2853 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002854 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002855 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002856 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002857
2858 uint64_t EB_Lo = Offset / 64;
2859 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002860
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002861 if (EB_Lo) {
2862 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2863 FieldLo = NoClass;
2864 FieldHi = Integer;
2865 } else {
2866 FieldLo = Integer;
2867 FieldHi = EB_Hi ? Integer : NoClass;
2868 }
2869 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002870 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002871 Lo = merge(Lo, FieldLo);
2872 Hi = merge(Hi, FieldHi);
2873 if (Lo == Memory || Hi == Memory)
2874 break;
2875 }
2876
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002877 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002878 }
2879}
2880
Chris Lattner22a931e2010-06-29 06:01:59 +00002881ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002882 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2883 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002884 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002885 // Treat an enum type as its underlying type.
2886 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2887 Ty = EnumTy->getDecl()->getIntegerType();
2888
Alex Bradburye41a5e22018-01-12 20:08:16 +00002889 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2890 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002891 }
2892
John McCall7f416cc2015-09-08 08:05:57 +00002893 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002894}
2895
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002896bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2897 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2898 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002899 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002900 if (Size <= 64 || Size > LargestVector)
2901 return true;
2902 }
2903
2904 return false;
2905}
2906
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002907ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2908 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002909 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2910 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002911 //
2912 // This assumption is optimistic, as there could be free registers available
2913 // when we need to pass this argument in memory, and LLVM could try to pass
2914 // the argument in the free register. This does not seem to happen currently,
2915 // but this code would be much safer if we could mark the argument with
2916 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002917 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002918 // Treat an enum type as its underlying type.
2919 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2920 Ty = EnumTy->getDecl()->getIntegerType();
2921
Alex Bradburye41a5e22018-01-12 20:08:16 +00002922 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2923 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002924 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002925
Mark Lacey3825e832013-10-06 01:33:34 +00002926 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002927 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002928
Chris Lattner44c2b902011-05-22 23:21:23 +00002929 // Compute the byval alignment. We specify the alignment of the byval in all
2930 // cases so that the mid-level optimizer knows the alignment of the byval.
2931 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002932
2933 // Attempt to avoid passing indirect results using byval when possible. This
2934 // is important for good codegen.
2935 //
2936 // We do this by coercing the value into a scalar type which the backend can
2937 // handle naturally (i.e., without using byval).
2938 //
2939 // For simplicity, we currently only do this when we have exhausted all of the
2940 // free integer registers. Doing this when there are free integer registers
2941 // would require more care, as we would have to ensure that the coerced value
2942 // did not claim the unused register. That would require either reording the
2943 // arguments to the function (so that any subsequent inreg values came first),
2944 // or only doing this optimization when there were no following arguments that
2945 // might be inreg.
2946 //
2947 // We currently expect it to be rare (particularly in well written code) for
2948 // arguments to be passed on the stack when there are still free integer
2949 // registers available (this would typically imply large structs being passed
2950 // by value), so this seems like a fair tradeoff for now.
2951 //
2952 // We can revisit this if the backend grows support for 'onstack' parameter
2953 // attributes. See PR12193.
2954 if (freeIntRegs == 0) {
2955 uint64_t Size = getContext().getTypeSize(Ty);
2956
2957 // If this type fits in an eightbyte, coerce it into the matching integral
2958 // type, which will end up on the stack (with alignment 8).
2959 if (Align == 8 && Size <= 64)
2960 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2961 Size));
2962 }
2963
John McCall7f416cc2015-09-08 08:05:57 +00002964 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002965}
2966
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002967/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2968/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002969llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002970 // Wrapper structs/arrays that only contain vectors are passed just like
2971 // vectors; strip them off if present.
2972 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2973 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002974
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002975 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002976 if (isa<llvm::VectorType>(IRType) ||
2977 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002978 return IRType;
2979
2980 // We couldn't find the preferred IR vector type for 'Ty'.
2981 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002982 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002983
2984 // Return a LLVM IR vector type based on the size of 'Ty'.
2985 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2986 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002987}
2988
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002989/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2990/// is known to either be off the end of the specified type or being in
2991/// alignment padding. The user type specified is known to be at most 128 bits
2992/// in size, and have passed through X86_64ABIInfo::classify with a successful
2993/// classification that put one of the two halves in the INTEGER class.
2994///
2995/// It is conservatively correct to return false.
2996static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2997 unsigned EndBit, ASTContext &Context) {
2998 // If the bytes being queried are off the end of the type, there is no user
2999 // data hiding here. This handles analysis of builtins, vectors and other
3000 // types that don't contain interesting padding.
3001 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3002 if (TySize <= StartBit)
3003 return true;
3004
Chris Lattner98076a22010-07-29 07:43:55 +00003005 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3006 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3007 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3008
3009 // Check each element to see if the element overlaps with the queried range.
3010 for (unsigned i = 0; i != NumElts; ++i) {
3011 // If the element is after the span we care about, then we're done..
3012 unsigned EltOffset = i*EltSize;
3013 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003014
Chris Lattner98076a22010-07-29 07:43:55 +00003015 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3016 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3017 EndBit-EltOffset, Context))
3018 return false;
3019 }
3020 // If it overlaps no elements, then it is safe to process as padding.
3021 return true;
3022 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003023
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003024 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3025 const RecordDecl *RD = RT->getDecl();
3026 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003027
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003028 // If this is a C++ record, check the bases first.
3029 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003030 for (const auto &I : CXXRD->bases()) {
3031 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003032 "Unexpected base class!");
3033 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003034 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003035
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003036 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003037 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003038 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003039
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003040 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003041 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003042 EndBit-BaseOffset, Context))
3043 return false;
3044 }
3045 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003046
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003047 // Verify that no field has data that overlaps the region of interest. Yes
3048 // this could be sped up a lot by being smarter about queried fields,
3049 // however we're only looking at structs up to 16 bytes, so we don't care
3050 // much.
3051 unsigned idx = 0;
3052 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3053 i != e; ++i, ++idx) {
3054 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003055
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003056 // If we found a field after the region we care about, then we're done.
3057 if (FieldOffset >= EndBit) break;
3058
3059 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3060 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3061 Context))
3062 return false;
3063 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003064
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003065 // If nothing in this record overlapped the area of interest, then we're
3066 // clean.
3067 return true;
3068 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003069
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003070 return false;
3071}
3072
Chris Lattnere556a712010-07-29 18:39:32 +00003073/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3074/// float member at the specified offset. For example, {int,{float}} has a
3075/// float at offset 4. It is conservatively correct for this routine to return
3076/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003077static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003078 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003079 // Base case if we find a float.
3080 if (IROffset == 0 && IRType->isFloatTy())
3081 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003082
Chris Lattnere556a712010-07-29 18:39:32 +00003083 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003084 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003085 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3086 unsigned Elt = SL->getElementContainingOffset(IROffset);
3087 IROffset -= SL->getElementOffset(Elt);
3088 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3089 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003090
Chris Lattnere556a712010-07-29 18:39:32 +00003091 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003092 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3093 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003094 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3095 IROffset -= IROffset/EltSize*EltSize;
3096 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3097 }
3098
3099 return false;
3100}
3101
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003102
3103/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3104/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003105llvm::Type *X86_64ABIInfo::
3106GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003107 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003108 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003109 // pass as float if the last 4 bytes is just padding. This happens for
3110 // structs that contain 3 floats.
3111 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3112 SourceOffset*8+64, getContext()))
3113 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003114
Chris Lattnere556a712010-07-29 18:39:32 +00003115 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3116 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3117 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003118 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3119 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003120 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003121
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003122 return llvm::Type::getDoubleTy(getVMContext());
3123}
3124
3125
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003126/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3127/// an 8-byte GPR. This means that we either have a scalar or we are talking
3128/// about the high or low part of an up-to-16-byte struct. This routine picks
3129/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003130/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3131/// etc).
3132///
3133/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3134/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3135/// the 8-byte value references. PrefType may be null.
3136///
Alp Toker9907f082014-07-09 14:06:35 +00003137/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003138/// an offset into this that we're processing (which is always either 0 or 8).
3139///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003140llvm::Type *X86_64ABIInfo::
3141GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003142 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003143 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3144 // returning an 8-byte unit starting with it. See if we can safely use it.
3145 if (IROffset == 0) {
3146 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003147 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3148 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003149 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003150
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003151 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3152 // goodness in the source type is just tail padding. This is allowed to
3153 // kick in for struct {double,int} on the int, but not on
3154 // struct{double,int,int} because we wouldn't return the second int. We
3155 // have to do this analysis on the source type because we can't depend on
3156 // unions being lowered a specific way etc.
3157 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003158 IRType->isIntegerTy(32) ||
3159 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3160 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3161 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003162
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003163 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3164 SourceOffset*8+64, getContext()))
3165 return IRType;
3166 }
3167 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003168
Chris Lattner2192fe52011-07-18 04:24:23 +00003169 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003170 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003171 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003172 if (IROffset < SL->getSizeInBytes()) {
3173 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3174 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003175
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003176 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3177 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003178 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003179 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003180
Chris Lattner2192fe52011-07-18 04:24:23 +00003181 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003182 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003183 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003184 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003185 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3186 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003187 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003188
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003189 // Okay, we don't have any better idea of what to pass, so we pass this in an
3190 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003191 unsigned TySizeInBytes =
3192 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003193
Chris Lattner3f763422010-07-29 17:34:39 +00003194 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003195
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003196 // It is always safe to classify this as an integer type up to i64 that
3197 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003198 return llvm::IntegerType::get(getVMContext(),
3199 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003200}
3201
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003202
3203/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3204/// be used as elements of a two register pair to pass or return, return a
3205/// first class aggregate to represent them. For example, if the low part of
3206/// a by-value argument should be passed as i32* and the high part as float,
3207/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003208static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003209GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003210 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003211 // In order to correctly satisfy the ABI, we need to the high part to start
3212 // at offset 8. If the high and low parts we inferred are both 4-byte types
3213 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3214 // the second element at offset 8. Check for this:
3215 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3216 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003217 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003218 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003219
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003220 // To handle this, we have to increase the size of the low part so that the
3221 // second element will start at an 8 byte offset. We can't increase the size
3222 // of the second element because it might make us access off the end of the
3223 // struct.
3224 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003225 // There are usually two sorts of types the ABI generation code can produce
3226 // for the low part of a pair that aren't 8 bytes in size: float or
3227 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3228 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003229 // Promote these to a larger type.
3230 if (Lo->isFloatTy())
3231 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3232 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003233 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3234 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003235 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3236 }
3237 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003238
Serge Guelton1d993272017-05-09 19:31:30 +00003239 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003240
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003241 // Verify that the second element is at an 8-byte offset.
3242 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3243 "Invalid x86-64 argument pair!");
3244 return Result;
3245}
3246
Chris Lattner31faff52010-07-28 23:06:14 +00003247ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003248classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003249 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3250 // classification algorithm.
3251 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003252 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003253
3254 // Check some invariants.
3255 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003256 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3257
Craig Topper8a13c412014-05-21 05:09:00 +00003258 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003259 switch (Lo) {
3260 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003261 if (Hi == NoClass)
3262 return ABIArgInfo::getIgnore();
3263 // If the low part is just padding, it takes no register, leave ResType
3264 // null.
3265 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3266 "Unknown missing lo part");
3267 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003268
3269 case SSEUp:
3270 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003271 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003272
3273 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3274 // hidden argument.
3275 case Memory:
3276 return getIndirectReturnResult(RetTy);
3277
3278 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3279 // available register of the sequence %rax, %rdx is used.
3280 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003281 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003282
Chris Lattner1f3a0632010-07-29 21:42:50 +00003283 // If we have a sign or zero extended integer, make sure to return Extend
3284 // so that the parameter gets the right LLVM IR attributes.
3285 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3286 // Treat an enum type as its underlying type.
3287 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3288 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003289
Chris Lattner1f3a0632010-07-29 21:42:50 +00003290 if (RetTy->isIntegralOrEnumerationType() &&
3291 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003292 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003293 }
Chris Lattner31faff52010-07-28 23:06:14 +00003294 break;
3295
3296 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3297 // available SSE register of the sequence %xmm0, %xmm1 is used.
3298 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003299 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003300 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003301
3302 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3303 // returned on the X87 stack in %st0 as 80-bit x87 number.
3304 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003305 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003306 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003307
3308 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3309 // part of the value is returned in %st0 and the imaginary part in
3310 // %st1.
3311 case ComplexX87:
3312 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003313 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003314 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003315 break;
3316 }
3317
Craig Topper8a13c412014-05-21 05:09:00 +00003318 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003319 switch (Hi) {
3320 // Memory was handled previously and X87 should
3321 // never occur as a hi class.
3322 case Memory:
3323 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003324 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003325
3326 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003327 case NoClass:
3328 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003329
Chris Lattner52b3c132010-09-01 00:20:33 +00003330 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003331 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003332 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3333 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003334 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003335 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003336 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003337 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3338 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003339 break;
3340
3341 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003342 // is passed in the next available eightbyte chunk if the last used
3343 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003344 //
Chris Lattner57540c52011-04-15 05:22:18 +00003345 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003346 case SSEUp:
3347 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003348 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003349 break;
3350
3351 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3352 // returned together with the previous X87 value in %st0.
3353 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003354 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003355 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003356 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003357 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003358 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003359 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003360 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3361 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003362 }
Chris Lattner31faff52010-07-28 23:06:14 +00003363 break;
3364 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003365
Chris Lattner52b3c132010-09-01 00:20:33 +00003366 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003367 // known to pass in the high eightbyte of the result. We do this by forming a
3368 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003369 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003370 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003371
Chris Lattner1f3a0632010-07-29 21:42:50 +00003372 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003373}
3374
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003375ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003376 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3377 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003378 const
3379{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003380 Ty = useFirstFieldIfTransparentUnion(Ty);
3381
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003382 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003383 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003384
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003385 // Check some invariants.
3386 // FIXME: Enforce these by construction.
3387 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003388 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3389
3390 neededInt = 0;
3391 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003392 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003393 switch (Lo) {
3394 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003395 if (Hi == NoClass)
3396 return ABIArgInfo::getIgnore();
3397 // If the low part is just padding, it takes no register, leave ResType
3398 // null.
3399 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3400 "Unknown missing lo part");
3401 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003402
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003403 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3404 // on the stack.
3405 case Memory:
3406
3407 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3408 // COMPLEX_X87, it is passed in memory.
3409 case X87:
3410 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003411 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003412 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003413 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003414
3415 case SSEUp:
3416 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003417 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003418
3419 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3420 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3421 // and %r9 is used.
3422 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003423 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003424
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003425 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003426 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003427
3428 // If we have a sign or zero extended integer, make sure to return Extend
3429 // so that the parameter gets the right LLVM IR attributes.
3430 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3431 // Treat an enum type as its underlying type.
3432 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3433 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003434
Chris Lattner1f3a0632010-07-29 21:42:50 +00003435 if (Ty->isIntegralOrEnumerationType() &&
3436 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003437 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003438 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003439
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003440 break;
3441
3442 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3443 // available SSE register is used, the registers are taken in the
3444 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003445 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003446 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003447 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003448 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003449 break;
3450 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003451 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003452
Craig Topper8a13c412014-05-21 05:09:00 +00003453 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003454 switch (Hi) {
3455 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003456 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003457 // which is passed in memory.
3458 case Memory:
3459 case X87:
3460 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003461 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003462
3463 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003464
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003465 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003466 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003467 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003468 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003469
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003470 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3471 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003472 break;
3473
3474 // X87Up generally doesn't occur here (long double is passed in
3475 // memory), except in situations involving unions.
3476 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003477 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003478 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003479
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003480 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3481 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003482
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003483 ++neededSSE;
3484 break;
3485
3486 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3487 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003488 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003489 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003490 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003491 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003492 break;
3493 }
3494
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003495 // If a high part was specified, merge it together with the low part. It is
3496 // known to pass in the high eightbyte of the result. We do this by forming a
3497 // first class struct aggregate with the high and low part: {low, high}
3498 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003499 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003500
Chris Lattner1f3a0632010-07-29 21:42:50 +00003501 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003502}
3503
Erich Keane757d3172016-11-02 18:29:35 +00003504ABIArgInfo
3505X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3506 unsigned &NeededSSE) const {
3507 auto RT = Ty->getAs<RecordType>();
3508 assert(RT && "classifyRegCallStructType only valid with struct types");
3509
3510 if (RT->getDecl()->hasFlexibleArrayMember())
3511 return getIndirectReturnResult(Ty);
3512
3513 // Sum up bases
3514 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3515 if (CXXRD->isDynamicClass()) {
3516 NeededInt = NeededSSE = 0;
3517 return getIndirectReturnResult(Ty);
3518 }
3519
3520 for (const auto &I : CXXRD->bases())
3521 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3522 .isIndirect()) {
3523 NeededInt = NeededSSE = 0;
3524 return getIndirectReturnResult(Ty);
3525 }
3526 }
3527
3528 // Sum up members
3529 for (const auto *FD : RT->getDecl()->fields()) {
3530 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3531 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3532 .isIndirect()) {
3533 NeededInt = NeededSSE = 0;
3534 return getIndirectReturnResult(Ty);
3535 }
3536 } else {
3537 unsigned LocalNeededInt, LocalNeededSSE;
3538 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3539 LocalNeededSSE, true)
3540 .isIndirect()) {
3541 NeededInt = NeededSSE = 0;
3542 return getIndirectReturnResult(Ty);
3543 }
3544 NeededInt += LocalNeededInt;
3545 NeededSSE += LocalNeededSSE;
3546 }
3547 }
3548
3549 return ABIArgInfo::getDirect();
3550}
3551
3552ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3553 unsigned &NeededInt,
3554 unsigned &NeededSSE) const {
3555
3556 NeededInt = 0;
3557 NeededSSE = 0;
3558
3559 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3560}
3561
Chris Lattner22326a12010-07-29 02:31:05 +00003562void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003563
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003564 const unsigned CallingConv = FI.getCallingConvention();
3565 // It is possible to force Win64 calling convention on any x86_64 target by
3566 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3567 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3568 if (CallingConv == llvm::CallingConv::Win64) {
Reid Kleckner3fd3de12019-06-20 20:07:20 +00003569 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003570 Win64ABIInfo.computeInfo(FI);
3571 return;
3572 }
3573
3574 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003575
3576 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003577 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3578 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3579 unsigned NeededInt, NeededSSE;
3580
Akira Hatanakad791e922018-03-19 17:38:40 +00003581 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Erich Keanede1b2a92017-07-21 18:50:36 +00003582 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3583 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3584 FI.getReturnInfo() =
3585 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3586 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3587 FreeIntRegs -= NeededInt;
3588 FreeSSERegs -= NeededSSE;
3589 } else {
3590 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3591 }
3592 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3593 // Complex Long Double Type is passed in Memory when Regcall
3594 // calling convention is used.
3595 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3596 if (getContext().getCanonicalType(CT->getElementType()) ==
3597 getContext().LongDoubleTy)
3598 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3599 } else
3600 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3601 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003602
3603 // If the return value is indirect, then the hidden argument is consuming one
3604 // integer register.
3605 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003606 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003607
Peter Collingbournef7706832014-12-12 23:41:25 +00003608 // The chain argument effectively gives us another free register.
3609 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003610 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003611
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003612 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003613 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3614 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003615 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003616 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003617 it != ie; ++it, ++ArgNo) {
3618 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003619
Erich Keane757d3172016-11-02 18:29:35 +00003620 if (IsRegCall && it->type->isStructureOrClassType())
3621 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3622 else
3623 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3624 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003625
3626 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3627 // eightbyte of an argument, the whole argument is passed on the
3628 // stack. If registers have already been assigned for some
3629 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003630 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3631 FreeIntRegs -= NeededInt;
3632 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003633 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003634 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003635 }
3636 }
3637}
3638
John McCall7f416cc2015-09-08 08:05:57 +00003639static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3640 Address VAListAddr, QualType Ty) {
James Y Knight751fe282019-02-09 22:22:28 +00003641 Address overflow_arg_area_p =
3642 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003643 llvm::Value *overflow_arg_area =
3644 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3645
3646 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3647 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003648 // It isn't stated explicitly in the standard, but in practice we use
3649 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003650 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3651 if (Align > CharUnits::fromQuantity(8)) {
3652 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3653 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003654 }
3655
3656 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003657 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003658 llvm::Value *Res =
3659 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003660 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003661
3662 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3663 // l->overflow_arg_area + sizeof(type).
3664 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3665 // an 8 byte boundary.
3666
3667 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003668 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003669 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003670 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3671 "overflow_arg_area.next");
3672 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3673
3674 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003675 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003676}
3677
John McCall7f416cc2015-09-08 08:05:57 +00003678Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3679 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003680 // Assume that va_list type is correct; should be pointer to LLVM type:
3681 // struct {
3682 // i32 gp_offset;
3683 // i32 fp_offset;
3684 // i8* overflow_arg_area;
3685 // i8* reg_save_area;
3686 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003687 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003688
John McCall7f416cc2015-09-08 08:05:57 +00003689 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003690 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003691 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003692
3693 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3694 // in the registers. If not go to step 7.
3695 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003696 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003697
3698 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3699 // general purpose registers needed to pass type and num_fp to hold
3700 // the number of floating point registers needed.
3701
3702 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3703 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3704 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3705 //
3706 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3707 // register save space).
3708
Craig Topper8a13c412014-05-21 05:09:00 +00003709 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003710 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3711 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003712 if (neededInt) {
James Y Knight751fe282019-02-09 22:22:28 +00003713 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003714 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003715 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3716 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003717 }
3718
3719 if (neededSSE) {
James Y Knight751fe282019-02-09 22:22:28 +00003720 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003721 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3722 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003723 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3724 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003725 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3726 }
3727
3728 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3729 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3730 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3731 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3732
3733 // Emit code to load the value if it was passed in registers.
3734
3735 CGF.EmitBlock(InRegBlock);
3736
3737 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3738 // an offset of l->gp_offset and/or l->fp_offset. This may require
3739 // copying to a temporary location in case the parameter is passed
3740 // in different register classes or requires an alignment greater
3741 // than 8 for general purpose registers and 16 for XMM registers.
3742 //
3743 // FIXME: This really results in shameful code when we end up needing to
3744 // collect arguments from different places; often what should result in a
3745 // simple assembling of a structure from scattered addresses has many more
3746 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003747 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003748 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
James Y Knight751fe282019-02-09 22:22:28 +00003749 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00003750
3751 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003752 if (neededInt && neededSSE) {
3753 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003754 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003755 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003756 Address Tmp = CGF.CreateMemTemp(Ty);
3757 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003758 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003759 llvm::Type *TyLo = ST->getElementType(0);
3760 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003761 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003762 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003763 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3764 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003765 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3766 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003767 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3768 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003769
John McCall7f416cc2015-09-08 08:05:57 +00003770 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003771 // FIXME: Our choice of alignment here and below is probably pessimistic.
3772 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3773 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3774 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
James Y Knight751fe282019-02-09 22:22:28 +00003775 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
John McCall7f416cc2015-09-08 08:05:57 +00003776
3777 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003778 V = CGF.Builder.CreateAlignedLoad(
3779 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3780 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
James Y Knight751fe282019-02-09 22:22:28 +00003781 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
John McCall7f416cc2015-09-08 08:05:57 +00003782
3783 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003784 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003785 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3786 CharUnits::fromQuantity(8));
3787 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003788
3789 // Copy to a temporary if necessary to ensure the appropriate alignment.
3790 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003791 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003792 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003793 CharUnits TyAlign = SizeAlign.second;
3794
3795 // Copy into a temporary if the type is more aligned than the
3796 // register save area.
3797 if (TyAlign.getQuantity() > 8) {
3798 Address Tmp = CGF.CreateMemTemp(Ty);
3799 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003800 RegAddr = Tmp;
3801 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003802
Chris Lattner0cf24192010-06-28 20:05:43 +00003803 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003804 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3805 CharUnits::fromQuantity(16));
3806 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003807 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003808 assert(neededSSE == 2 && "Invalid number of needed registers!");
3809 // SSE registers are spaced 16 bytes apart in the register save
3810 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003811 // The ABI isn't explicit about this, but it seems reasonable
3812 // to assume that the slots are 16-byte aligned, since the stack is
3813 // naturally 16-byte aligned and the prologue is expected to store
3814 // all the SSE registers to the RSA.
3815 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3816 CharUnits::fromQuantity(16));
3817 Address RegAddrHi =
3818 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3819 CharUnits::fromQuantity(16));
Erich Keane24e68402018-02-02 15:53:35 +00003820 llvm::Type *ST = AI.canHaveCoerceToType()
3821 ? AI.getCoerceToType()
3822 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003823 llvm::Value *V;
3824 Address Tmp = CGF.CreateMemTemp(Ty);
3825 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Erich Keane24e68402018-02-02 15:53:35 +00003826 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3827 RegAddrLo, ST->getStructElementType(0)));
James Y Knight751fe282019-02-09 22:22:28 +00003828 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
Erich Keane24e68402018-02-02 15:53:35 +00003829 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3830 RegAddrHi, ST->getStructElementType(1)));
James Y Knight751fe282019-02-09 22:22:28 +00003831 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
John McCall7f416cc2015-09-08 08:05:57 +00003832
3833 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003834 }
3835
3836 // AMD64-ABI 3.5.7p5: Step 5. Set:
3837 // l->gp_offset = l->gp_offset + num_gp * 8
3838 // l->fp_offset = l->fp_offset + num_fp * 16.
3839 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003840 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003841 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3842 gp_offset_p);
3843 }
3844 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003845 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003846 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3847 fp_offset_p);
3848 }
3849 CGF.EmitBranch(ContBlock);
3850
3851 // Emit code to load the value if it was passed in memory.
3852
3853 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003854 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003855
3856 // Return the appropriate result.
3857
3858 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003859 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3860 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003861 return ResAddr;
3862}
3863
Charles Davisc7d5c942015-09-17 20:55:33 +00003864Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3865 QualType Ty) const {
3866 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3867 CGF.getContext().getTypeInfoInChars(Ty),
3868 CharUnits::fromQuantity(8),
3869 /*allowHigherAlign*/ false);
3870}
3871
Erich Keane521ed962017-01-05 00:20:51 +00003872ABIArgInfo
3873WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3874 const ABIArgInfo &current) const {
3875 // Assumes vectorCall calling convention.
3876 const Type *Base = nullptr;
3877 uint64_t NumElts = 0;
3878
3879 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3880 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3881 FreeSSERegs -= NumElts;
3882 return getDirectX86Hva();
3883 }
3884 return current;
3885}
3886
Reid Kleckner80944df2014-10-31 22:00:51 +00003887ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003888 bool IsReturnType, bool IsVectorCall,
3889 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003890
3891 if (Ty->isVoidType())
3892 return ABIArgInfo::getIgnore();
3893
3894 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3895 Ty = EnumTy->getDecl()->getIntegerType();
3896
Reid Kleckner80944df2014-10-31 22:00:51 +00003897 TypeInfo Info = getContext().getTypeInfo(Ty);
3898 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003899 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003900
Reid Kleckner9005f412014-05-02 00:51:20 +00003901 const RecordType *RT = Ty->getAs<RecordType>();
3902 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003903 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003904 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003905 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003906 }
3907
3908 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003909 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003910
Reid Kleckner9005f412014-05-02 00:51:20 +00003911 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003912
Reid Kleckner80944df2014-10-31 22:00:51 +00003913 const Type *Base = nullptr;
3914 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003915 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3916 // other targets.
3917 if ((IsVectorCall || IsRegCall) &&
3918 isHomogeneousAggregate(Ty, Base, NumElts)) {
3919 if (IsRegCall) {
3920 if (FreeSSERegs >= NumElts) {
3921 FreeSSERegs -= NumElts;
3922 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3923 return ABIArgInfo::getDirect();
3924 return ABIArgInfo::getExpand();
3925 }
3926 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3927 } else if (IsVectorCall) {
3928 if (FreeSSERegs >= NumElts &&
3929 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3930 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003931 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003932 } else if (IsReturnType) {
3933 return ABIArgInfo::getExpand();
3934 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3935 // HVAs are delayed and reclassified in the 2nd step.
3936 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3937 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003938 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003939 }
3940
Reid Klecknerec87fec2014-05-02 01:17:12 +00003941 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003942 // If the member pointer is represented by an LLVM int or ptr, pass it
3943 // directly.
3944 llvm::Type *LLTy = CGT.ConvertType(Ty);
3945 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3946 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003947 }
3948
Michael Kuperstein4f818702015-02-24 09:35:58 +00003949 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003950 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3951 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003952 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003953 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003954
Reid Kleckner9005f412014-05-02 00:51:20 +00003955 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003956 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003957 }
3958
Reid Kleckner08f64e92018-10-31 17:43:55 +00003959 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3960 switch (BT->getKind()) {
3961 case BuiltinType::Bool:
3962 // Bool type is always extended to the ABI, other builtin types are not
3963 // extended.
3964 return ABIArgInfo::getExtend(Ty);
3965
3966 case BuiltinType::LongDouble:
3967 // Mingw64 GCC uses the old 80 bit extended precision floating point
3968 // unit. It passes them indirectly through memory.
3969 if (IsMingw64) {
3970 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3971 if (LDF == &llvm::APFloat::x87DoubleExtended())
3972 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3973 }
3974 break;
3975
3976 case BuiltinType::Int128:
3977 case BuiltinType::UInt128:
3978 // If it's a parameter type, the normal ABI rule is that arguments larger
3979 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3980 // even though it isn't particularly efficient.
3981 if (!IsReturnType)
3982 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3983
3984 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3985 // Clang matches them for compatibility.
3986 return ABIArgInfo::getDirect(
3987 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
3988
3989 default:
3990 break;
3991 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003992 }
3993
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003994 return ABIArgInfo::getDirect();
3995}
3996
Erich Keane521ed962017-01-05 00:20:51 +00003997void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3998 unsigned FreeSSERegs,
3999 bool IsVectorCall,
4000 bool IsRegCall) const {
4001 unsigned Count = 0;
4002 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004003 // Vectorcall in x64 only permits the first 6 arguments to be passed
4004 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00004005 if (Count < VectorcallMaxParamNumAsReg)
4006 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4007 else {
4008 // Since these cannot be passed in registers, pretend no registers
4009 // are left.
4010 unsigned ZeroSSERegsAvail = 0;
4011 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4012 IsVectorCall, IsRegCall);
4013 }
4014 ++Count;
4015 }
4016
Erich Keane521ed962017-01-05 00:20:51 +00004017 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004018 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00004019 }
4020}
4021
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004022void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner3fd3de12019-06-20 20:07:20 +00004023 const unsigned CC = FI.getCallingConvention();
4024 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4025 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4026
4027 // If __attribute__((sysv_abi)) is in use, use the SysV argument
4028 // classification rules.
4029 if (CC == llvm::CallingConv::X86_64_SysV) {
4030 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4031 SysVABIInfo.computeInfo(FI);
4032 return;
4033 }
Reid Kleckner37abaca2014-05-09 22:46:15 +00004034
Erich Keane757d3172016-11-02 18:29:35 +00004035 unsigned FreeSSERegs = 0;
4036 if (IsVectorCall) {
4037 // We can use up to 4 SSE return registers with vectorcall.
4038 FreeSSERegs = 4;
4039 } else if (IsRegCall) {
4040 // RegCall gives us 16 SSE registers.
4041 FreeSSERegs = 16;
4042 }
4043
Reid Kleckner80944df2014-10-31 22:00:51 +00004044 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004045 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4046 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004047
Erich Keane757d3172016-11-02 18:29:35 +00004048 if (IsVectorCall) {
4049 // We can use up to 6 SSE register parameters with vectorcall.
4050 FreeSSERegs = 6;
4051 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004052 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004053 FreeSSERegs = 16;
4054 }
4055
Erich Keane521ed962017-01-05 00:20:51 +00004056 if (IsVectorCall) {
4057 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4058 } else {
4059 for (auto &I : FI.arguments())
4060 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4061 }
4062
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004063}
4064
John McCall7f416cc2015-09-08 08:05:57 +00004065Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4066 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004067
4068 bool IsIndirect = false;
4069
4070 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4071 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4072 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4073 uint64_t Width = getContext().getTypeSize(Ty);
4074 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4075 }
4076
4077 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004078 CGF.getContext().getTypeInfoInChars(Ty),
4079 CharUnits::fromQuantity(8),
4080 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004081}
Chris Lattner0cf24192010-06-28 20:05:43 +00004082
John McCallea8d8bb2010-03-11 00:10:12 +00004083// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004084namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004085/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4086class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004087 bool IsSoftFloatABI;
4088
4089 CharUnits getParamTypeAlignment(QualType Ty) const;
4090
John McCallea8d8bb2010-03-11 00:10:12 +00004091public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004092 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4093 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004094
John McCall7f416cc2015-09-08 08:05:57 +00004095 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4096 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004097};
4098
4099class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4100public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004101 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4102 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004103
Craig Topper4f12f102014-03-12 06:41:41 +00004104 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004105 // This is recovered from gcc output.
4106 return 1; // r1 is the dedicated stack pointer
4107 }
4108
4109 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004110 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004111};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004112}
John McCallea8d8bb2010-03-11 00:10:12 +00004113
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004114CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4115 // Complex types are passed just like their elements
4116 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4117 Ty = CTy->getElementType();
4118
4119 if (Ty->isVectorType())
4120 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4121 : 4);
4122
4123 // For single-element float/vector structs, we consider the whole type
4124 // to have the same alignment requirements as its single element.
4125 const Type *AlignTy = nullptr;
4126 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4127 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4128 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4129 (BT && BT->isFloatingPoint()))
4130 AlignTy = EltType;
4131 }
4132
4133 if (AlignTy)
4134 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4135 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004136}
John McCallea8d8bb2010-03-11 00:10:12 +00004137
James Y Knight29b5f082016-02-24 02:59:33 +00004138// TODO: this implementation is now likely redundant with
4139// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004140Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4141 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004142 if (getTarget().getTriple().isOSDarwin()) {
4143 auto TI = getContext().getTypeInfoInChars(Ty);
4144 TI.second = getParamTypeAlignment(Ty);
4145
4146 CharUnits SlotSize = CharUnits::fromQuantity(4);
4147 return emitVoidPtrVAArg(CGF, VAList, Ty,
4148 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4149 /*AllowHigherAlign=*/true);
4150 }
4151
Roman Divacky039b9702016-02-20 08:31:24 +00004152 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004153 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4154 // TODO: Implement this. For now ignore.
4155 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004156 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004157 }
4158
John McCall7f416cc2015-09-08 08:05:57 +00004159 // struct __va_list_tag {
4160 // unsigned char gpr;
4161 // unsigned char fpr;
4162 // unsigned short reserved;
4163 // void *overflow_arg_area;
4164 // void *reg_save_area;
4165 // };
4166
Roman Divacky8a12d842014-11-03 18:32:54 +00004167 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004168 bool isInt =
4169 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004170 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004171
4172 // All aggregates are passed indirectly? That doesn't seem consistent
4173 // with the argument-lowering code.
4174 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004175
4176 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004177
4178 // The calling convention either uses 1-2 GPRs or 1 FPR.
4179 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004180 if (isInt || IsSoftFloatABI) {
James Y Knight751fe282019-02-09 22:22:28 +00004181 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
John McCall7f416cc2015-09-08 08:05:57 +00004182 } else {
James Y Knight751fe282019-02-09 22:22:28 +00004183 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004184 }
John McCall7f416cc2015-09-08 08:05:57 +00004185
4186 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4187
4188 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004189 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004190 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4191 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4192 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004193
Eric Christopher7565e0d2015-05-29 23:09:49 +00004194 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004195 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004196
4197 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4198 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4199 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4200
4201 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4202
John McCall7f416cc2015-09-08 08:05:57 +00004203 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4204 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004205
John McCall7f416cc2015-09-08 08:05:57 +00004206 // Case 1: consume registers.
4207 Address RegAddr = Address::invalid();
4208 {
4209 CGF.EmitBlock(UsingRegs);
4210
James Y Knight751fe282019-02-09 22:22:28 +00004211 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
John McCall7f416cc2015-09-08 08:05:57 +00004212 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4213 CharUnits::fromQuantity(8));
4214 assert(RegAddr.getElementType() == CGF.Int8Ty);
4215
4216 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004217 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004218 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4219 CharUnits::fromQuantity(32));
4220 }
4221
4222 // Get the address of the saved value by scaling the number of
Fangrui Song6907ce22018-07-30 19:24:48 +00004223 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004224 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004225 llvm::Value *RegOffset =
4226 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4227 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4228 RegAddr.getPointer(), RegOffset),
4229 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4230 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4231
4232 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004233 NumRegs =
Fangrui Song6907ce22018-07-30 19:24:48 +00004234 Builder.CreateAdd(NumRegs,
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004235 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004236 Builder.CreateStore(NumRegs, NumRegsAddr);
4237
4238 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004239 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004240
John McCall7f416cc2015-09-08 08:05:57 +00004241 // Case 2: consume space in the overflow area.
4242 Address MemAddr = Address::invalid();
4243 {
4244 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004245
Roman Divacky039b9702016-02-20 08:31:24 +00004246 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4247
John McCall7f416cc2015-09-08 08:05:57 +00004248 // Everything in the overflow area is rounded up to a size of at least 4.
4249 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4250
4251 CharUnits Size;
4252 if (!isIndirect) {
4253 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004254 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004255 } else {
4256 Size = CGF.getPointerSize();
4257 }
4258
James Y Knight751fe282019-02-09 22:22:28 +00004259 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004260 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004261 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004262 // Round up address of argument to alignment
4263 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4264 if (Align > OverflowAreaAlign) {
4265 llvm::Value *Ptr = OverflowArea.getPointer();
4266 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4267 Align);
4268 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004269
John McCall7f416cc2015-09-08 08:05:57 +00004270 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4271
4272 // Increase the overflow area.
4273 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4274 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4275 CGF.EmitBranch(Cont);
4276 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004277
4278 CGF.EmitBlock(Cont);
4279
John McCall7f416cc2015-09-08 08:05:57 +00004280 // Merge the cases with a phi.
4281 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4282 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004283
John McCall7f416cc2015-09-08 08:05:57 +00004284 // Load the pointer if the argument was passed indirectly.
4285 if (isIndirect) {
4286 Result = Address(Builder.CreateLoad(Result, "aggr"),
4287 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004288 }
4289
4290 return Result;
4291}
4292
John McCallea8d8bb2010-03-11 00:10:12 +00004293bool
4294PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4295 llvm::Value *Address) const {
4296 // This is calculated from the LLVM and GCC tables and verified
4297 // against gcc output. AFAIK all ABIs use the same encoding.
4298
4299 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004300
Chris Lattnerece04092012-02-07 00:39:47 +00004301 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004302 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4303 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4304 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4305
4306 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004307 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004308
4309 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004310 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004311
4312 // 64-76 are various 4-byte special-purpose registers:
4313 // 64: mq
4314 // 65: lr
4315 // 66: ctr
4316 // 67: ap
4317 // 68-75 cr0-7
4318 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004319 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004320
4321 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004322 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004323
4324 // 109: vrsave
4325 // 110: vscr
4326 // 111: spe_acc
4327 // 112: spefscr
4328 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004329 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004330
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004331 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004332}
4333
Roman Divackyd966e722012-05-09 18:22:46 +00004334// PowerPC-64
4335
4336namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004337/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004338class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004339public:
4340 enum ABIKind {
4341 ELFv1 = 0,
4342 ELFv2
4343 };
4344
4345private:
4346 static const unsigned GPRBits = 64;
4347 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004348 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004349 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004350
4351 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4352 // will be passed in a QPX register.
4353 bool IsQPXVectorTy(const Type *Ty) const {
4354 if (!HasQPX)
4355 return false;
4356
4357 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4358 unsigned NumElements = VT->getNumElements();
4359 if (NumElements == 1)
4360 return false;
4361
4362 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4363 if (getContext().getTypeSize(Ty) <= 256)
4364 return true;
4365 } else if (VT->getElementType()->
4366 isSpecificBuiltinType(BuiltinType::Float)) {
4367 if (getContext().getTypeSize(Ty) <= 128)
4368 return true;
4369 }
4370 }
4371
4372 return false;
4373 }
4374
4375 bool IsQPXVectorTy(QualType Ty) const {
4376 return IsQPXVectorTy(Ty.getTypePtr());
4377 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004378
4379public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004380 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4381 bool SoftFloatABI)
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004382 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
Hal Finkel415c2a32016-10-02 02:10:45 +00004383 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004384
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004385 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004386 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004387
4388 ABIArgInfo classifyReturnType(QualType RetTy) const;
4389 ABIArgInfo classifyArgumentType(QualType Ty) const;
4390
Reid Klecknere9f6a712014-10-31 17:10:41 +00004391 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4392 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4393 uint64_t Members) const override;
4394
Bill Schmidt84d37792012-10-12 19:26:17 +00004395 // TODO: We can add more logic to computeInfo to improve performance.
4396 // Example: For aggregate arguments that fit in a register, we could
4397 // use getDirectInReg (as is done below for structs containing a single
4398 // floating-point value) to avoid pushing them to memory on function
4399 // entry. This would require changing the logic in PPCISelLowering
4400 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004401 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004402 if (!getCXXABI().classifyReturnType(FI))
4403 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004404 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004405 // We rely on the default argument classification for the most part.
4406 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004407 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004408 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004409 if (T) {
4410 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004411 if (IsQPXVectorTy(T) ||
4412 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004413 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004414 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004415 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004416 continue;
4417 }
4418 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004419 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004420 }
4421 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004422
John McCall7f416cc2015-09-08 08:05:57 +00004423 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4424 QualType Ty) const override;
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004425
4426 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4427 bool asReturnValue) const override {
4428 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4429 }
4430
4431 bool isSwiftErrorInRegister() const override {
4432 return false;
4433 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004434};
4435
4436class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004437
Bill Schmidt25cb3492012-10-03 19:18:57 +00004438public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004439 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004440 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4441 bool SoftFloatABI)
4442 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4443 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004444
Craig Topper4f12f102014-03-12 06:41:41 +00004445 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004446 // This is recovered from gcc output.
4447 return 1; // r1 is the dedicated stack pointer
4448 }
4449
4450 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004451 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004452};
4453
Roman Divackyd966e722012-05-09 18:22:46 +00004454class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4455public:
4456 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4457
Craig Topper4f12f102014-03-12 06:41:41 +00004458 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004459 // This is recovered from gcc output.
4460 return 1; // r1 is the dedicated stack pointer
4461 }
4462
4463 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004464 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004465};
4466
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004467}
Roman Divackyd966e722012-05-09 18:22:46 +00004468
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004469// Return true if the ABI requires Ty to be passed sign- or zero-
4470// extended to 64 bits.
4471bool
4472PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4473 // Treat an enum type as its underlying type.
4474 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4475 Ty = EnumTy->getDecl()->getIntegerType();
4476
4477 // Promotable integer types are required to be promoted by the ABI.
4478 if (Ty->isPromotableIntegerType())
4479 return true;
4480
4481 // In addition to the usual promotable integer types, we also need to
4482 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4483 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4484 switch (BT->getKind()) {
4485 case BuiltinType::Int:
4486 case BuiltinType::UInt:
4487 return true;
4488 default:
4489 break;
4490 }
4491
4492 return false;
4493}
4494
John McCall7f416cc2015-09-08 08:05:57 +00004495/// isAlignedParamType - Determine whether a type requires 16-byte or
4496/// higher alignment in the parameter area. Always returns at least 8.
4497CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004498 // Complex types are passed just like their elements.
4499 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4500 Ty = CTy->getElementType();
4501
4502 // Only vector types of size 16 bytes need alignment (larger types are
4503 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004504 if (IsQPXVectorTy(Ty)) {
4505 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004506 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004507
John McCall7f416cc2015-09-08 08:05:57 +00004508 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004509 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004510 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004511 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004512
4513 // For single-element float/vector structs, we consider the whole type
4514 // to have the same alignment requirements as its single element.
4515 const Type *AlignAsType = nullptr;
4516 const Type *EltType = isSingleElementStruct(Ty, getContext());
4517 if (EltType) {
4518 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004519 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004520 getContext().getTypeSize(EltType) == 128) ||
4521 (BT && BT->isFloatingPoint()))
4522 AlignAsType = EltType;
4523 }
4524
Ulrich Weigandb7122372014-07-21 00:48:09 +00004525 // Likewise for ELFv2 homogeneous aggregates.
4526 const Type *Base = nullptr;
4527 uint64_t Members = 0;
4528 if (!AlignAsType && Kind == ELFv2 &&
4529 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4530 AlignAsType = Base;
4531
Ulrich Weigand581badc2014-07-10 17:20:07 +00004532 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004533 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4534 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004535 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004536
John McCall7f416cc2015-09-08 08:05:57 +00004537 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004538 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004539 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004540 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004541
4542 // Otherwise, we only need alignment for any aggregate type that
4543 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004544 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4545 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004546 return CharUnits::fromQuantity(32);
4547 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004548 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004549
John McCall7f416cc2015-09-08 08:05:57 +00004550 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004551}
4552
Ulrich Weigandb7122372014-07-21 00:48:09 +00004553/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4554/// aggregate. Base is set to the base element type, and Members is set
4555/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004556bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4557 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004558 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4559 uint64_t NElements = AT->getSize().getZExtValue();
4560 if (NElements == 0)
4561 return false;
4562 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4563 return false;
4564 Members *= NElements;
4565 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4566 const RecordDecl *RD = RT->getDecl();
4567 if (RD->hasFlexibleArrayMember())
4568 return false;
4569
4570 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004571
4572 // If this is a C++ record, check the bases first.
4573 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4574 for (const auto &I : CXXRD->bases()) {
4575 // Ignore empty records.
4576 if (isEmptyRecord(getContext(), I.getType(), true))
4577 continue;
4578
4579 uint64_t FldMembers;
4580 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4581 return false;
4582
4583 Members += FldMembers;
4584 }
4585 }
4586
Ulrich Weigandb7122372014-07-21 00:48:09 +00004587 for (const auto *FD : RD->fields()) {
4588 // Ignore (non-zero arrays of) empty records.
4589 QualType FT = FD->getType();
4590 while (const ConstantArrayType *AT =
4591 getContext().getAsConstantArrayType(FT)) {
4592 if (AT->getSize().getZExtValue() == 0)
4593 return false;
4594 FT = AT->getElementType();
4595 }
4596 if (isEmptyRecord(getContext(), FT, true))
4597 continue;
4598
4599 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4600 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00004601 FD->isZeroLengthBitField(getContext()))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004602 continue;
4603
4604 uint64_t FldMembers;
4605 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4606 return false;
4607
4608 Members = (RD->isUnion() ?
4609 std::max(Members, FldMembers) : Members + FldMembers);
4610 }
4611
4612 if (!Base)
4613 return false;
4614
4615 // Ensure there is no padding.
4616 if (getContext().getTypeSize(Base) * Members !=
4617 getContext().getTypeSize(Ty))
4618 return false;
4619 } else {
4620 Members = 1;
4621 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4622 Members = 2;
4623 Ty = CT->getElementType();
4624 }
4625
Reid Klecknere9f6a712014-10-31 17:10:41 +00004626 // Most ABIs only support float, double, and some vector type widths.
4627 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004628 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004629
4630 // The base type must be the same for all members. Types that
4631 // agree in both total size and mode (float vs. vector) are
4632 // treated as being equivalent here.
4633 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004634 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004635 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004636 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4637 // so make sure to widen it explicitly.
4638 if (const VectorType *VT = Base->getAs<VectorType>()) {
4639 QualType EltTy = VT->getElementType();
4640 unsigned NumElements =
4641 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4642 Base = getContext()
4643 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4644 .getTypePtr();
4645 }
4646 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004647
4648 if (Base->isVectorType() != TyPtr->isVectorType() ||
4649 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4650 return false;
4651 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004652 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4653}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004654
Reid Klecknere9f6a712014-10-31 17:10:41 +00004655bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4656 // Homogeneous aggregates for ELFv2 must have base types of float,
4657 // double, long double, or 128-bit vectors.
4658 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4659 if (BT->getKind() == BuiltinType::Float ||
4660 BT->getKind() == BuiltinType::Double ||
Lei Huang449252d2018-07-05 04:32:01 +00004661 BT->getKind() == BuiltinType::LongDouble ||
4662 (getContext().getTargetInfo().hasFloat128Type() &&
4663 (BT->getKind() == BuiltinType::Float128))) {
Hal Finkel415c2a32016-10-02 02:10:45 +00004664 if (IsSoftFloatABI)
4665 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004666 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004667 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004668 }
4669 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004670 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004671 return true;
4672 }
4673 return false;
4674}
4675
4676bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4677 const Type *Base, uint64_t Members) const {
Lei Huang449252d2018-07-05 04:32:01 +00004678 // Vector and fp128 types require one register, other floating point types
4679 // require one or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004680 uint32_t NumRegs =
Lei Huang449252d2018-07-05 04:32:01 +00004681 ((getContext().getTargetInfo().hasFloat128Type() &&
4682 Base->isFloat128Type()) ||
4683 Base->isVectorType()) ? 1
4684 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004685
4686 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004687 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004688}
4689
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004690ABIArgInfo
4691PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004692 Ty = useFirstFieldIfTransparentUnion(Ty);
4693
Bill Schmidt90b22c92012-11-27 02:46:43 +00004694 if (Ty->isAnyComplexType())
4695 return ABIArgInfo::getDirect();
4696
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004697 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4698 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004699 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004700 uint64_t Size = getContext().getTypeSize(Ty);
4701 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004702 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004703 else if (Size < 128) {
4704 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4705 return ABIArgInfo::getDirect(CoerceTy);
4706 }
4707 }
4708
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004709 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004710 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004711 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004712
John McCall7f416cc2015-09-08 08:05:57 +00004713 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4714 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004715
4716 // ELFv2 homogeneous aggregates are passed as array types.
4717 const Type *Base = nullptr;
4718 uint64_t Members = 0;
4719 if (Kind == ELFv2 &&
4720 isHomogeneousAggregate(Ty, Base, Members)) {
4721 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4722 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4723 return ABIArgInfo::getDirect(CoerceTy);
4724 }
4725
Ulrich Weigand601957f2014-07-21 00:56:36 +00004726 // If an aggregate may end up fully in registers, we do not
4727 // use the ByVal method, but pass the aggregate as array.
4728 // This is usually beneficial since we avoid forcing the
4729 // back-end to store the argument to memory.
4730 uint64_t Bits = getContext().getTypeSize(Ty);
4731 if (Bits > 0 && Bits <= 8 * GPRBits) {
4732 llvm::Type *CoerceTy;
4733
4734 // Types up to 8 bytes are passed as integer type (which will be
4735 // properly aligned in the argument save area doubleword).
4736 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004737 CoerceTy =
4738 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004739 // Larger types are passed as arrays, with the base type selected
4740 // according to the required alignment in the save area.
4741 else {
4742 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004743 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004744 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4745 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4746 }
4747
4748 return ABIArgInfo::getDirect(CoerceTy);
4749 }
4750
Ulrich Weigandb7122372014-07-21 00:48:09 +00004751 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004752 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4753 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004754 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004755 }
4756
Alex Bradburye41a5e22018-01-12 20:08:16 +00004757 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4758 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004759}
4760
4761ABIArgInfo
4762PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4763 if (RetTy->isVoidType())
4764 return ABIArgInfo::getIgnore();
4765
Bill Schmidta3d121c2012-12-17 04:20:17 +00004766 if (RetTy->isAnyComplexType())
4767 return ABIArgInfo::getDirect();
4768
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004769 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4770 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004771 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004772 uint64_t Size = getContext().getTypeSize(RetTy);
4773 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004774 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004775 else if (Size < 128) {
4776 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4777 return ABIArgInfo::getDirect(CoerceTy);
4778 }
4779 }
4780
Ulrich Weigandb7122372014-07-21 00:48:09 +00004781 if (isAggregateTypeForABI(RetTy)) {
4782 // ELFv2 homogeneous aggregates are returned as array types.
4783 const Type *Base = nullptr;
4784 uint64_t Members = 0;
4785 if (Kind == ELFv2 &&
4786 isHomogeneousAggregate(RetTy, Base, Members)) {
4787 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4788 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4789 return ABIArgInfo::getDirect(CoerceTy);
4790 }
4791
4792 // ELFv2 small aggregates are returned in up to two registers.
4793 uint64_t Bits = getContext().getTypeSize(RetTy);
4794 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4795 if (Bits == 0)
4796 return ABIArgInfo::getIgnore();
4797
4798 llvm::Type *CoerceTy;
4799 if (Bits > GPRBits) {
4800 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004801 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004802 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004803 CoerceTy =
4804 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004805 return ABIArgInfo::getDirect(CoerceTy);
4806 }
4807
4808 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004809 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004810 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004811
Alex Bradburye41a5e22018-01-12 20:08:16 +00004812 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4813 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004814}
4815
Bill Schmidt25cb3492012-10-03 19:18:57 +00004816// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004817Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4818 QualType Ty) const {
4819 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4820 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004821
John McCall7f416cc2015-09-08 08:05:57 +00004822 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004823
Bill Schmidt924c4782013-01-14 17:45:36 +00004824 // If we have a complex type and the base type is smaller than 8 bytes,
4825 // the ABI calls for the real and imaginary parts to be right-adjusted
4826 // in separate doublewords. However, Clang expects us to produce a
4827 // pointer to a structure with the two parts packed tightly. So generate
4828 // loads of the real and imaginary parts relative to the va_list pointer,
4829 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004830 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4831 CharUnits EltSize = TypeInfo.first / 2;
4832 if (EltSize < SlotSize) {
4833 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4834 SlotSize * 2, SlotSize,
4835 SlotSize, /*AllowHigher*/ true);
4836
4837 Address RealAddr = Addr;
4838 Address ImagAddr = RealAddr;
4839 if (CGF.CGM.getDataLayout().isBigEndian()) {
4840 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4841 SlotSize - EltSize);
4842 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4843 2 * SlotSize - EltSize);
4844 } else {
4845 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4846 }
4847
4848 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4849 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4850 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4851 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4852 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4853
4854 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4855 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4856 /*init*/ true);
4857 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004858 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004859 }
4860
John McCall7f416cc2015-09-08 08:05:57 +00004861 // Otherwise, just use the general rule.
4862 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4863 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004864}
4865
4866static bool
4867PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4868 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004869 // This is calculated from the LLVM and GCC tables and verified
4870 // against gcc output. AFAIK all ABIs use the same encoding.
4871
4872 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4873
4874 llvm::IntegerType *i8 = CGF.Int8Ty;
4875 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4876 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4877 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4878
4879 // 0-31: r0-31, the 8-byte general-purpose registers
4880 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4881
4882 // 32-63: fp0-31, the 8-byte floating-point registers
4883 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4884
Hal Finkel84832a72016-08-30 02:38:34 +00004885 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004886 // 64: mq
4887 // 65: lr
4888 // 66: ctr
4889 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004890 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4891
4892 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004893 // 68-75 cr0-7
4894 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004895 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004896
4897 // 77-108: v0-31, the 16-byte vector registers
4898 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4899
4900 // 109: vrsave
4901 // 110: vscr
4902 // 111: spe_acc
4903 // 112: spefscr
4904 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004905 // 114: tfhar
4906 // 115: tfiar
4907 // 116: texasr
4908 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004909
4910 return false;
4911}
John McCallea8d8bb2010-03-11 00:10:12 +00004912
Bill Schmidt25cb3492012-10-03 19:18:57 +00004913bool
4914PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4915 CodeGen::CodeGenFunction &CGF,
4916 llvm::Value *Address) const {
4917
4918 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4919}
4920
4921bool
4922PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4923 llvm::Value *Address) const {
4924
4925 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4926}
4927
Chris Lattner0cf24192010-06-28 20:05:43 +00004928//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004929// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004930//===----------------------------------------------------------------------===//
4931
4932namespace {
4933
John McCall12f23522016-04-04 18:33:08 +00004934class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004935public:
4936 enum ABIKind {
4937 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004938 DarwinPCS,
4939 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004940 };
4941
4942private:
4943 ABIKind Kind;
4944
4945public:
John McCall12f23522016-04-04 18:33:08 +00004946 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4947 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004948
4949private:
4950 ABIKind getABIKind() const { return Kind; }
4951 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4952
4953 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004954 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004955 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4956 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4957 uint64_t Members) const override;
4958
Tim Northovera2ee4332014-03-29 15:09:45 +00004959 bool isIllegalVectorType(QualType Ty) const;
4960
David Blaikie1cbb9712014-11-14 19:09:44 +00004961 void computeInfo(CGFunctionInfo &FI) const override {
Akira Hatanakad791e922018-03-19 17:38:40 +00004962 if (!::classifyReturnType(getCXXABI(), FI, *this))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004963 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004964
Tim Northoverb047bfa2014-11-27 21:02:49 +00004965 for (auto &it : FI.arguments())
4966 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004967 }
4968
John McCall7f416cc2015-09-08 08:05:57 +00004969 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4970 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004971
John McCall7f416cc2015-09-08 08:05:57 +00004972 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4973 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004974
John McCall7f416cc2015-09-08 08:05:57 +00004975 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4976 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004977 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4978 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4979 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004980 }
John McCall12f23522016-04-04 18:33:08 +00004981
Martin Storsjo502de222017-07-13 17:59:14 +00004982 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4983 QualType Ty) const override;
4984
John McCall56331e22018-01-07 06:28:49 +00004985 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004986 bool asReturnValue) const override {
4987 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4988 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004989 bool isSwiftErrorInRegister() const override {
4990 return true;
4991 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004992
4993 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4994 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004995};
4996
Tim Northover573cbee2014-05-24 12:52:07 +00004997class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004998public:
Tim Northover573cbee2014-05-24 12:52:07 +00004999 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5000 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00005001
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005002 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005003 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00005004 }
5005
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005006 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5007 return 31;
5008 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005009
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005010 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005011
5012 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5013 CodeGen::CodeGenModule &CGM) const override {
5014 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5015 if (!FD)
5016 return;
5017 llvm::Function *Fn = cast<llvm::Function>(GV);
5018
5019 auto Kind = CGM.getCodeGenOpts().getSignReturnAddress();
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005020 if (Kind != CodeGenOptions::SignReturnAddressScope::None) {
5021 Fn->addFnAttr("sign-return-address",
5022 Kind == CodeGenOptions::SignReturnAddressScope::All
5023 ? "all"
5024 : "non-leaf");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005025
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005026 auto Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5027 Fn->addFnAttr("sign-return-address-key",
5028 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5029 ? "a_key"
5030 : "b_key");
5031 }
5032
5033 if (CGM.getCodeGenOpts().BranchTargetEnforcement)
5034 Fn->addFnAttr("branch-target-enforcement");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005035 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005036};
Martin Storsjo1c8af272017-07-20 05:47:06 +00005037
5038class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5039public:
5040 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5041 : AArch64TargetCodeGenInfo(CGT, K) {}
5042
Eli Friedman540be6d2018-10-26 01:31:57 +00005043 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5044 CodeGen::CodeGenModule &CGM) const override;
5045
Martin Storsjo1c8af272017-07-20 05:47:06 +00005046 void getDependentLibraryOption(llvm::StringRef Lib,
5047 llvm::SmallString<24> &Opt) const override {
5048 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5049 }
5050
5051 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5052 llvm::SmallString<32> &Opt) const override {
5053 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5054 }
5055};
Eli Friedman540be6d2018-10-26 01:31:57 +00005056
5057void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5058 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5059 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5060 if (GV->isDeclaration())
5061 return;
5062 addStackProbeTargetAttributes(D, GV, CGM);
5063}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005064}
Tim Northovera2ee4332014-03-29 15:09:45 +00005065
Tim Northoverb047bfa2014-11-27 21:02:49 +00005066ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00005067 Ty = useFirstFieldIfTransparentUnion(Ty);
5068
Tim Northovera2ee4332014-03-29 15:09:45 +00005069 // Handle illegal vector types here.
5070 if (isIllegalVectorType(Ty)) {
5071 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005072 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00005073 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005074 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5075 return ABIArgInfo::getDirect(ResType);
5076 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005077 if (Size <= 32) {
5078 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00005079 return ABIArgInfo::getDirect(ResType);
5080 }
5081 if (Size == 64) {
5082 llvm::Type *ResType =
5083 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00005084 return ABIArgInfo::getDirect(ResType);
5085 }
5086 if (Size == 128) {
5087 llvm::Type *ResType =
5088 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00005089 return ABIArgInfo::getDirect(ResType);
5090 }
John McCall7f416cc2015-09-08 08:05:57 +00005091 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005092 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005093
5094 if (!isAggregateTypeForABI(Ty)) {
5095 // Treat an enum type as its underlying type.
5096 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5097 Ty = EnumTy->getDecl()->getIntegerType();
5098
Tim Northovera2ee4332014-03-29 15:09:45 +00005099 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005100 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00005101 : ABIArgInfo::getDirect());
5102 }
5103
5104 // Structures with either a non-trivial destructor or a non-trivial
5105 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005106 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005107 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5108 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005109 }
5110
5111 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5112 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005113 uint64_t Size = getContext().getTypeSize(Ty);
5114 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5115 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005116 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5117 return ABIArgInfo::getIgnore();
5118
Tim Northover23bcad22017-05-05 22:36:06 +00005119 // GNU C mode. The only argument that gets ignored is an empty one with size
5120 // 0.
5121 if (IsEmpty && Size == 0)
5122 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005123 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5124 }
5125
5126 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005127 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005128 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005129 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005130 return ABIArgInfo::getDirect(
5131 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005132 }
5133
5134 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005135 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005136 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5137 // same size and alignment.
5138 if (getTarget().isRenderScriptTarget()) {
5139 return coerceToIntArray(Ty, getContext(), getVMContext());
5140 }
Momchil Velikov20208cc2018-07-30 17:48:23 +00005141 unsigned Alignment;
5142 if (Kind == AArch64ABIInfo::AAPCS) {
5143 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5144 Alignment = Alignment < 128 ? 64 : 128;
5145 } else {
5146 Alignment = getContext().getTypeAlign(Ty);
5147 }
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005148 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005149
Tim Northovera2ee4332014-03-29 15:09:45 +00005150 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5151 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005152 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005153 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5154 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5155 }
5156 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5157 }
5158
John McCall7f416cc2015-09-08 08:05:57 +00005159 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005160}
5161
Tim Northover573cbee2014-05-24 12:52:07 +00005162ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005163 if (RetTy->isVoidType())
5164 return ABIArgInfo::getIgnore();
5165
5166 // Large vector types should be returned via memory.
5167 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005168 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005169
5170 if (!isAggregateTypeForABI(RetTy)) {
5171 // Treat an enum type as its underlying type.
5172 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5173 RetTy = EnumTy->getDecl()->getIntegerType();
5174
Tim Northover4dab6982014-04-18 13:46:08 +00005175 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005176 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005177 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005178 }
5179
Tim Northover23bcad22017-05-05 22:36:06 +00005180 uint64_t Size = getContext().getTypeSize(RetTy);
5181 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005182 return ABIArgInfo::getIgnore();
5183
Craig Topper8a13c412014-05-21 05:09:00 +00005184 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005185 uint64_t Members = 0;
5186 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005187 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5188 return ABIArgInfo::getDirect();
5189
5190 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005191 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005192 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5193 // same size and alignment.
5194 if (getTarget().isRenderScriptTarget()) {
5195 return coerceToIntArray(RetTy, getContext(), getVMContext());
5196 }
Pete Cooper635b5092015-04-17 22:16:24 +00005197 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005198 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005199
5200 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5201 // For aggregates with 16-byte alignment, we use i128.
5202 if (Alignment < 128 && Size == 128) {
5203 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5204 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5205 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005206 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5207 }
5208
John McCall7f416cc2015-09-08 08:05:57 +00005209 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005210}
5211
Tim Northover573cbee2014-05-24 12:52:07 +00005212/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5213bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005214 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5215 // Check whether VT is legal.
5216 unsigned NumElements = VT->getNumElements();
5217 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005218 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005219 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005220 return true;
5221 return Size != 64 && (Size != 128 || NumElements == 1);
5222 }
5223 return false;
5224}
5225
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005226bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5227 llvm::Type *eltTy,
5228 unsigned elts) const {
5229 if (!llvm::isPowerOf2_32(elts))
5230 return false;
5231 if (totalSize.getQuantity() != 8 &&
5232 (totalSize.getQuantity() != 16 || elts == 1))
5233 return false;
5234 return true;
5235}
5236
Reid Klecknere9f6a712014-10-31 17:10:41 +00005237bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5238 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5239 // point type or a short-vector type. This is the same as the 32-bit ABI,
5240 // but with the difference that any floating-point type is allowed,
5241 // including __fp16.
5242 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5243 if (BT->isFloatingPoint())
5244 return true;
5245 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5246 unsigned VecSize = getContext().getTypeSize(VT);
5247 if (VecSize == 64 || VecSize == 128)
5248 return true;
5249 }
5250 return false;
5251}
5252
5253bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5254 uint64_t Members) const {
5255 return Members <= 4;
5256}
5257
John McCall7f416cc2015-09-08 08:05:57 +00005258Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005259 QualType Ty,
5260 CodeGenFunction &CGF) const {
5261 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005262 bool IsIndirect = AI.isIndirect();
5263
Tim Northoverb047bfa2014-11-27 21:02:49 +00005264 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5265 if (IsIndirect)
5266 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5267 else if (AI.getCoerceToType())
5268 BaseTy = AI.getCoerceToType();
5269
5270 unsigned NumRegs = 1;
5271 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5272 BaseTy = ArrTy->getElementType();
5273 NumRegs = ArrTy->getNumElements();
5274 }
5275 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5276
Tim Northovera2ee4332014-03-29 15:09:45 +00005277 // The AArch64 va_list type and handling is specified in the Procedure Call
5278 // Standard, section B.4:
5279 //
5280 // struct {
5281 // void *__stack;
5282 // void *__gr_top;
5283 // void *__vr_top;
5284 // int __gr_offs;
5285 // int __vr_offs;
5286 // };
5287
5288 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5289 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5290 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5291 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005292
John Brawn6c49f582019-05-22 11:42:54 +00005293 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5294 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005295
5296 Address reg_offs_p = Address::invalid();
5297 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005298 int reg_top_index;
John Brawn6c49f582019-05-22 11:42:54 +00005299 int RegSize = IsIndirect ? 8 : TySize.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005300 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005301 // 3 is the field number of __gr_offs
James Y Knight751fe282019-02-09 22:22:28 +00005302 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005303 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5304 reg_top_index = 1; // field number for __gr_top
Rui Ueyama83aa9792016-01-14 21:00:27 +00005305 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005306 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005307 // 4 is the field number of __vr_offs.
James Y Knight751fe282019-02-09 22:22:28 +00005308 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005309 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5310 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00005311 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005312 }
5313
5314 //=======================================
5315 // Find out where argument was passed
5316 //=======================================
5317
5318 // If reg_offs >= 0 we're already using the stack for this type of
5319 // argument. We don't want to keep updating reg_offs (in case it overflows,
5320 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5321 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005322 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005323 UsingStack = CGF.Builder.CreateICmpSGE(
5324 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5325
5326 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5327
5328 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005329 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005330 CGF.EmitBlock(MaybeRegBlock);
5331
5332 // Integer arguments may need to correct register alignment (for example a
5333 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5334 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005335 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5336 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005337
5338 reg_offs = CGF.Builder.CreateAdd(
5339 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5340 "align_regoffs");
5341 reg_offs = CGF.Builder.CreateAnd(
5342 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5343 "aligned_regoffs");
5344 }
5345
5346 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005347 // The fact that this is done unconditionally reflects the fact that
5348 // allocating an argument to the stack also uses up all the remaining
5349 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005350 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005351 NewOffset = CGF.Builder.CreateAdd(
5352 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5353 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5354
5355 // Now we're in a position to decide whether this argument really was in
5356 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005357 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005358 InRegs = CGF.Builder.CreateICmpSLE(
5359 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5360
5361 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5362
5363 //=======================================
5364 // Argument was in registers
5365 //=======================================
5366
5367 // Now we emit the code for if the argument was originally passed in
5368 // registers. First start the appropriate block:
5369 CGF.EmitBlock(InRegBlock);
5370
John McCall7f416cc2015-09-08 08:05:57 +00005371 llvm::Value *reg_top = nullptr;
James Y Knight751fe282019-02-09 22:22:28 +00005372 Address reg_top_p =
5373 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005374 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005375 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5376 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5377 Address RegAddr = Address::invalid();
5378 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005379
5380 if (IsIndirect) {
5381 // If it's been passed indirectly (actually a struct), whatever we find from
5382 // stored registers or on the stack will actually be a struct **.
5383 MemTy = llvm::PointerType::getUnqual(MemTy);
5384 }
5385
Craig Topper8a13c412014-05-21 05:09:00 +00005386 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005387 uint64_t NumMembers = 0;
5388 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005389 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005390 // Homogeneous aggregates passed in registers will have their elements split
5391 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5392 // qN+1, ...). We reload and store into a temporary local variable
5393 // contiguously.
5394 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005395 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005396 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5397 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005398 Address Tmp = CGF.CreateTempAlloca(HFATy,
5399 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005400
John McCall7f416cc2015-09-08 08:05:57 +00005401 // On big-endian platforms, the value will be right-aligned in its slot.
5402 int Offset = 0;
5403 if (CGF.CGM.getDataLayout().isBigEndian() &&
5404 BaseTyInfo.first.getQuantity() < 16)
5405 Offset = 16 - BaseTyInfo.first.getQuantity();
5406
Tim Northovera2ee4332014-03-29 15:09:45 +00005407 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005408 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5409 Address LoadAddr =
5410 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5411 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5412
James Y Knight751fe282019-02-09 22:22:28 +00005413 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00005414
5415 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5416 CGF.Builder.CreateStore(Elem, StoreAddr);
5417 }
5418
John McCall7f416cc2015-09-08 08:05:57 +00005419 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005420 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005421 // Otherwise the object is contiguous in memory.
5422
5423 // It might be right-aligned in its slot.
5424 CharUnits SlotSize = BaseAddr.getAlignment();
5425 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005426 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John Brawn6c49f582019-05-22 11:42:54 +00005427 TySize < SlotSize) {
5428 CharUnits Offset = SlotSize - TySize;
John McCall7f416cc2015-09-08 08:05:57 +00005429 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005430 }
5431
John McCall7f416cc2015-09-08 08:05:57 +00005432 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005433 }
5434
5435 CGF.EmitBranch(ContBlock);
5436
5437 //=======================================
5438 // Argument was on the stack
5439 //=======================================
5440 CGF.EmitBlock(OnStackBlock);
5441
James Y Knight751fe282019-02-09 22:22:28 +00005442 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
John McCall7f416cc2015-09-08 08:05:57 +00005443 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005444
John McCall7f416cc2015-09-08 08:05:57 +00005445 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005446 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005447 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5448 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005449
John McCall7f416cc2015-09-08 08:05:57 +00005450 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005451
John McCall7f416cc2015-09-08 08:05:57 +00005452 OnStackPtr = CGF.Builder.CreateAdd(
5453 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005454 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005455 OnStackPtr = CGF.Builder.CreateAnd(
5456 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005457 "align_stack");
5458
John McCall7f416cc2015-09-08 08:05:57 +00005459 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005460 }
John McCall7f416cc2015-09-08 08:05:57 +00005461 Address OnStackAddr(OnStackPtr,
5462 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005463
John McCall7f416cc2015-09-08 08:05:57 +00005464 // All stack slots are multiples of 8 bytes.
5465 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5466 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005467 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005468 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005469 else
John Brawn6c49f582019-05-22 11:42:54 +00005470 StackSize = TySize.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005471
John McCall7f416cc2015-09-08 08:05:57 +00005472 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005473 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005474 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005475
5476 // Write the new value of __stack for the next call to va_arg
5477 CGF.Builder.CreateStore(NewStack, stack_p);
5478
5479 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John Brawn6c49f582019-05-22 11:42:54 +00005480 TySize < StackSlotSize) {
5481 CharUnits Offset = StackSlotSize - TySize;
John McCall7f416cc2015-09-08 08:05:57 +00005482 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005483 }
5484
John McCall7f416cc2015-09-08 08:05:57 +00005485 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005486
5487 CGF.EmitBranch(ContBlock);
5488
5489 //=======================================
5490 // Tidy up
5491 //=======================================
5492 CGF.EmitBlock(ContBlock);
5493
John McCall7f416cc2015-09-08 08:05:57 +00005494 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5495 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005496
5497 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005498 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
John Brawn6c49f582019-05-22 11:42:54 +00005499 TyAlign);
Tim Northovera2ee4332014-03-29 15:09:45 +00005500
5501 return ResAddr;
5502}
5503
John McCall7f416cc2015-09-08 08:05:57 +00005504Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5505 CodeGenFunction &CGF) const {
5506 // The backend's lowering doesn't support va_arg for aggregates or
5507 // illegal vector types. Lower VAArg here for these cases and use
5508 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005509 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005510 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005511
John McCall7f416cc2015-09-08 08:05:57 +00005512 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005513
John McCall7f416cc2015-09-08 08:05:57 +00005514 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005515 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005516 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5517 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5518 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005519 }
5520
John McCall7f416cc2015-09-08 08:05:57 +00005521 // The size of the actual thing passed, which might end up just
5522 // being a pointer for indirect types.
5523 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5524
5525 // Arguments bigger than 16 bytes which aren't homogeneous
5526 // aggregates should be passed indirectly.
5527 bool IsIndirect = false;
5528 if (TyInfo.first.getQuantity() > 16) {
5529 const Type *Base = nullptr;
5530 uint64_t Members = 0;
5531 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005532 }
5533
John McCall7f416cc2015-09-08 08:05:57 +00005534 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5535 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005536}
5537
Martin Storsjo502de222017-07-13 17:59:14 +00005538Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5539 QualType Ty) const {
5540 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5541 CGF.getContext().getTypeInfoInChars(Ty),
5542 CharUnits::fromQuantity(8),
5543 /*allowHigherAlign*/ false);
5544}
5545
Tim Northovera2ee4332014-03-29 15:09:45 +00005546//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005547// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005548//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005549
5550namespace {
5551
John McCall12f23522016-04-04 18:33:08 +00005552class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005553public:
5554 enum ABIKind {
5555 APCS = 0,
5556 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005557 AAPCS_VFP = 2,
5558 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005559 };
5560
5561private:
5562 ABIKind Kind;
5563
5564public:
John McCall12f23522016-04-04 18:33:08 +00005565 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5566 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005567 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005568 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005569
John McCall3480ef22011-08-30 01:42:09 +00005570 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005571 switch (getTarget().getTriple().getEnvironment()) {
5572 case llvm::Triple::Android:
5573 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005574 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005575 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005576 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005577 case llvm::Triple::MuslEABI:
5578 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005579 return true;
5580 default:
5581 return false;
5582 }
John McCall3480ef22011-08-30 01:42:09 +00005583 }
5584
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005585 bool isEABIHF() const {
5586 switch (getTarget().getTriple().getEnvironment()) {
5587 case llvm::Triple::EABIHF:
5588 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005589 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005590 return true;
5591 default:
5592 return false;
5593 }
5594 }
5595
Daniel Dunbar020daa92009-09-12 01:00:39 +00005596 ABIKind getABIKind() const { return Kind; }
5597
Tim Northovera484bc02013-10-01 14:34:25 +00005598private:
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005599 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
5600 unsigned functionCallConv) const;
5601 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
5602 unsigned functionCallConv) const;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005603 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5604 uint64_t Members) const;
5605 ABIArgInfo coerceIllegalVector(QualType Ty) const;
Manman Renfef9e312012-10-16 19:18:39 +00005606 bool isIllegalVectorType(QualType Ty) const;
Mikhail Maltseva45292c2019-06-18 14:34:27 +00005607 bool containsAnyFP16Vectors(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005608
Reid Klecknere9f6a712014-10-31 17:10:41 +00005609 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5610 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5611 uint64_t Members) const override;
5612
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005613 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
5614
Craig Topper4f12f102014-03-12 06:41:41 +00005615 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005616
John McCall7f416cc2015-09-08 08:05:57 +00005617 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5618 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005619
5620 llvm::CallingConv::ID getLLVMDefaultCC() const;
5621 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005622 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005623
John McCall56331e22018-01-07 06:28:49 +00005624 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005625 bool asReturnValue) const override {
5626 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5627 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005628 bool isSwiftErrorInRegister() const override {
5629 return true;
5630 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005631 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5632 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005633};
5634
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005635class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5636public:
Chris Lattner2b037972010-07-29 02:01:43 +00005637 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5638 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005639
John McCall3480ef22011-08-30 01:42:09 +00005640 const ARMABIInfo &getABIInfo() const {
5641 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5642 }
5643
Craig Topper4f12f102014-03-12 06:41:41 +00005644 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005645 return 13;
5646 }
Roman Divackyc1617352011-05-18 19:36:54 +00005647
Craig Topper4f12f102014-03-12 06:41:41 +00005648 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005649 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005650 }
5651
Roman Divackyc1617352011-05-18 19:36:54 +00005652 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005653 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005654 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005655
5656 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005657 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005658 return false;
5659 }
John McCall3480ef22011-08-30 01:42:09 +00005660
Craig Topper4f12f102014-03-12 06:41:41 +00005661 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005662 if (getABIInfo().isEABI()) return 88;
5663 return TargetCodeGenInfo::getSizeOfUnwindException();
5664 }
Tim Northovera484bc02013-10-01 14:34:25 +00005665
Eric Christopher162c91c2015-06-05 22:03:00 +00005666 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005667 CodeGen::CodeGenModule &CGM) const override {
5668 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005669 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005670 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005671 if (!FD)
5672 return;
5673
5674 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5675 if (!Attr)
5676 return;
5677
5678 const char *Kind;
5679 switch (Attr->getInterrupt()) {
5680 case ARMInterruptAttr::Generic: Kind = ""; break;
5681 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5682 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5683 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5684 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5685 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5686 }
5687
5688 llvm::Function *Fn = cast<llvm::Function>(GV);
5689
5690 Fn->addFnAttr("interrupt", Kind);
5691
Tim Northover5627d392015-10-30 16:30:45 +00005692 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5693 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005694 return;
5695
5696 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5697 // however this is not necessarily true on taking any interrupt. Instruct
5698 // the backend to perform a realignment as part of the function prologue.
5699 llvm::AttrBuilder B;
5700 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005701 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005702 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005703};
5704
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005705class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005706public:
5707 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5708 : ARMTargetCodeGenInfo(CGT, K) {}
5709
Eric Christopher162c91c2015-06-05 22:03:00 +00005710 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005711 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005712
5713 void getDependentLibraryOption(llvm::StringRef Lib,
5714 llvm::SmallString<24> &Opt) const override {
5715 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5716 }
5717
5718 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5719 llvm::SmallString<32> &Opt) const override {
5720 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5721 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005722};
5723
Eric Christopher162c91c2015-06-05 22:03:00 +00005724void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005725 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5726 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5727 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005728 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00005729 addStackProbeTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005730}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005731}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005732
Chris Lattner22326a12010-07-29 02:31:05 +00005733void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakad791e922018-03-19 17:38:40 +00005734 if (!::classifyReturnType(getCXXABI(), FI, *this))
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005735 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
5736 FI.getCallingConvention());
Oliver Stannard405bded2014-02-11 09:25:50 +00005737
Tim Northoverbc784d12015-02-24 17:22:40 +00005738 for (auto &I : FI.arguments())
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005739 I.info = classifyArgumentType(I.type, FI.isVariadic(),
5740 FI.getCallingConvention());
5741
Daniel Dunbar020daa92009-09-12 01:00:39 +00005742
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005743 // Always honor user-specified calling convention.
5744 if (FI.getCallingConvention() != llvm::CallingConv::C)
5745 return;
5746
John McCall882987f2013-02-28 19:01:20 +00005747 llvm::CallingConv::ID cc = getRuntimeCC();
5748 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005749 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005750}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005751
John McCall882987f2013-02-28 19:01:20 +00005752/// Return the default calling convention that LLVM will use.
5753llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5754 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005755 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005756 return llvm::CallingConv::ARM_AAPCS_VFP;
5757 else if (isEABI())
5758 return llvm::CallingConv::ARM_AAPCS;
5759 else
5760 return llvm::CallingConv::ARM_APCS;
5761}
5762
5763/// Return the calling convention that our ABI would like us to use
5764/// as the C calling convention.
5765llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005766 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005767 case APCS: return llvm::CallingConv::ARM_APCS;
5768 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5769 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005770 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005771 }
John McCall882987f2013-02-28 19:01:20 +00005772 llvm_unreachable("bad ABI kind");
5773}
5774
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005775void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005776 assert(getRuntimeCC() == llvm::CallingConv::C);
5777
5778 // Don't muddy up the IR with a ton of explicit annotations if
5779 // they'd just match what LLVM will infer from the triple.
5780 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5781 if (abiCC != getLLVMDefaultCC())
5782 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005783}
5784
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005785ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5786 uint64_t Size = getContext().getTypeSize(Ty);
5787 if (Size <= 32) {
5788 llvm::Type *ResType =
5789 llvm::Type::getInt32Ty(getVMContext());
5790 return ABIArgInfo::getDirect(ResType);
5791 }
5792 if (Size == 64 || Size == 128) {
5793 llvm::Type *ResType = llvm::VectorType::get(
5794 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5795 return ABIArgInfo::getDirect(ResType);
5796 }
5797 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5798}
5799
5800ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5801 const Type *Base,
5802 uint64_t Members) const {
5803 assert(Base && "Base class should be set for homogeneous aggregate");
5804 // Base can be a floating-point or a vector.
5805 if (const VectorType *VT = Base->getAs<VectorType>()) {
5806 // FP16 vectors should be converted to integer vectors
Mikhail Maltseva45292c2019-06-18 14:34:27 +00005807 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005808 uint64_t Size = getContext().getTypeSize(VT);
5809 llvm::Type *NewVecTy = llvm::VectorType::get(
5810 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5811 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5812 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5813 }
5814 }
5815 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5816}
5817
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005818ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
5819 unsigned functionCallConv) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005820 // 6.1.2.1 The following argument types are VFP CPRCs:
5821 // A single-precision floating-point type (including promoted
5822 // half-precision types); A double-precision floating-point type;
5823 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5824 // with a Base Type of a single- or double-precision floating-point type,
5825 // 64-bit containerized vectors or 128-bit containerized vectors with one
5826 // to four Elements.
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005827 // Variadic functions should always marshal to the base standard.
5828 bool IsAAPCS_VFP =
5829 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005830
Reid Klecknerb1be6832014-11-15 01:41:41 +00005831 Ty = useFirstFieldIfTransparentUnion(Ty);
5832
Manman Renfef9e312012-10-16 19:18:39 +00005833 // Handle illegal vector types here.
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005834 if (isIllegalVectorType(Ty))
5835 return coerceIllegalVector(Ty);
Manman Renfef9e312012-10-16 19:18:39 +00005836
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005837 // _Float16 and __fp16 get passed as if it were an int or float, but with
5838 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5839 // half type natively, and does not need to interwork with AAPCS code.
5840 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5841 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005842 llvm::Type *ResType = IsAAPCS_VFP ?
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005843 llvm::Type::getFloatTy(getVMContext()) :
5844 llvm::Type::getInt32Ty(getVMContext());
5845 return ABIArgInfo::getDirect(ResType);
5846 }
5847
John McCalla1dee5302010-08-22 10:59:02 +00005848 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005849 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005850 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005851 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005852 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005853
Alex Bradburye41a5e22018-01-12 20:08:16 +00005854 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005855 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005856 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005857
Oliver Stannard405bded2014-02-11 09:25:50 +00005858 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005859 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005860 }
Tim Northover1060eae2013-06-21 22:49:34 +00005861
Daniel Dunbar09d33622009-09-14 21:54:03 +00005862 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005863 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005864 return ABIArgInfo::getIgnore();
5865
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005866 if (IsAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005867 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5868 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005869 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005870 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005871 if (isHomogeneousAggregate(Ty, Base, Members))
5872 return classifyHomogeneousAggregate(Ty, Base, Members);
Tim Northover5627d392015-10-30 16:30:45 +00005873 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5874 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5875 // this convention even for a variadic function: the backend will use GPRs
5876 // if needed.
5877 const Type *Base = nullptr;
5878 uint64_t Members = 0;
5879 if (isHomogeneousAggregate(Ty, Base, Members)) {
5880 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5881 llvm::Type *Ty =
5882 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5883 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5884 }
5885 }
5886
5887 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5888 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5889 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5890 // bigger than 128-bits, they get placed in space allocated by the caller,
5891 // and a pointer is passed.
5892 return ABIArgInfo::getIndirect(
5893 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005894 }
5895
Manman Ren6c30e132012-08-13 21:23:55 +00005896 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005897 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5898 // most 8-byte. We realign the indirect argument if type alignment is bigger
5899 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005900 uint64_t ABIAlign = 4;
Momchil Velikov20208cc2018-07-30 17:48:23 +00005901 uint64_t TyAlign;
Manman Ren505d68f2012-11-05 22:42:46 +00005902 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Momchil Velikov20208cc2018-07-30 17:48:23 +00005903 getABIKind() == ARMABIInfo::AAPCS) {
5904 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
Manman Ren505d68f2012-11-05 22:42:46 +00005905 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Momchil Velikov20208cc2018-07-30 17:48:23 +00005906 } else {
5907 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5908 }
Manman Ren8cd99812012-11-06 04:58:01 +00005909 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005910 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005911 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5912 /*ByVal=*/true,
5913 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005914 }
5915
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005916 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5917 // same size and alignment.
5918 if (getTarget().isRenderScriptTarget()) {
5919 return coerceToIntArray(Ty, getContext(), getVMContext());
5920 }
5921
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005922 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005923 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005924 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005925 // FIXME: Try to match the types of the arguments more accurately where
5926 // we can.
Momchil Velikov20208cc2018-07-30 17:48:23 +00005927 if (TyAlign <= 4) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005928 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5929 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005930 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005931 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5932 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005933 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005934
Tim Northover5a1558e2014-11-07 22:30:50 +00005935 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005936}
5937
Chris Lattner458b2aa2010-07-29 02:16:43 +00005938static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005939 llvm::LLVMContext &VMContext) {
5940 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5941 // is called integer-like if its size is less than or equal to one word, and
5942 // the offset of each of its addressable sub-fields is zero.
5943
5944 uint64_t Size = Context.getTypeSize(Ty);
5945
5946 // Check that the type fits in a word.
5947 if (Size > 32)
5948 return false;
5949
5950 // FIXME: Handle vector types!
5951 if (Ty->isVectorType())
5952 return false;
5953
Daniel Dunbard53bac72009-09-14 02:20:34 +00005954 // Float types are never treated as "integer like".
5955 if (Ty->isRealFloatingType())
5956 return false;
5957
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005958 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005959 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005960 return true;
5961
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005962 // Small complex integer types are "integer like".
5963 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5964 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005965
5966 // Single element and zero sized arrays should be allowed, by the definition
5967 // above, but they are not.
5968
5969 // Otherwise, it must be a record type.
5970 const RecordType *RT = Ty->getAs<RecordType>();
5971 if (!RT) return false;
5972
5973 // Ignore records with flexible arrays.
5974 const RecordDecl *RD = RT->getDecl();
5975 if (RD->hasFlexibleArrayMember())
5976 return false;
5977
5978 // Check that all sub-fields are at offset 0, and are themselves "integer
5979 // like".
5980 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5981
5982 bool HadField = false;
5983 unsigned idx = 0;
5984 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5985 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005986 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005987
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005988 // Bit-fields are not addressable, we only need to verify they are "integer
5989 // like". We still have to disallow a subsequent non-bitfield, for example:
5990 // struct { int : 0; int x }
5991 // is non-integer like according to gcc.
5992 if (FD->isBitField()) {
5993 if (!RD->isUnion())
5994 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005995
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005996 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5997 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005998
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005999 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006000 }
6001
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006002 // Check if this field is at offset 0.
6003 if (Layout.getFieldOffset(idx) != 0)
6004 return false;
6005
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006006 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6007 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00006008
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006009 // Only allow at most one field in a structure. This doesn't match the
6010 // wording above, but follows gcc in situations with a field following an
6011 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006012 if (!RD->isUnion()) {
6013 if (HadField)
6014 return false;
6015
6016 HadField = true;
6017 }
6018 }
6019
6020 return true;
6021}
6022
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006023ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6024 unsigned functionCallConv) const {
6025
6026 // Variadic functions should always marshal to the base standard.
6027 bool IsAAPCS_VFP =
6028 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006029
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006030 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006031 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006032
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006033 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6034 // Large vector types should be returned via memory.
6035 if (getContext().getTypeSize(RetTy) > 128)
6036 return getNaturalAlignIndirect(RetTy);
6037 // FP16 vectors should be converted to integer vectors
6038 if (!getTarget().hasLegalHalfType() &&
6039 (VT->getElementType()->isFloat16Type() ||
6040 VT->getElementType()->isHalfType()))
6041 return coerceIllegalVector(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00006042 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00006043
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00006044 // _Float16 and __fp16 get returned as if it were an int or float, but with
6045 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6046 // half type natively, and does not need to interwork with AAPCS code.
6047 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6048 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006049 llvm::Type *ResType = IsAAPCS_VFP ?
Oliver Stannarddc2854c2015-09-03 12:40:58 +00006050 llvm::Type::getFloatTy(getVMContext()) :
6051 llvm::Type::getInt32Ty(getVMContext());
6052 return ABIArgInfo::getDirect(ResType);
6053 }
6054
John McCalla1dee5302010-08-22 10:59:02 +00006055 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00006056 // Treat an enum type as its underlying type.
6057 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6058 RetTy = EnumTy->getDecl()->getIntegerType();
6059
Alex Bradburye41a5e22018-01-12 20:08:16 +00006060 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00006061 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00006062 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006063
6064 // Are we following APCS?
6065 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00006066 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006067 return ABIArgInfo::getIgnore();
6068
Daniel Dunbareedf1512010-02-01 23:31:19 +00006069 // Complex types are all returned as packed integers.
6070 //
6071 // FIXME: Consider using 2 x vector types if the back end handles them
6072 // correctly.
6073 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006074 return ABIArgInfo::getDirect(llvm::IntegerType::get(
6075 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00006076
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006077 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006078 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006079 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006080 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006081 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006082 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006083 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006084 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6085 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006086 }
6087
6088 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00006089 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006090 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006091
6092 // Otherwise this is an AAPCS variant.
6093
Chris Lattner458b2aa2010-07-29 02:16:43 +00006094 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006095 return ABIArgInfo::getIgnore();
6096
Bob Wilson1d9269a2011-11-02 04:51:36 +00006097 // Check for homogeneous aggregates with AAPCS-VFP.
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006098 if (IsAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00006099 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00006100 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006101 if (isHomogeneousAggregate(RetTy, Base, Members))
6102 return classifyHomogeneousAggregate(RetTy, Base, Members);
Bob Wilson1d9269a2011-11-02 04:51:36 +00006103 }
6104
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006105 // Aggregates <= 4 bytes are returned in r0; other aggregates
6106 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006107 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006108 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00006109 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6110 // same size and alignment.
6111 if (getTarget().isRenderScriptTarget()) {
6112 return coerceToIntArray(RetTy, getContext(), getVMContext());
6113 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00006114 if (getDataLayout().isBigEndian())
6115 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006116 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006117
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006118 // Return in the smallest viable integer type.
6119 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006120 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006121 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006122 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6123 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006124 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6125 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6126 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006127 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006128 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006129 }
6130
John McCall7f416cc2015-09-08 08:05:57 +00006131 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006132}
6133
Manman Renfef9e312012-10-16 19:18:39 +00006134/// isIllegalVector - check whether Ty is an illegal vector type.
6135bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006136 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006137 // On targets that don't support FP16, FP16 is expanded into float, and we
6138 // don't want the ABI to depend on whether or not FP16 is supported in
6139 // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6140 if (!getTarget().hasLegalHalfType() &&
6141 (VT->getElementType()->isFloat16Type() ||
6142 VT->getElementType()->isHalfType()))
6143 return true;
Stephen Hines8267e7d2015-12-04 01:39:30 +00006144 if (isAndroid()) {
6145 // Android shipped using Clang 3.1, which supported a slightly different
6146 // vector ABI. The primary differences were that 3-element vector types
6147 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6148 // accepts that legacy behavior for Android only.
6149 // Check whether VT is legal.
6150 unsigned NumElements = VT->getNumElements();
6151 // NumElements should be power of 2 or equal to 3.
6152 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6153 return true;
6154 } else {
6155 // Check whether VT is legal.
6156 unsigned NumElements = VT->getNumElements();
6157 uint64_t Size = getContext().getTypeSize(VT);
6158 // NumElements should be power of 2.
6159 if (!llvm::isPowerOf2_32(NumElements))
6160 return true;
6161 // Size should be greater than 32 bits.
6162 return Size <= 32;
6163 }
Manman Renfef9e312012-10-16 19:18:39 +00006164 }
6165 return false;
6166}
6167
Mikhail Maltseva45292c2019-06-18 14:34:27 +00006168/// Return true if a type contains any 16-bit floating point vectors
6169bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6170 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6171 uint64_t NElements = AT->getSize().getZExtValue();
6172 if (NElements == 0)
6173 return false;
6174 return containsAnyFP16Vectors(AT->getElementType());
6175 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6176 const RecordDecl *RD = RT->getDecl();
6177
6178 // If this is a C++ record, check the bases first.
6179 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6180 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6181 return containsAnyFP16Vectors(B.getType());
6182 }))
6183 return true;
6184
6185 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6186 return FD && containsAnyFP16Vectors(FD->getType());
6187 }))
6188 return true;
6189
6190 return false;
6191 } else {
6192 if (const VectorType *VT = Ty->getAs<VectorType>())
6193 return (VT->getElementType()->isFloat16Type() ||
6194 VT->getElementType()->isHalfType());
6195 return false;
6196 }
6197}
6198
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006199bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6200 llvm::Type *eltTy,
6201 unsigned numElts) const {
6202 if (!llvm::isPowerOf2_32(numElts))
6203 return false;
6204 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6205 if (size > 64)
6206 return false;
6207 if (vectorSize.getQuantity() != 8 &&
6208 (vectorSize.getQuantity() != 16 || numElts == 1))
6209 return false;
6210 return true;
6211}
6212
Reid Klecknere9f6a712014-10-31 17:10:41 +00006213bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6214 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6215 // double, or 64-bit or 128-bit vectors.
6216 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6217 if (BT->getKind() == BuiltinType::Float ||
6218 BT->getKind() == BuiltinType::Double ||
6219 BT->getKind() == BuiltinType::LongDouble)
6220 return true;
6221 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6222 unsigned VecSize = getContext().getTypeSize(VT);
6223 if (VecSize == 64 || VecSize == 128)
6224 return true;
6225 }
6226 return false;
6227}
6228
6229bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6230 uint64_t Members) const {
6231 return Members <= 4;
6232}
6233
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006234bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6235 bool acceptHalf) const {
6236 // Give precedence to user-specified calling conventions.
6237 if (callConvention != llvm::CallingConv::C)
6238 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6239 else
6240 return (getABIKind() == AAPCS_VFP) ||
6241 (acceptHalf && (getABIKind() == AAPCS16_VFP));
6242}
6243
John McCall7f416cc2015-09-08 08:05:57 +00006244Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6245 QualType Ty) const {
6246 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006247
John McCall7f416cc2015-09-08 08:05:57 +00006248 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006249 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006250 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6251 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6252 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006253 }
6254
John Brawn6c49f582019-05-22 11:42:54 +00006255 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6256 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
Manman Rencca54d02012-10-16 19:01:37 +00006257
John McCall7f416cc2015-09-08 08:05:57 +00006258 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6259 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006260 const Type *Base = nullptr;
6261 uint64_t Members = 0;
John Brawn6c49f582019-05-22 11:42:54 +00006262 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00006263 IsIndirect = true;
6264
Tim Northover5627d392015-10-30 16:30:45 +00006265 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6266 // allocated by the caller.
John Brawn6c49f582019-05-22 11:42:54 +00006267 } else if (TySize > CharUnits::fromQuantity(16) &&
Tim Northover5627d392015-10-30 16:30:45 +00006268 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6269 !isHomogeneousAggregate(Ty, Base, Members)) {
6270 IsIndirect = true;
6271
John McCall7f416cc2015-09-08 08:05:57 +00006272 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006273 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6274 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006275 // Our callers should be prepared to handle an under-aligned address.
6276 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6277 getABIKind() == ARMABIInfo::AAPCS) {
6278 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6279 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006280 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6281 // ARMv7k allows type alignment up to 16 bytes.
6282 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6283 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006284 } else {
6285 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006286 }
Manman Rencca54d02012-10-16 19:01:37 +00006287
John Brawn6c49f582019-05-22 11:42:54 +00006288 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
John McCall7f416cc2015-09-08 08:05:57 +00006289 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6290 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006291}
6292
Chris Lattner0cf24192010-06-28 20:05:43 +00006293//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006294// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006295//===----------------------------------------------------------------------===//
6296
6297namespace {
6298
Justin Holewinski83e96682012-05-24 17:43:12 +00006299class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006300public:
Justin Holewinski36837432013-03-30 14:38:24 +00006301 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006302
6303 ABIArgInfo classifyReturnType(QualType RetTy) const;
6304 ABIArgInfo classifyArgumentType(QualType Ty) const;
6305
Craig Topper4f12f102014-03-12 06:41:41 +00006306 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006307 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6308 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006309};
6310
Justin Holewinski83e96682012-05-24 17:43:12 +00006311class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006312public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006313 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6314 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006315
Eric Christopher162c91c2015-06-05 22:03:00 +00006316 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006317 CodeGen::CodeGenModule &M) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00006318 bool shouldEmitStaticExternCAliases() const override;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006319
Justin Holewinski36837432013-03-30 14:38:24 +00006320private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006321 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6322 // resulting MDNode to the nvvm.annotations MDNode.
6323 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006324};
6325
Alexey Bataev123ad192019-02-27 20:29:45 +00006326/// Checks if the type is unsupported directly by the current target.
6327static bool isUnsupportedType(ASTContext &Context, QualType T) {
6328 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6329 return true;
Alexey Bataev7ae267d2019-06-18 19:04:27 +00006330 if (!Context.getTargetInfo().hasFloat128Type() &&
6331 (T->isFloat128Type() ||
6332 (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
Alexey Bataev123ad192019-02-27 20:29:45 +00006333 return true;
6334 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6335 Context.getTypeSize(T) > 64)
6336 return true;
6337 if (const auto *AT = T->getAsArrayTypeUnsafe())
6338 return isUnsupportedType(Context, AT->getElementType());
6339 const auto *RT = T->getAs<RecordType>();
6340 if (!RT)
6341 return false;
6342 const RecordDecl *RD = RT->getDecl();
6343
6344 // If this is a C++ record, check the bases first.
6345 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6346 for (const CXXBaseSpecifier &I : CXXRD->bases())
6347 if (isUnsupportedType(Context, I.getType()))
6348 return true;
6349
6350 for (const FieldDecl *I : RD->fields())
6351 if (isUnsupportedType(Context, I->getType()))
6352 return true;
6353 return false;
6354}
6355
6356/// Coerce the given type into an array with maximum allowed size of elements.
6357static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context,
6358 llvm::LLVMContext &LLVMContext,
6359 unsigned MaxSize) {
6360 // Alignment and Size are measured in bits.
6361 const uint64_t Size = Context.getTypeSize(Ty);
6362 const uint64_t Alignment = Context.getTypeAlign(Ty);
6363 const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6364 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div);
6365 const uint64_t NumElements = (Size + Div - 1) / Div;
6366 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6367}
6368
Justin Holewinski83e96682012-05-24 17:43:12 +00006369ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006370 if (RetTy->isVoidType())
6371 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006372
Alexey Bataev123ad192019-02-27 20:29:45 +00006373 if (getContext().getLangOpts().OpenMP &&
6374 getContext().getLangOpts().OpenMPIsDevice &&
6375 isUnsupportedType(getContext(), RetTy))
6376 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64);
6377
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006378 // note: this is different from default ABI
6379 if (!RetTy->isScalarType())
6380 return ABIArgInfo::getDirect();
6381
6382 // Treat an enum type as its underlying type.
6383 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6384 RetTy = EnumTy->getDecl()->getIntegerType();
6385
Alex Bradburye41a5e22018-01-12 20:08:16 +00006386 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6387 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006388}
6389
Justin Holewinski83e96682012-05-24 17:43:12 +00006390ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006391 // Treat an enum type as its underlying type.
6392 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6393 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006394
Eli Bendersky95338a02014-10-29 13:43:21 +00006395 // Return aggregates type as indirect by value
6396 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006397 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006398
Alex Bradburye41a5e22018-01-12 20:08:16 +00006399 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6400 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006401}
6402
Justin Holewinski83e96682012-05-24 17:43:12 +00006403void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006404 if (!getCXXABI().classifyReturnType(FI))
6405 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006406 for (auto &I : FI.arguments())
6407 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006408
6409 // Always honor user-specified calling convention.
6410 if (FI.getCallingConvention() != llvm::CallingConv::C)
6411 return;
6412
John McCall882987f2013-02-28 19:01:20 +00006413 FI.setEffectiveCallingConvention(getRuntimeCC());
6414}
6415
John McCall7f416cc2015-09-08 08:05:57 +00006416Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6417 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006418 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006419}
6420
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006421void NVPTXTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006422 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6423 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006424 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006425 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006426 if (!FD) return;
6427
6428 llvm::Function *F = cast<llvm::Function>(GV);
6429
6430 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006431 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006432 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006433 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006434 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006435 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006436 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6437 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006438 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006439 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006440 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006441 }
Justin Holewinski38031972011-10-05 17:58:44 +00006442
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006443 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006444 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006445 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006446 // __global__ functions cannot be called from the device, we do not
6447 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006448 if (FD->hasAttr<CUDAGlobalAttr>()) {
6449 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6450 addNVVMMetadata(F, "kernel", 1);
6451 }
Artem Belevich7093e402015-04-21 22:55:54 +00006452 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006453 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006454 llvm::APSInt MaxThreads(32);
6455 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6456 if (MaxThreads > 0)
6457 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6458
6459 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6460 // not specified in __launch_bounds__ or if the user specified a 0 value,
6461 // we don't have to add a PTX directive.
6462 if (Attr->getMinBlocks()) {
6463 llvm::APSInt MinBlocks(32);
6464 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6465 if (MinBlocks > 0)
6466 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6467 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006468 }
6469 }
Justin Holewinski38031972011-10-05 17:58:44 +00006470 }
6471}
6472
Eli Benderskye06a2c42014-04-15 16:57:05 +00006473void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6474 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006475 llvm::Module *M = F->getParent();
6476 llvm::LLVMContext &Ctx = M->getContext();
6477
6478 // Get "nvvm.annotations" metadata node
6479 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6480
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006481 llvm::Metadata *MDVals[] = {
6482 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6483 llvm::ConstantAsMetadata::get(
6484 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006485 // Append metadata to nvvm.annotations
6486 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6487}
Yaxun Liub0eee292018-03-29 14:50:00 +00006488
6489bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6490 return false;
6491}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006492}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006493
6494//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006495// SystemZ ABI Implementation
6496//===----------------------------------------------------------------------===//
6497
6498namespace {
6499
Bryan Chane3f1ed52016-04-28 13:56:43 +00006500class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006501 bool HasVector;
6502
Ulrich Weigand47445072013-05-06 16:26:41 +00006503public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006504 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006505 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006506
6507 bool isPromotableIntegerType(QualType Ty) const;
6508 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006509 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006510 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006511 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006512
6513 ABIArgInfo classifyReturnType(QualType RetTy) const;
6514 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6515
Craig Topper4f12f102014-03-12 06:41:41 +00006516 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006517 if (!getCXXABI().classifyReturnType(FI))
6518 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006519 for (auto &I : FI.arguments())
6520 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006521 }
6522
John McCall7f416cc2015-09-08 08:05:57 +00006523 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6524 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006525
John McCall56331e22018-01-07 06:28:49 +00006526 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006527 bool asReturnValue) const override {
6528 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6529 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006530 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006531 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006532 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006533};
6534
6535class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6536public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006537 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6538 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006539};
6540
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006541}
Ulrich Weigand47445072013-05-06 16:26:41 +00006542
6543bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6544 // Treat an enum type as its underlying type.
6545 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6546 Ty = EnumTy->getDecl()->getIntegerType();
6547
6548 // Promotable integer types are required to be promoted by the ABI.
6549 if (Ty->isPromotableIntegerType())
6550 return true;
6551
6552 // 32-bit values must also be promoted.
6553 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6554 switch (BT->getKind()) {
6555 case BuiltinType::Int:
6556 case BuiltinType::UInt:
6557 return true;
6558 default:
6559 return false;
6560 }
6561 return false;
6562}
6563
6564bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006565 return (Ty->isAnyComplexType() ||
6566 Ty->isVectorType() ||
6567 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006568}
6569
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006570bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6571 return (HasVector &&
6572 Ty->isVectorType() &&
6573 getContext().getTypeSize(Ty) <= 128);
6574}
6575
Ulrich Weigand47445072013-05-06 16:26:41 +00006576bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6577 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6578 switch (BT->getKind()) {
6579 case BuiltinType::Float:
6580 case BuiltinType::Double:
6581 return true;
6582 default:
6583 return false;
6584 }
6585
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006586 return false;
6587}
6588
6589QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006590 if (const RecordType *RT = Ty->getAsStructureType()) {
6591 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006592 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006593
6594 // If this is a C++ record, check the bases first.
6595 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006596 for (const auto &I : CXXRD->bases()) {
6597 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006598
6599 // Empty bases don't affect things either way.
6600 if (isEmptyRecord(getContext(), Base, true))
6601 continue;
6602
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006603 if (!Found.isNull())
6604 return Ty;
6605 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006606 }
6607
6608 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006609 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006610 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006611 // Unlike isSingleElementStruct(), empty structure and array fields
6612 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006613 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00006614 FD->isZeroLengthBitField(getContext()))
Ulrich Weigand759449c2015-03-30 13:49:01 +00006615 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006616
6617 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006618 // Nested structures still do though.
6619 if (!Found.isNull())
6620 return Ty;
6621 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006622 }
6623
6624 // Unlike isSingleElementStruct(), trailing padding is allowed.
6625 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006626 if (!Found.isNull())
6627 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006628 }
6629
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006630 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006631}
6632
John McCall7f416cc2015-09-08 08:05:57 +00006633Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6634 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006635 // Assume that va_list type is correct; should be pointer to LLVM type:
6636 // struct {
6637 // i64 __gpr;
6638 // i64 __fpr;
6639 // i8 *__overflow_arg_area;
6640 // i8 *__reg_save_area;
6641 // };
6642
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006643 // Every non-vector argument occupies 8 bytes and is passed by preference
6644 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6645 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006646 Ty = getContext().getCanonicalType(Ty);
6647 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006648 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006649 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006650 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006651 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006652 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006653 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006654 CharUnits UnpaddedSize;
6655 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006656 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006657 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6658 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006659 } else {
6660 if (AI.getCoerceToType())
6661 ArgTy = AI.getCoerceToType();
6662 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006663 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006664 UnpaddedSize = TyInfo.first;
6665 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006666 }
John McCall7f416cc2015-09-08 08:05:57 +00006667 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6668 if (IsVector && UnpaddedSize > PaddedSize)
6669 PaddedSize = CharUnits::fromQuantity(16);
6670 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006671
John McCall7f416cc2015-09-08 08:05:57 +00006672 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006673
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006674 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006675 llvm::Value *PaddedSizeV =
6676 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006677
6678 if (IsVector) {
6679 // Work out the address of a vector argument on the stack.
6680 // Vector arguments are always passed in the high bits of a
6681 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006682 Address OverflowArgAreaPtr =
James Y Knight751fe282019-02-09 22:22:28 +00006683 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006684 Address OverflowArgArea =
6685 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6686 TyInfo.second);
6687 Address MemAddr =
6688 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006689
6690 // Update overflow_arg_area_ptr pointer
6691 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006692 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6693 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006694 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6695
6696 return MemAddr;
6697 }
6698
John McCall7f416cc2015-09-08 08:05:57 +00006699 assert(PaddedSize.getQuantity() == 8);
6700
6701 unsigned MaxRegs, RegCountField, RegSaveIndex;
6702 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006703 if (InFPRs) {
6704 MaxRegs = 4; // Maximum of 4 FPR arguments
6705 RegCountField = 1; // __fpr
6706 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006707 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006708 } else {
6709 MaxRegs = 5; // Maximum of 5 GPR arguments
6710 RegCountField = 0; // __gpr
6711 RegSaveIndex = 2; // save offset for r2
6712 RegPadding = Padding; // values are passed in the low bits of a GPR
6713 }
6714
James Y Knight751fe282019-02-09 22:22:28 +00006715 Address RegCountPtr =
6716 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006717 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006718 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6719 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006720 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006721
6722 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6723 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6724 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6725 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6726
6727 // Emit code to load the value if it was passed in registers.
6728 CGF.EmitBlock(InRegBlock);
6729
6730 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006731 llvm::Value *ScaledRegCount =
6732 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6733 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006734 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6735 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006736 llvm::Value *RegOffset =
6737 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006738 Address RegSaveAreaPtr =
James Y Knight751fe282019-02-09 22:22:28 +00006739 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006740 llvm::Value *RegSaveArea =
6741 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006742 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6743 "raw_reg_addr"),
6744 PaddedSize);
6745 Address RegAddr =
6746 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006747
6748 // Update the register count
6749 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6750 llvm::Value *NewRegCount =
6751 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6752 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6753 CGF.EmitBranch(ContBlock);
6754
6755 // Emit code to load the value if it was passed in memory.
6756 CGF.EmitBlock(InMemBlock);
6757
6758 // Work out the address of a stack argument.
James Y Knight751fe282019-02-09 22:22:28 +00006759 Address OverflowArgAreaPtr =
6760 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006761 Address OverflowArgArea =
6762 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6763 PaddedSize);
6764 Address RawMemAddr =
6765 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6766 Address MemAddr =
6767 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006768
6769 // Update overflow_arg_area_ptr pointer
6770 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006771 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6772 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006773 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6774 CGF.EmitBranch(ContBlock);
6775
6776 // Return the appropriate result.
6777 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006778 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6779 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006780
6781 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006782 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6783 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006784
6785 return ResAddr;
6786}
6787
Ulrich Weigand47445072013-05-06 16:26:41 +00006788ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6789 if (RetTy->isVoidType())
6790 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006791 if (isVectorArgumentType(RetTy))
6792 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006793 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006794 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006795 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6796 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006797}
6798
6799ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6800 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006801 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006802 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006803
6804 // Integers and enums are extended to full register width.
6805 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006806 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006807
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006808 // Handle vector types and vector-like structure types. Note that
6809 // as opposed to float-like structure types, we do not allow any
6810 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006811 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006812 QualType SingleElementTy = GetSingleElementType(Ty);
6813 if (isVectorArgumentType(SingleElementTy) &&
6814 getContext().getTypeSize(SingleElementTy) == Size)
6815 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6816
6817 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006818 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006819 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006820
6821 // Handle small structures.
6822 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6823 // Structures with flexible arrays have variable length, so really
6824 // fail the size test above.
6825 const RecordDecl *RD = RT->getDecl();
6826 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006827 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006828
6829 // The structure is passed as an unextended integer, a float, or a double.
6830 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006831 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006832 assert(Size == 32 || Size == 64);
6833 if (Size == 32)
6834 PassTy = llvm::Type::getFloatTy(getVMContext());
6835 else
6836 PassTy = llvm::Type::getDoubleTy(getVMContext());
6837 } else
6838 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6839 return ABIArgInfo::getDirect(PassTy);
6840 }
6841
6842 // Non-structure compounds are passed indirectly.
6843 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006844 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006845
Craig Topper8a13c412014-05-21 05:09:00 +00006846 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006847}
6848
6849//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006850// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006851//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006852
6853namespace {
6854
6855class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6856public:
Chris Lattner2b037972010-07-29 02:01:43 +00006857 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6858 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006859 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006860 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006861};
6862
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006863}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006864
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006865void MSP430TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006866 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6867 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006868 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006869 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006870 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
6871 if (!InterruptAttr)
6872 return;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006873
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006874 // Handle 'interrupt' attribute:
6875 llvm::Function *F = cast<llvm::Function>(GV);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006876
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006877 // Step 1: Set ISR calling convention.
6878 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006879
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006880 // Step 2: Add attributes goodness.
6881 F->addFnAttr(llvm::Attribute::NoInline);
6882 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006883 }
6884}
6885
Chris Lattner0cf24192010-06-28 20:05:43 +00006886//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006887// MIPS ABI Implementation. This works for both little-endian and
6888// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006889//===----------------------------------------------------------------------===//
6890
John McCall943fae92010-05-27 06:19:26 +00006891namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006892class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006893 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006894 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6895 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006896 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006897 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006898 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006899 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006900public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006901 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006902 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006903 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006904
6905 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006906 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006907 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006908 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6909 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006910 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006911};
6912
John McCall943fae92010-05-27 06:19:26 +00006913class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006914 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006915public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006916 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6917 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006918 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006919
Craig Topper4f12f102014-03-12 06:41:41 +00006920 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006921 return 29;
6922 }
6923
Eric Christopher162c91c2015-06-05 22:03:00 +00006924 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006925 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006926 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006927 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006928 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006929
6930 if (FD->hasAttr<MipsLongCallAttr>())
6931 Fn->addFnAttr("long-call");
6932 else if (FD->hasAttr<MipsShortCallAttr>())
6933 Fn->addFnAttr("short-call");
6934
6935 // Other attributes do not have a meaning for declarations.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006936 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006937 return;
6938
Reed Kotler3d5966f2013-03-13 20:40:30 +00006939 if (FD->hasAttr<Mips16Attr>()) {
6940 Fn->addFnAttr("mips16");
6941 }
6942 else if (FD->hasAttr<NoMips16Attr>()) {
6943 Fn->addFnAttr("nomips16");
6944 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006945
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006946 if (FD->hasAttr<MicroMipsAttr>())
6947 Fn->addFnAttr("micromips");
6948 else if (FD->hasAttr<NoMicroMipsAttr>())
6949 Fn->addFnAttr("nomicromips");
6950
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006951 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6952 if (!Attr)
6953 return;
6954
6955 const char *Kind;
6956 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006957 case MipsInterruptAttr::eic: Kind = "eic"; break;
6958 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6959 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6960 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6961 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6962 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6963 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6964 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6965 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6966 }
6967
6968 Fn->addFnAttr("interrupt", Kind);
6969
Reed Kotler373feca2013-01-16 17:10:28 +00006970 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006971
John McCall943fae92010-05-27 06:19:26 +00006972 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006973 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006974
Craig Topper4f12f102014-03-12 06:41:41 +00006975 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006976 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006977 }
John McCall943fae92010-05-27 06:19:26 +00006978};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006979}
John McCall943fae92010-05-27 06:19:26 +00006980
Eric Christopher7565e0d2015-05-29 23:09:49 +00006981void MipsABIInfo::CoerceToIntArgs(
6982 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006983 llvm::IntegerType *IntTy =
6984 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006985
6986 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6987 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6988 ArgList.push_back(IntTy);
6989
6990 // If necessary, add one more integer type to ArgList.
6991 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6992
6993 if (R)
6994 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006995}
6996
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006997// In N32/64, an aligned double precision floating point field is passed in
6998// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006999llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007000 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7001
7002 if (IsO32) {
7003 CoerceToIntArgs(TySize, ArgList);
7004 return llvm::StructType::get(getVMContext(), ArgList);
7005 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007006
Akira Hatanaka02e13e52012-01-12 00:52:17 +00007007 if (Ty->isComplexType())
7008 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00007009
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00007010 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007011
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007012 // Unions/vectors are passed in integer registers.
7013 if (!RT || !RT->isStructureOrClassType()) {
7014 CoerceToIntArgs(TySize, ArgList);
7015 return llvm::StructType::get(getVMContext(), ArgList);
7016 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007017
7018 const RecordDecl *RD = RT->getDecl();
7019 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007020 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00007021
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007022 uint64_t LastOffset = 0;
7023 unsigned idx = 0;
7024 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7025
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00007026 // Iterate over fields in the struct/class and check if there are any aligned
7027 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007028 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7029 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007030 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007031 const BuiltinType *BT = Ty->getAs<BuiltinType>();
7032
7033 if (!BT || BT->getKind() != BuiltinType::Double)
7034 continue;
7035
7036 uint64_t Offset = Layout.getFieldOffset(idx);
7037 if (Offset % 64) // Ignore doubles that are not aligned.
7038 continue;
7039
7040 // Add ((Offset - LastOffset) / 64) args of type i64.
7041 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7042 ArgList.push_back(I64);
7043
7044 // Add double type.
7045 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7046 LastOffset = Offset + 64;
7047 }
7048
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007049 CoerceToIntArgs(TySize - LastOffset, IntArgList);
7050 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007051
7052 return llvm::StructType::get(getVMContext(), ArgList);
7053}
7054
Akira Hatanakaddd66342013-10-29 18:41:15 +00007055llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7056 uint64_t Offset) const {
7057 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00007058 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00007059
Akira Hatanakaddd66342013-10-29 18:41:15 +00007060 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007061}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00007062
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007063ABIArgInfo
7064MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00007065 Ty = useFirstFieldIfTransparentUnion(Ty);
7066
Akira Hatanaka1632af62012-01-09 19:31:25 +00007067 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007068 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007069 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007070
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007071 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7072 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007073 unsigned CurrOffset = llvm::alignTo(Offset, Align);
7074 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00007075
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007076 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00007077 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007078 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007079 return ABIArgInfo::getIgnore();
7080
Mark Lacey3825e832013-10-06 01:33:34 +00007081 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007082 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00007083 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007084 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00007085
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007086 // If we have reached here, aggregates are passed directly by coercing to
7087 // another structure type. Padding is inserted if the offset of the
7088 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00007089 ABIArgInfo ArgInfo =
7090 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7091 getPaddingType(OrigOffset, CurrOffset));
7092 ArgInfo.setInReg(true);
7093 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007094 }
7095
7096 // Treat an enum type as its underlying type.
7097 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7098 Ty = EnumTy->getDecl()->getIntegerType();
7099
Daniel Sanders5b445b32014-10-24 14:42:42 +00007100 // All integral types are promoted to the GPR width.
7101 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007102 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007103
Akira Hatanakaddd66342013-10-29 18:41:15 +00007104 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00007105 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00007106}
7107
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007108llvm::Type*
7109MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00007110 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007111 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007112
Akira Hatanakab6f74432012-02-09 18:49:26 +00007113 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007114 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00007115 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7116 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007117
Akira Hatanakab6f74432012-02-09 18:49:26 +00007118 // N32/64 returns struct/classes in floating point registers if the
7119 // following conditions are met:
7120 // 1. The size of the struct/class is no larger than 128-bit.
7121 // 2. The struct/class has one or two fields all of which are floating
7122 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007123 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00007124 //
7125 // Any other composite results are returned in integer registers.
7126 //
7127 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7128 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7129 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007130 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007131
Akira Hatanakab6f74432012-02-09 18:49:26 +00007132 if (!BT || !BT->isFloatingPoint())
7133 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007134
David Blaikie2d7c57e2012-04-30 02:36:29 +00007135 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00007136 }
7137
7138 if (b == e)
7139 return llvm::StructType::get(getVMContext(), RTList,
7140 RD->hasAttr<PackedAttr>());
7141
7142 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007143 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007144 }
7145
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007146 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007147 return llvm::StructType::get(getVMContext(), RTList);
7148}
7149
Akira Hatanakab579fe52011-06-02 00:09:17 +00007150ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00007151 uint64_t Size = getContext().getTypeSize(RetTy);
7152
Daniel Sandersed39f582014-09-04 13:28:14 +00007153 if (RetTy->isVoidType())
7154 return ABIArgInfo::getIgnore();
7155
7156 // O32 doesn't treat zero-sized structs differently from other structs.
7157 // However, N32/N64 ignores zero sized return values.
7158 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007159 return ABIArgInfo::getIgnore();
7160
Akira Hatanakac37eddf2012-05-11 21:01:17 +00007161 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007162 if (Size <= 128) {
7163 if (RetTy->isAnyComplexType())
7164 return ABIArgInfo::getDirect();
7165
Daniel Sanderse5018b62014-09-04 15:05:39 +00007166 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00007167 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00007168 if (!IsO32 ||
7169 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7170 ABIArgInfo ArgInfo =
7171 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7172 ArgInfo.setInReg(true);
7173 return ArgInfo;
7174 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007175 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00007176
John McCall7f416cc2015-09-08 08:05:57 +00007177 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007178 }
7179
7180 // Treat an enum type as its underlying type.
7181 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7182 RetTy = EnumTy->getDecl()->getIntegerType();
7183
Stefan Maksimovicb9da8a52018-07-30 10:44:46 +00007184 if (RetTy->isPromotableIntegerType())
7185 return ABIArgInfo::getExtend(RetTy);
7186
7187 if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7188 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7189 return ABIArgInfo::getSignExtend(RetTy);
7190
7191 return ABIArgInfo::getDirect();
Akira Hatanakab579fe52011-06-02 00:09:17 +00007192}
7193
7194void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00007195 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00007196 if (!getCXXABI().classifyReturnType(FI))
7197 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00007198
Eric Christopher7565e0d2015-05-29 23:09:49 +00007199 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007200 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00007201
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007202 for (auto &I : FI.arguments())
7203 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007204}
7205
John McCall7f416cc2015-09-08 08:05:57 +00007206Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7207 QualType OrigTy) const {
7208 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00007209
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007210 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7211 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00007212 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007213 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00007214 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007215 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007216 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007217 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007218 DidPromote = true;
7219 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7220 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007221 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007222
John McCall7f416cc2015-09-08 08:05:57 +00007223 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007224
John McCall7f416cc2015-09-08 08:05:57 +00007225 // The alignment of things in the argument area is never larger than
7226 // StackAlignInBytes.
7227 TyInfo.second =
7228 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7229
7230 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7231 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7232
7233 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7234 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7235
7236
7237 // If there was a promotion, "unpromote" into a temporary.
7238 // TODO: can we just use a pointer into a subset of the original slot?
7239 if (DidPromote) {
7240 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7241 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7242
7243 // Truncate down to the right width.
7244 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7245 : CGF.IntPtrTy);
7246 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7247 if (OrigTy->isPointerType())
7248 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7249
7250 CGF.Builder.CreateStore(V, Temp);
7251 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007252 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007253
John McCall7f416cc2015-09-08 08:05:57 +00007254 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007255}
7256
Alex Bradburye41a5e22018-01-12 20:08:16 +00007257ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007258 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007259
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007260 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7261 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007262 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007263
Alex Bradburye41a5e22018-01-12 20:08:16 +00007264 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007265}
7266
John McCall943fae92010-05-27 06:19:26 +00007267bool
7268MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7269 llvm::Value *Address) const {
7270 // This information comes from gcc's implementation, which seems to
7271 // as canonical as it gets.
7272
John McCall943fae92010-05-27 06:19:26 +00007273 // Everything on MIPS is 4 bytes. Double-precision FP registers
7274 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007275 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007276
7277 // 0-31 are the general purpose registers, $0 - $31.
7278 // 32-63 are the floating-point registers, $f0 - $f31.
7279 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7280 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007281 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007282
7283 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7284 // They are one bit wide and ignored here.
7285
7286 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7287 // (coprocessor 1 is the FP unit)
7288 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7289 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7290 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007291 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007292 return false;
7293}
7294
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007295//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007296// AVR ABI Implementation.
7297//===----------------------------------------------------------------------===//
7298
7299namespace {
7300class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7301public:
7302 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7303 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7304
7305 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007306 CodeGen::CodeGenModule &CGM) const override {
7307 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007308 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007309 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7310 if (!FD) return;
7311 auto *Fn = cast<llvm::Function>(GV);
7312
7313 if (FD->getAttr<AVRInterruptAttr>())
7314 Fn->addFnAttr("interrupt");
7315
7316 if (FD->getAttr<AVRSignalAttr>())
7317 Fn->addFnAttr("signal");
7318 }
7319};
7320}
7321
7322//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007323// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007324// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007325// handling.
7326//===----------------------------------------------------------------------===//
7327
7328namespace {
7329
7330class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7331public:
7332 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7333 : DefaultTargetCodeGenInfo(CGT) {}
7334
Eric Christopher162c91c2015-06-05 22:03:00 +00007335 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007336 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007337};
7338
Eric Christopher162c91c2015-06-05 22:03:00 +00007339void TCETargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007340 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7341 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007342 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007343 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007344 if (!FD) return;
7345
7346 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007347
David Blaikiebbafb8a2012-03-11 07:00:24 +00007348 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007349 if (FD->hasAttr<OpenCLKernelAttr>()) {
7350 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007351 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007352 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7353 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007354 // Convert the reqd_work_group_size() attributes to metadata.
7355 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007356 llvm::NamedMDNode *OpenCLMetadata =
7357 M.getModule().getOrInsertNamedMetadata(
7358 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007359
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007360 SmallVector<llvm::Metadata *, 5> Operands;
7361 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007362
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007363 Operands.push_back(
7364 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7365 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7366 Operands.push_back(
7367 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7368 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7369 Operands.push_back(
7370 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7371 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007372
Eric Christopher7565e0d2015-05-29 23:09:49 +00007373 // Add a boolean constant operand for "required" (true) or "hint"
7374 // (false) for implementing the work_group_size_hint attr later.
7375 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007376 Operands.push_back(
7377 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007378 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7379 }
7380 }
7381 }
7382}
7383
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007384}
John McCall943fae92010-05-27 06:19:26 +00007385
Tony Linthicum76329bf2011-12-12 21:14:55 +00007386//===----------------------------------------------------------------------===//
7387// Hexagon ABI Implementation
7388//===----------------------------------------------------------------------===//
7389
7390namespace {
7391
7392class HexagonABIInfo : public ABIInfo {
7393
7394
7395public:
7396 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7397
7398private:
7399
7400 ABIArgInfo classifyReturnType(QualType RetTy) const;
7401 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7402
Craig Topper4f12f102014-03-12 06:41:41 +00007403 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007404
John McCall7f416cc2015-09-08 08:05:57 +00007405 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7406 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007407};
7408
7409class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7410public:
7411 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7412 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7413
Craig Topper4f12f102014-03-12 06:41:41 +00007414 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007415 return 29;
7416 }
7417};
7418
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007419}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007420
7421void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007422 if (!getCXXABI().classifyReturnType(FI))
7423 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007424 for (auto &I : FI.arguments())
7425 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007426}
7427
7428ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7429 if (!isAggregateTypeForABI(Ty)) {
7430 // Treat an enum type as its underlying type.
7431 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7432 Ty = EnumTy->getDecl()->getIntegerType();
7433
Alex Bradburye41a5e22018-01-12 20:08:16 +00007434 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7435 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007436 }
7437
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007438 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7439 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7440
Tony Linthicum76329bf2011-12-12 21:14:55 +00007441 // Ignore empty records.
7442 if (isEmptyRecord(getContext(), Ty, true))
7443 return ABIArgInfo::getIgnore();
7444
Tony Linthicum76329bf2011-12-12 21:14:55 +00007445 uint64_t Size = getContext().getTypeSize(Ty);
7446 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007447 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007448 // Pass in the smallest viable integer type.
7449 else if (Size > 32)
7450 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7451 else if (Size > 16)
7452 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7453 else if (Size > 8)
7454 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7455 else
7456 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7457}
7458
7459ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7460 if (RetTy->isVoidType())
7461 return ABIArgInfo::getIgnore();
7462
7463 // Large vector types should be returned via memory.
7464 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007465 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007466
7467 if (!isAggregateTypeForABI(RetTy)) {
7468 // Treat an enum type as its underlying type.
7469 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7470 RetTy = EnumTy->getDecl()->getIntegerType();
7471
Alex Bradburye41a5e22018-01-12 20:08:16 +00007472 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7473 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007474 }
7475
Tony Linthicum76329bf2011-12-12 21:14:55 +00007476 if (isEmptyRecord(getContext(), RetTy, true))
7477 return ABIArgInfo::getIgnore();
7478
7479 // Aggregates <= 8 bytes are returned in r0; other aggregates
7480 // are returned indirectly.
7481 uint64_t Size = getContext().getTypeSize(RetTy);
7482 if (Size <= 64) {
7483 // Return in the smallest viable integer type.
7484 if (Size <= 8)
7485 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7486 if (Size <= 16)
7487 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7488 if (Size <= 32)
7489 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7490 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7491 }
7492
John McCall7f416cc2015-09-08 08:05:57 +00007493 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007494}
7495
John McCall7f416cc2015-09-08 08:05:57 +00007496Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7497 QualType Ty) const {
7498 // FIXME: Someone needs to audit that this handle alignment correctly.
7499 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7500 getContext().getTypeInfoInChars(Ty),
7501 CharUnits::fromQuantity(4),
7502 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007503}
7504
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007505//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007506// Lanai ABI Implementation
7507//===----------------------------------------------------------------------===//
7508
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007509namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007510class LanaiABIInfo : public DefaultABIInfo {
7511public:
7512 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7513
7514 bool shouldUseInReg(QualType Ty, CCState &State) const;
7515
7516 void computeInfo(CGFunctionInfo &FI) const override {
7517 CCState State(FI.getCallingConvention());
7518 // Lanai uses 4 registers to pass arguments unless the function has the
7519 // regparm attribute set.
7520 if (FI.getHasRegParm()) {
7521 State.FreeRegs = FI.getRegParm();
7522 } else {
7523 State.FreeRegs = 4;
7524 }
7525
7526 if (!getCXXABI().classifyReturnType(FI))
7527 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7528 for (auto &I : FI.arguments())
7529 I.info = classifyArgumentType(I.type, State);
7530 }
7531
Jacques Pienaare74d9132016-04-26 00:09:29 +00007532 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007533 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7534};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007535} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007536
7537bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7538 unsigned Size = getContext().getTypeSize(Ty);
7539 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7540
7541 if (SizeInRegs == 0)
7542 return false;
7543
7544 if (SizeInRegs > State.FreeRegs) {
7545 State.FreeRegs = 0;
7546 return false;
7547 }
7548
7549 State.FreeRegs -= SizeInRegs;
7550
7551 return true;
7552}
7553
Jacques Pienaare74d9132016-04-26 00:09:29 +00007554ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7555 CCState &State) const {
7556 if (!ByVal) {
7557 if (State.FreeRegs) {
7558 --State.FreeRegs; // Non-byval indirects just use one pointer.
7559 return getNaturalAlignIndirectInReg(Ty);
7560 }
7561 return getNaturalAlignIndirect(Ty, false);
7562 }
7563
7564 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007565 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007566 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7567 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7568 /*Realign=*/TypeAlign >
7569 MinABIStackAlignInBytes);
7570}
7571
Jacques Pienaard964cc22016-03-28 21:02:54 +00007572ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7573 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007574 // Check with the C++ ABI first.
7575 const RecordType *RT = Ty->getAs<RecordType>();
7576 if (RT) {
7577 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7578 if (RAA == CGCXXABI::RAA_Indirect) {
7579 return getIndirectResult(Ty, /*ByVal=*/false, State);
7580 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7581 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7582 }
7583 }
7584
7585 if (isAggregateTypeForABI(Ty)) {
7586 // Structures with flexible arrays are always indirect.
7587 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7588 return getIndirectResult(Ty, /*ByVal=*/true, State);
7589
7590 // Ignore empty structs/unions.
7591 if (isEmptyRecord(getContext(), Ty, true))
7592 return ABIArgInfo::getIgnore();
7593
7594 llvm::LLVMContext &LLVMContext = getVMContext();
7595 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7596 if (SizeInRegs <= State.FreeRegs) {
7597 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7598 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7599 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7600 State.FreeRegs -= SizeInRegs;
7601 return ABIArgInfo::getDirectInReg(Result);
7602 } else {
7603 State.FreeRegs = 0;
7604 }
7605 return getIndirectResult(Ty, true, State);
7606 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007607
7608 // Treat an enum type as its underlying type.
7609 if (const auto *EnumTy = Ty->getAs<EnumType>())
7610 Ty = EnumTy->getDecl()->getIntegerType();
7611
Jacques Pienaare74d9132016-04-26 00:09:29 +00007612 bool InReg = shouldUseInReg(Ty, State);
7613 if (Ty->isPromotableIntegerType()) {
7614 if (InReg)
7615 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007616 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007617 }
7618 if (InReg)
7619 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007620 return ABIArgInfo::getDirect();
7621}
7622
7623namespace {
7624class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7625public:
7626 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7627 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7628};
7629}
7630
7631//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007632// AMDGPU ABI Implementation
7633//===----------------------------------------------------------------------===//
7634
7635namespace {
7636
Matt Arsenault88d7da02016-08-22 19:25:59 +00007637class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007638private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007639 static const unsigned MaxNumRegsForArgsRet = 16;
7640
Matt Arsenault3fe73952017-08-09 21:44:58 +00007641 unsigned numRegsForType(QualType Ty) const;
7642
7643 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7644 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7645 uint64_t Members) const override;
7646
7647public:
7648 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7649 DefaultABIInfo(CGT) {}
7650
7651 ABIArgInfo classifyReturnType(QualType RetTy) const;
7652 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7653 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007654
7655 void computeInfo(CGFunctionInfo &FI) const override;
7656};
7657
Matt Arsenault3fe73952017-08-09 21:44:58 +00007658bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7659 return true;
7660}
7661
7662bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7663 const Type *Base, uint64_t Members) const {
7664 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7665
7666 // Homogeneous Aggregates may occupy at most 16 registers.
7667 return Members * NumRegs <= MaxNumRegsForArgsRet;
7668}
7669
Matt Arsenault3fe73952017-08-09 21:44:58 +00007670/// Estimate number of registers the type will use when passed in registers.
7671unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7672 unsigned NumRegs = 0;
7673
7674 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7675 // Compute from the number of elements. The reported size is based on the
7676 // in-memory size, which includes the padding 4th element for 3-vectors.
7677 QualType EltTy = VT->getElementType();
7678 unsigned EltSize = getContext().getTypeSize(EltTy);
7679
7680 // 16-bit element vectors should be passed as packed.
7681 if (EltSize == 16)
7682 return (VT->getNumElements() + 1) / 2;
7683
7684 unsigned EltNumRegs = (EltSize + 31) / 32;
7685 return EltNumRegs * VT->getNumElements();
7686 }
7687
7688 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7689 const RecordDecl *RD = RT->getDecl();
7690 assert(!RD->hasFlexibleArrayMember());
7691
7692 for (const FieldDecl *Field : RD->fields()) {
7693 QualType FieldTy = Field->getType();
7694 NumRegs += numRegsForType(FieldTy);
7695 }
7696
7697 return NumRegs;
7698 }
7699
7700 return (getContext().getTypeSize(Ty) + 31) / 32;
7701}
7702
Matt Arsenault88d7da02016-08-22 19:25:59 +00007703void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007704 llvm::CallingConv::ID CC = FI.getCallingConvention();
7705
Matt Arsenault88d7da02016-08-22 19:25:59 +00007706 if (!getCXXABI().classifyReturnType(FI))
7707 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7708
Matt Arsenault3fe73952017-08-09 21:44:58 +00007709 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7710 for (auto &Arg : FI.arguments()) {
7711 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7712 Arg.info = classifyKernelArgumentType(Arg.type);
7713 } else {
7714 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7715 }
7716 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007717}
7718
Matt Arsenault3fe73952017-08-09 21:44:58 +00007719ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7720 if (isAggregateTypeForABI(RetTy)) {
7721 // Records with non-trivial destructors/copy-constructors should not be
7722 // returned by value.
7723 if (!getRecordArgABI(RetTy, getCXXABI())) {
7724 // Ignore empty structs/unions.
7725 if (isEmptyRecord(getContext(), RetTy, true))
7726 return ABIArgInfo::getIgnore();
7727
7728 // Lower single-element structs to just return a regular value.
7729 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7730 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7731
7732 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7733 const RecordDecl *RD = RT->getDecl();
7734 if (RD->hasFlexibleArrayMember())
7735 return DefaultABIInfo::classifyReturnType(RetTy);
7736 }
7737
7738 // Pack aggregates <= 4 bytes into single VGPR or pair.
7739 uint64_t Size = getContext().getTypeSize(RetTy);
7740 if (Size <= 16)
7741 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7742
7743 if (Size <= 32)
7744 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7745
7746 if (Size <= 64) {
7747 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7748 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7749 }
7750
7751 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7752 return ABIArgInfo::getDirect();
7753 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007754 }
7755
Matt Arsenault3fe73952017-08-09 21:44:58 +00007756 // Otherwise just do the default thing.
7757 return DefaultABIInfo::classifyReturnType(RetTy);
7758}
7759
7760/// For kernels all parameters are really passed in a special buffer. It doesn't
7761/// make sense to pass anything byval, so everything must be direct.
7762ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7763 Ty = useFirstFieldIfTransparentUnion(Ty);
7764
7765 // TODO: Can we omit empty structs?
7766
Matt Arsenault88d7da02016-08-22 19:25:59 +00007767 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007768 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7769 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007770
7771 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7772 // individual elements, which confuses the Clover OpenCL backend; therefore we
7773 // have to set it to false here. Other args of getDirect() are just defaults.
7774 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7775}
7776
Matt Arsenault3fe73952017-08-09 21:44:58 +00007777ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7778 unsigned &NumRegsLeft) const {
7779 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7780
7781 Ty = useFirstFieldIfTransparentUnion(Ty);
7782
7783 if (isAggregateTypeForABI(Ty)) {
7784 // Records with non-trivial destructors/copy-constructors should not be
7785 // passed by value.
7786 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7787 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7788
7789 // Ignore empty structs/unions.
7790 if (isEmptyRecord(getContext(), Ty, true))
7791 return ABIArgInfo::getIgnore();
7792
7793 // Lower single-element structs to just pass a regular value. TODO: We
7794 // could do reasonable-size multiple-element structs too, using getExpand(),
7795 // though watch out for things like bitfields.
7796 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7797 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7798
7799 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7800 const RecordDecl *RD = RT->getDecl();
7801 if (RD->hasFlexibleArrayMember())
7802 return DefaultABIInfo::classifyArgumentType(Ty);
7803 }
7804
7805 // Pack aggregates <= 8 bytes into single VGPR or pair.
7806 uint64_t Size = getContext().getTypeSize(Ty);
7807 if (Size <= 64) {
7808 unsigned NumRegs = (Size + 31) / 32;
7809 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7810
7811 if (Size <= 16)
7812 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7813
7814 if (Size <= 32)
7815 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7816
7817 // XXX: Should this be i64 instead, and should the limit increase?
7818 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7819 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7820 }
7821
7822 if (NumRegsLeft > 0) {
7823 unsigned NumRegs = numRegsForType(Ty);
7824 if (NumRegsLeft >= NumRegs) {
7825 NumRegsLeft -= NumRegs;
7826 return ABIArgInfo::getDirect();
7827 }
7828 }
7829 }
7830
7831 // Otherwise just do the default thing.
7832 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7833 if (!ArgInfo.isIndirect()) {
7834 unsigned NumRegs = numRegsForType(Ty);
7835 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7836 }
7837
7838 return ArgInfo;
7839}
7840
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007841class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7842public:
7843 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007844 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007845 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007846 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007847 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007848
Yaxun Liu402804b2016-12-15 08:09:08 +00007849 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7850 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007851
Alexander Richardson6d989432017-10-15 18:48:14 +00007852 LangAS getASTAllocaAddressSpace() const override {
7853 return getLangASFromTargetAS(
7854 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007855 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007856 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7857 const VarDecl *D) const override;
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00007858 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
7859 SyncScope Scope,
7860 llvm::AtomicOrdering Ordering,
7861 llvm::LLVMContext &Ctx) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007862 llvm::Function *
7863 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7864 llvm::Function *BlockInvokeFunc,
7865 llvm::Value *BlockLiteral) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00007866 bool shouldEmitStaticExternCAliases() const override;
Yaxun Liu6c10a662018-06-12 00:16:33 +00007867 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007868};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007869}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007870
Scott Linder80a1ee42019-02-12 18:30:38 +00007871static bool requiresAMDGPUProtectedVisibility(const Decl *D,
7872 llvm::GlobalValue *GV) {
7873 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
7874 return false;
7875
7876 return D->hasAttr<OpenCLKernelAttr>() ||
7877 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
Michael Liao38205062019-04-26 19:31:48 +00007878 (isa<VarDecl>(D) &&
Yaxun Liuc3dfe902019-06-26 03:47:37 +00007879 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
7880 D->hasAttr<HIPPinnedShadowAttr>()));
7881}
7882
7883static bool requiresAMDGPUDefaultVisibility(const Decl *D,
7884 llvm::GlobalValue *GV) {
7885 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
7886 return false;
7887
7888 return isa<VarDecl>(D) && D->hasAttr<HIPPinnedShadowAttr>();
Scott Linder80a1ee42019-02-12 18:30:38 +00007889}
7890
Eric Christopher162c91c2015-06-05 22:03:00 +00007891void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007892 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Yaxun Liuc3dfe902019-06-26 03:47:37 +00007893 if (requiresAMDGPUDefaultVisibility(D, GV)) {
7894 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
7895 GV->setDSOLocal(false);
7896 } else if (requiresAMDGPUProtectedVisibility(D, GV)) {
Scott Linder80a1ee42019-02-12 18:30:38 +00007897 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
7898 GV->setDSOLocal(true);
7899 }
7900
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007901 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007902 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007903 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007904 if (!FD)
7905 return;
7906
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007907 llvm::Function *F = cast<llvm::Function>(GV);
7908
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007909 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7910 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
Tony Tye1a3f3a22018-03-23 18:43:15 +00007911
Yaxun Liucabce712019-06-14 15:54:47 +00007912 if (((M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>()) ||
7913 (M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>())) &&
Tony Tye1a3f3a22018-03-23 18:43:15 +00007914 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
Christudasan Devadasan18ba9d62019-07-10 15:10:08 +00007915 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
Tony Tye1a3f3a22018-03-23 18:43:15 +00007916
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007917 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7918 if (ReqdWGS || FlatWGS) {
Michael Liao7557afa2019-02-26 18:49:36 +00007919 unsigned Min = 0;
7920 unsigned Max = 0;
7921 if (FlatWGS) {
7922 Min = FlatWGS->getMin()
7923 ->EvaluateKnownConstInt(M.getContext())
7924 .getExtValue();
7925 Max = FlatWGS->getMax()
7926 ->EvaluateKnownConstInt(M.getContext())
7927 .getExtValue();
7928 }
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007929 if (ReqdWGS && Min == 0 && Max == 0)
7930 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007931
7932 if (Min != 0) {
7933 assert(Min <= Max && "Min must be less than or equal Max");
7934
7935 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7936 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7937 } else
7938 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007939 }
7940
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007941 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
Michael Liao7557afa2019-02-26 18:49:36 +00007942 unsigned Min =
7943 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
7944 unsigned Max = Attr->getMax() ? Attr->getMax()
7945 ->EvaluateKnownConstInt(M.getContext())
7946 .getExtValue()
7947 : 0;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007948
7949 if (Min != 0) {
7950 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7951
7952 std::string AttrVal = llvm::utostr(Min);
7953 if (Max != 0)
7954 AttrVal = AttrVal + "," + llvm::utostr(Max);
7955 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7956 } else
7957 assert(Max == 0 && "Max must be zero");
7958 }
7959
7960 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007961 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007962
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007963 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007964 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7965 }
7966
7967 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7968 uint32_t NumVGPR = Attr->getNumVGPR();
7969
7970 if (NumVGPR != 0)
7971 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007972 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007973}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007974
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007975unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7976 return llvm::CallingConv::AMDGPU_KERNEL;
7977}
7978
Yaxun Liu402804b2016-12-15 08:09:08 +00007979// Currently LLVM assumes null pointers always have value 0,
7980// which results in incorrectly transformed IR. Therefore, instead of
7981// emitting null pointers in private and local address spaces, a null
7982// pointer in generic address space is emitted which is casted to a
7983// pointer in local or private address space.
7984llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7985 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7986 QualType QT) const {
7987 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7988 return llvm::ConstantPointerNull::get(PT);
7989
7990 auto &Ctx = CGM.getContext();
7991 auto NPT = llvm::PointerType::get(PT->getElementType(),
7992 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7993 return llvm::ConstantExpr::getAddrSpaceCast(
7994 llvm::ConstantPointerNull::get(NPT), PT);
7995}
7996
Alexander Richardson6d989432017-10-15 18:48:14 +00007997LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00007998AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7999 const VarDecl *D) const {
8000 assert(!CGM.getLangOpts().OpenCL &&
8001 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
8002 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00008003 LangAS DefaultGlobalAS = getLangASFromTargetAS(
8004 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00008005 if (!D)
8006 return DefaultGlobalAS;
8007
Alexander Richardson6d989432017-10-15 18:48:14 +00008008 LangAS AddrSpace = D->getType().getAddressSpace();
8009 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00008010 if (AddrSpace != LangAS::Default)
8011 return AddrSpace;
8012
8013 if (CGM.isTypeConstant(D->getType(), false)) {
8014 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
8015 return ConstAS.getValue();
8016 }
8017 return DefaultGlobalAS;
8018}
8019
Yaxun Liu39195062017-08-04 18:16:31 +00008020llvm::SyncScope::ID
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00008021AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
8022 SyncScope Scope,
8023 llvm::AtomicOrdering Ordering,
8024 llvm::LLVMContext &Ctx) const {
8025 std::string Name;
8026 switch (Scope) {
Yaxun Liu39195062017-08-04 18:16:31 +00008027 case SyncScope::OpenCLWorkGroup:
8028 Name = "workgroup";
8029 break;
8030 case SyncScope::OpenCLDevice:
8031 Name = "agent";
8032 break;
8033 case SyncScope::OpenCLAllSVMDevices:
8034 Name = "";
8035 break;
8036 case SyncScope::OpenCLSubGroup:
Konstantin Zhuravlyov3161c892019-03-06 20:54:48 +00008037 Name = "wavefront";
Yaxun Liu39195062017-08-04 18:16:31 +00008038 }
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00008039
8040 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
8041 if (!Name.empty())
8042 Name = Twine(Twine(Name) + Twine("-")).str();
8043
8044 Name = Twine(Twine(Name) + Twine("one-as")).str();
8045 }
8046
8047 return Ctx.getOrInsertSyncScopeID(Name);
Yaxun Liu39195062017-08-04 18:16:31 +00008048}
8049
Yaxun Liub0eee292018-03-29 14:50:00 +00008050bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
8051 return false;
8052}
8053
Yaxun Liu4306f202018-04-20 17:01:03 +00008054void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
Yaxun Liu6c10a662018-06-12 00:16:33 +00008055 const FunctionType *&FT) const {
8056 FT = getABIInfo().getContext().adjustFunctionType(
8057 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
Yaxun Liu4306f202018-04-20 17:01:03 +00008058}
8059
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008060//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008061// SPARC v8 ABI Implementation.
8062// Based on the SPARC Compliance Definition version 2.4.1.
8063//
8064// Ensures that complex values are passed in registers.
8065//
8066namespace {
8067class SparcV8ABIInfo : public DefaultABIInfo {
8068public:
8069 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8070
8071private:
8072 ABIArgInfo classifyReturnType(QualType RetTy) const;
8073 void computeInfo(CGFunctionInfo &FI) const override;
8074};
8075} // end anonymous namespace
8076
8077
8078ABIArgInfo
8079SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
8080 if (Ty->isAnyComplexType()) {
8081 return ABIArgInfo::getDirect();
8082 }
8083 else {
8084 return DefaultABIInfo::classifyReturnType(Ty);
8085 }
8086}
8087
8088void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8089
8090 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8091 for (auto &Arg : FI.arguments())
8092 Arg.info = classifyArgumentType(Arg.type);
8093}
8094
8095namespace {
8096class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
8097public:
8098 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
8099 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
8100};
8101} // end anonymous namespace
8102
8103//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008104// SPARC v9 ABI Implementation.
8105// Based on the SPARC Compliance Definition version 2.4.1.
8106//
8107// Function arguments a mapped to a nominal "parameter array" and promoted to
8108// registers depending on their type. Each argument occupies 8 or 16 bytes in
8109// the array, structs larger than 16 bytes are passed indirectly.
8110//
8111// One case requires special care:
8112//
8113// struct mixed {
8114// int i;
8115// float f;
8116// };
8117//
8118// When a struct mixed is passed by value, it only occupies 8 bytes in the
8119// parameter array, but the int is passed in an integer register, and the float
8120// is passed in a floating point register. This is represented as two arguments
8121// with the LLVM IR inreg attribute:
8122//
8123// declare void f(i32 inreg %i, float inreg %f)
8124//
8125// The code generator will only allocate 4 bytes from the parameter array for
8126// the inreg arguments. All other arguments are allocated a multiple of 8
8127// bytes.
8128//
8129namespace {
8130class SparcV9ABIInfo : public ABIInfo {
8131public:
8132 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
8133
8134private:
8135 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00008136 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00008137 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8138 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008139
8140 // Coercion type builder for structs passed in registers. The coercion type
8141 // serves two purposes:
8142 //
8143 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8144 // in registers.
8145 // 2. Expose aligned floating point elements as first-level elements, so the
8146 // code generator knows to pass them in floating point registers.
8147 //
8148 // We also compute the InReg flag which indicates that the struct contains
8149 // aligned 32-bit floats.
8150 //
8151 struct CoerceBuilder {
8152 llvm::LLVMContext &Context;
8153 const llvm::DataLayout &DL;
8154 SmallVector<llvm::Type*, 8> Elems;
8155 uint64_t Size;
8156 bool InReg;
8157
8158 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8159 : Context(c), DL(dl), Size(0), InReg(false) {}
8160
8161 // Pad Elems with integers until Size is ToSize.
8162 void pad(uint64_t ToSize) {
8163 assert(ToSize >= Size && "Cannot remove elements");
8164 if (ToSize == Size)
8165 return;
8166
8167 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008168 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008169 if (Aligned > Size && Aligned <= ToSize) {
8170 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8171 Size = Aligned;
8172 }
8173
8174 // Add whole 64-bit words.
8175 while (Size + 64 <= ToSize) {
8176 Elems.push_back(llvm::Type::getInt64Ty(Context));
8177 Size += 64;
8178 }
8179
8180 // Final in-word padding.
8181 if (Size < ToSize) {
8182 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8183 Size = ToSize;
8184 }
8185 }
8186
8187 // Add a floating point element at Offset.
8188 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8189 // Unaligned floats are treated as integers.
8190 if (Offset % Bits)
8191 return;
8192 // The InReg flag is only required if there are any floats < 64 bits.
8193 if (Bits < 64)
8194 InReg = true;
8195 pad(Offset);
8196 Elems.push_back(Ty);
8197 Size = Offset + Bits;
8198 }
8199
8200 // Add a struct type to the coercion type, starting at Offset (in bits).
8201 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8202 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8203 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8204 llvm::Type *ElemTy = StrTy->getElementType(i);
8205 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8206 switch (ElemTy->getTypeID()) {
8207 case llvm::Type::StructTyID:
8208 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8209 break;
8210 case llvm::Type::FloatTyID:
8211 addFloat(ElemOffset, ElemTy, 32);
8212 break;
8213 case llvm::Type::DoubleTyID:
8214 addFloat(ElemOffset, ElemTy, 64);
8215 break;
8216 case llvm::Type::FP128TyID:
8217 addFloat(ElemOffset, ElemTy, 128);
8218 break;
8219 case llvm::Type::PointerTyID:
8220 if (ElemOffset % 64 == 0) {
8221 pad(ElemOffset);
8222 Elems.push_back(ElemTy);
8223 Size += 64;
8224 }
8225 break;
8226 default:
8227 break;
8228 }
8229 }
8230 }
8231
8232 // Check if Ty is a usable substitute for the coercion type.
8233 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00008234 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008235 }
8236
8237 // Get the coercion type as a literal struct type.
8238 llvm::Type *getType() const {
8239 if (Elems.size() == 1)
8240 return Elems.front();
8241 else
8242 return llvm::StructType::get(Context, Elems);
8243 }
8244 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008245};
8246} // end anonymous namespace
8247
8248ABIArgInfo
8249SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8250 if (Ty->isVoidType())
8251 return ABIArgInfo::getIgnore();
8252
8253 uint64_t Size = getContext().getTypeSize(Ty);
8254
8255 // Anything too big to fit in registers is passed with an explicit indirect
8256 // pointer / sret pointer.
8257 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00008258 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008259
8260 // Treat an enum type as its underlying type.
8261 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8262 Ty = EnumTy->getDecl()->getIntegerType();
8263
8264 // Integer types smaller than a register are extended.
8265 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00008266 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008267
8268 // Other non-aggregates go in registers.
8269 if (!isAggregateTypeForABI(Ty))
8270 return ABIArgInfo::getDirect();
8271
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008272 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8273 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8274 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00008275 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008276
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008277 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008278 // Build a coercion type from the LLVM struct type.
8279 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8280 if (!StrTy)
8281 return ABIArgInfo::getDirect();
8282
8283 CoerceBuilder CB(getVMContext(), getDataLayout());
8284 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008285 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008286
8287 // Try to use the original type for coercion.
8288 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8289
8290 if (CB.InReg)
8291 return ABIArgInfo::getDirectInReg(CoerceTy);
8292 else
8293 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008294}
8295
John McCall7f416cc2015-09-08 08:05:57 +00008296Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8297 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008298 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8299 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8300 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8301 AI.setCoerceToType(ArgTy);
8302
John McCall7f416cc2015-09-08 08:05:57 +00008303 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008304
John McCall7f416cc2015-09-08 08:05:57 +00008305 CGBuilderTy &Builder = CGF.Builder;
8306 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8307 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8308
8309 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8310
8311 Address ArgAddr = Address::invalid();
8312 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008313 switch (AI.getKind()) {
8314 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008315 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008316 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008317 llvm_unreachable("Unsupported ABI kind for va_arg");
8318
John McCall7f416cc2015-09-08 08:05:57 +00008319 case ABIArgInfo::Extend: {
8320 Stride = SlotSize;
8321 CharUnits Offset = SlotSize - TypeInfo.first;
8322 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008323 break;
John McCall7f416cc2015-09-08 08:05:57 +00008324 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008325
John McCall7f416cc2015-09-08 08:05:57 +00008326 case ABIArgInfo::Direct: {
8327 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008328 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008329 ArgAddr = Addr;
8330 break;
John McCall7f416cc2015-09-08 08:05:57 +00008331 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008332
8333 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008334 Stride = SlotSize;
8335 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8336 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8337 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008338 break;
8339
8340 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008341 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008342 }
8343
8344 // Update VAList.
James Y Knight3d2df5a2019-02-05 19:01:33 +00008345 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
8346 Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008347
John McCall7f416cc2015-09-08 08:05:57 +00008348 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008349}
8350
8351void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8352 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008353 for (auto &I : FI.arguments())
8354 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008355}
8356
8357namespace {
8358class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8359public:
8360 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8361 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008362
Craig Topper4f12f102014-03-12 06:41:41 +00008363 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008364 return 14;
8365 }
8366
8367 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008368 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008369};
8370} // end anonymous namespace
8371
Roman Divackyf02c9942014-02-24 18:46:27 +00008372bool
8373SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8374 llvm::Value *Address) const {
8375 // This is calculated from the LLVM and GCC tables and verified
8376 // against gcc output. AFAIK all ABIs use the same encoding.
8377
8378 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8379
8380 llvm::IntegerType *i8 = CGF.Int8Ty;
8381 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8382 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8383
8384 // 0-31: the 8-byte general-purpose registers
8385 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8386
8387 // 32-63: f0-31, the 4-byte floating-point registers
8388 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8389
8390 // Y = 64
8391 // PSR = 65
8392 // WIM = 66
8393 // TBR = 67
8394 // PC = 68
8395 // NPC = 69
8396 // FSR = 70
8397 // CSR = 71
8398 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008399
Roman Divackyf02c9942014-02-24 18:46:27 +00008400 // 72-87: d0-15, the 8-byte floating-point registers
8401 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8402
8403 return false;
8404}
8405
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008406// ARC ABI implementation.
8407namespace {
8408
8409class ARCABIInfo : public DefaultABIInfo {
8410public:
8411 using DefaultABIInfo::DefaultABIInfo;
8412
8413private:
8414 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8415 QualType Ty) const override;
8416
8417 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
8418 if (!State.FreeRegs)
8419 return;
8420 if (Info.isIndirect() && Info.getInReg())
8421 State.FreeRegs--;
8422 else if (Info.isDirect() && Info.getInReg()) {
8423 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
8424 if (sz < State.FreeRegs)
8425 State.FreeRegs -= sz;
8426 else
8427 State.FreeRegs = 0;
8428 }
8429 }
8430
8431 void computeInfo(CGFunctionInfo &FI) const override {
8432 CCState State(FI.getCallingConvention());
8433 // ARC uses 8 registers to pass arguments.
8434 State.FreeRegs = 8;
8435
8436 if (!getCXXABI().classifyReturnType(FI))
8437 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8438 updateState(FI.getReturnInfo(), FI.getReturnType(), State);
8439 for (auto &I : FI.arguments()) {
8440 I.info = classifyArgumentType(I.type, State.FreeRegs);
8441 updateState(I.info, I.type, State);
8442 }
8443 }
8444
8445 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
8446 ABIArgInfo getIndirectByValue(QualType Ty) const;
8447 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
8448 ABIArgInfo classifyReturnType(QualType RetTy) const;
8449};
8450
8451class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
8452public:
8453 ARCTargetCodeGenInfo(CodeGenTypes &CGT)
8454 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {}
8455};
8456
8457
8458ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
8459 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
8460 getNaturalAlignIndirect(Ty, false);
8461}
8462
8463ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
Daniel Dunbara39bab32019-01-03 23:24:50 +00008464 // Compute the byval alignment.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008465 const unsigned MinABIStackAlignInBytes = 4;
8466 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8467 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8468 TypeAlign > MinABIStackAlignInBytes);
8469}
8470
8471Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8472 QualType Ty) const {
8473 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8474 getContext().getTypeInfoInChars(Ty),
8475 CharUnits::fromQuantity(4), true);
8476}
8477
8478ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
8479 uint8_t FreeRegs) const {
8480 // Handle the generic C++ ABI.
8481 const RecordType *RT = Ty->getAs<RecordType>();
8482 if (RT) {
8483 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8484 if (RAA == CGCXXABI::RAA_Indirect)
8485 return getIndirectByRef(Ty, FreeRegs > 0);
8486
8487 if (RAA == CGCXXABI::RAA_DirectInMemory)
8488 return getIndirectByValue(Ty);
8489 }
8490
8491 // Treat an enum type as its underlying type.
8492 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8493 Ty = EnumTy->getDecl()->getIntegerType();
8494
8495 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
8496
8497 if (isAggregateTypeForABI(Ty)) {
8498 // Structures with flexible arrays are always indirect.
8499 if (RT && RT->getDecl()->hasFlexibleArrayMember())
8500 return getIndirectByValue(Ty);
8501
8502 // Ignore empty structs/unions.
8503 if (isEmptyRecord(getContext(), Ty, true))
8504 return ABIArgInfo::getIgnore();
8505
8506 llvm::LLVMContext &LLVMContext = getVMContext();
8507
8508 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8509 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8510 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8511
8512 return FreeRegs >= SizeInRegs ?
8513 ABIArgInfo::getDirectInReg(Result) :
8514 ABIArgInfo::getDirect(Result, 0, nullptr, false);
8515 }
8516
8517 return Ty->isPromotableIntegerType() ?
8518 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) :
8519 ABIArgInfo::getExtend(Ty)) :
8520 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() :
8521 ABIArgInfo::getDirect());
8522}
8523
8524ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
8525 if (RetTy->isAnyComplexType())
8526 return ABIArgInfo::getDirectInReg();
8527
Daniel Dunbara39bab32019-01-03 23:24:50 +00008528 // Arguments of size > 4 registers are indirect.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008529 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
8530 if (RetSize > 4)
8531 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
8532
8533 return DefaultABIInfo::classifyReturnType(RetTy);
8534}
8535
8536} // End anonymous namespace.
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008537
Robert Lytton0e076492013-08-13 09:43:10 +00008538//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008539// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008540//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008541
Robert Lytton0e076492013-08-13 09:43:10 +00008542namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008543
8544/// A SmallStringEnc instance is used to build up the TypeString by passing
8545/// it by reference between functions that append to it.
8546typedef llvm::SmallString<128> SmallStringEnc;
8547
8548/// TypeStringCache caches the meta encodings of Types.
8549///
8550/// The reason for caching TypeStrings is two fold:
8551/// 1. To cache a type's encoding for later uses;
8552/// 2. As a means to break recursive member type inclusion.
8553///
8554/// A cache Entry can have a Status of:
8555/// NonRecursive: The type encoding is not recursive;
8556/// Recursive: The type encoding is recursive;
8557/// Incomplete: An incomplete TypeString;
8558/// IncompleteUsed: An incomplete TypeString that has been used in a
8559/// Recursive type encoding.
8560///
8561/// A NonRecursive entry will have all of its sub-members expanded as fully
8562/// as possible. Whilst it may contain types which are recursive, the type
8563/// itself is not recursive and thus its encoding may be safely used whenever
8564/// the type is encountered.
8565///
8566/// A Recursive entry will have all of its sub-members expanded as fully as
8567/// possible. The type itself is recursive and it may contain other types which
8568/// are recursive. The Recursive encoding must not be used during the expansion
8569/// of a recursive type's recursive branch. For simplicity the code uses
8570/// IncompleteCount to reject all usage of Recursive encodings for member types.
8571///
8572/// An Incomplete entry is always a RecordType and only encodes its
8573/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8574/// are placed into the cache during type expansion as a means to identify and
8575/// handle recursive inclusion of types as sub-members. If there is recursion
8576/// the entry becomes IncompleteUsed.
8577///
8578/// During the expansion of a RecordType's members:
8579///
8580/// If the cache contains a NonRecursive encoding for the member type, the
8581/// cached encoding is used;
8582///
8583/// If the cache contains a Recursive encoding for the member type, the
8584/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8585///
8586/// If the member is a RecordType, an Incomplete encoding is placed into the
8587/// cache to break potential recursive inclusion of itself as a sub-member;
8588///
8589/// Once a member RecordType has been expanded, its temporary incomplete
8590/// entry is removed from the cache. If a Recursive encoding was swapped out
8591/// it is swapped back in;
8592///
8593/// If an incomplete entry is used to expand a sub-member, the incomplete
8594/// entry is marked as IncompleteUsed. The cache keeps count of how many
8595/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8596///
8597/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8598/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8599/// Else the member is part of a recursive type and thus the recursion has
8600/// been exited too soon for the encoding to be correct for the member.
8601///
8602class TypeStringCache {
8603 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8604 struct Entry {
8605 std::string Str; // The encoded TypeString for the type.
8606 enum Status State; // Information about the encoding in 'Str'.
8607 std::string Swapped; // A temporary place holder for a Recursive encoding
8608 // during the expansion of RecordType's members.
8609 };
8610 std::map<const IdentifierInfo *, struct Entry> Map;
8611 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8612 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8613public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008614 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008615 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8616 bool removeIncomplete(const IdentifierInfo *ID);
8617 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8618 bool IsRecursive);
8619 StringRef lookupStr(const IdentifierInfo *ID);
8620};
8621
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008622/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008623/// FieldEncoding is a helper for this ordering process.
8624class FieldEncoding {
8625 bool HasName;
8626 std::string Enc;
8627public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008628 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008629 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008630 bool operator<(const FieldEncoding &rhs) const {
8631 if (HasName != rhs.HasName) return HasName;
8632 return Enc < rhs.Enc;
8633 }
8634};
8635
Robert Lytton7d1db152013-08-19 09:46:39 +00008636class XCoreABIInfo : public DefaultABIInfo {
8637public:
8638 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008639 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8640 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008641};
8642
Robert Lyttond21e2d72014-03-03 13:45:29 +00008643class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008644 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008645public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008646 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008647 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008648 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8649 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008650};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008651
Robert Lytton2d196952013-10-11 10:29:34 +00008652} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008653
James Y Knight29b5f082016-02-24 02:59:33 +00008654// TODO: this implementation is likely now redundant with the default
8655// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008656Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8657 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008658 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008659
Robert Lytton2d196952013-10-11 10:29:34 +00008660 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008661 CharUnits SlotSize = CharUnits::fromQuantity(4);
8662 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008663
Robert Lytton2d196952013-10-11 10:29:34 +00008664 // Handle the argument.
8665 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008666 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008667 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8668 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8669 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008670 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008671
8672 Address Val = Address::invalid();
8673 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008674 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008675 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008676 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008677 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008678 llvm_unreachable("Unsupported ABI kind for va_arg");
8679 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008680 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8681 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008682 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008683 case ABIArgInfo::Extend:
8684 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008685 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8686 ArgSize = CharUnits::fromQuantity(
8687 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008688 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008689 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008690 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008691 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8692 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8693 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008694 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008695 }
Robert Lytton2d196952013-10-11 10:29:34 +00008696
8697 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008698 if (!ArgSize.isZero()) {
James Y Knight3d2df5a2019-02-05 19:01:33 +00008699 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
8700 Builder.CreateStore(APN.getPointer(), VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008701 }
John McCall7f416cc2015-09-08 08:05:57 +00008702
Robert Lytton2d196952013-10-11 10:29:34 +00008703 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008704}
Robert Lytton0e076492013-08-13 09:43:10 +00008705
Robert Lytton844aeeb2014-05-02 09:33:20 +00008706/// During the expansion of a RecordType, an incomplete TypeString is placed
8707/// into the cache as a means to identify and break recursion.
8708/// If there is a Recursive encoding in the cache, it is swapped out and will
8709/// be reinserted by removeIncomplete().
8710/// All other types of encoding should have been used rather than arriving here.
8711void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8712 std::string StubEnc) {
8713 if (!ID)
8714 return;
8715 Entry &E = Map[ID];
8716 assert( (E.Str.empty() || E.State == Recursive) &&
8717 "Incorrectly use of addIncomplete");
8718 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8719 E.Swapped.swap(E.Str); // swap out the Recursive
8720 E.Str.swap(StubEnc);
8721 E.State = Incomplete;
8722 ++IncompleteCount;
8723}
8724
8725/// Once the RecordType has been expanded, the temporary incomplete TypeString
8726/// must be removed from the cache.
8727/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8728/// Returns true if the RecordType was defined recursively.
8729bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8730 if (!ID)
8731 return false;
8732 auto I = Map.find(ID);
8733 assert(I != Map.end() && "Entry not present");
8734 Entry &E = I->second;
8735 assert( (E.State == Incomplete ||
8736 E.State == IncompleteUsed) &&
8737 "Entry must be an incomplete type");
8738 bool IsRecursive = false;
8739 if (E.State == IncompleteUsed) {
8740 // We made use of our Incomplete encoding, thus we are recursive.
8741 IsRecursive = true;
8742 --IncompleteUsedCount;
8743 }
8744 if (E.Swapped.empty())
8745 Map.erase(I);
8746 else {
8747 // Swap the Recursive back.
8748 E.Swapped.swap(E.Str);
8749 E.Swapped.clear();
8750 E.State = Recursive;
8751 }
8752 --IncompleteCount;
8753 return IsRecursive;
8754}
8755
8756/// Add the encoded TypeString to the cache only if it is NonRecursive or
8757/// Recursive (viz: all sub-members were expanded as fully as possible).
8758void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8759 bool IsRecursive) {
8760 if (!ID || IncompleteUsedCount)
8761 return; // No key or it is is an incomplete sub-type so don't add.
8762 Entry &E = Map[ID];
8763 if (IsRecursive && !E.Str.empty()) {
8764 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8765 "This is not the same Recursive entry");
8766 // The parent container was not recursive after all, so we could have used
8767 // this Recursive sub-member entry after all, but we assumed the worse when
8768 // we started viz: IncompleteCount!=0.
8769 return;
8770 }
8771 assert(E.Str.empty() && "Entry already present");
8772 E.Str = Str.str();
8773 E.State = IsRecursive? Recursive : NonRecursive;
8774}
8775
8776/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8777/// are recursively expanding a type (IncompleteCount != 0) and the cached
8778/// encoding is Recursive, return an empty StringRef.
8779StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8780 if (!ID)
8781 return StringRef(); // We have no key.
8782 auto I = Map.find(ID);
8783 if (I == Map.end())
8784 return StringRef(); // We have no encoding.
8785 Entry &E = I->second;
8786 if (E.State == Recursive && IncompleteCount)
8787 return StringRef(); // We don't use Recursive encodings for member types.
8788
8789 if (E.State == Incomplete) {
8790 // The incomplete type is being used to break out of recursion.
8791 E.State = IncompleteUsed;
8792 ++IncompleteUsedCount;
8793 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008794 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008795}
8796
8797/// The XCore ABI includes a type information section that communicates symbol
8798/// type information to the linker. The linker uses this information to verify
8799/// safety/correctness of things such as array bound and pointers et al.
8800/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8801/// This type information (TypeString) is emitted into meta data for all global
8802/// symbols: definitions, declarations, functions & variables.
8803///
8804/// The TypeString carries type, qualifier, name, size & value details.
8805/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008806/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008807/// The output is tested by test/CodeGen/xcore-stringtype.c.
8808///
8809static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8810 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8811
8812/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8813void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8814 CodeGen::CodeGenModule &CGM) const {
8815 SmallStringEnc Enc;
8816 if (getTypeString(Enc, D, CGM, TSC)) {
8817 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008818 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8819 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008820 llvm::NamedMDNode *MD =
8821 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8822 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8823 }
8824}
8825
Xiuli Pan972bea82016-03-24 03:57:17 +00008826//===----------------------------------------------------------------------===//
8827// SPIR ABI Implementation
8828//===----------------------------------------------------------------------===//
8829
8830namespace {
8831class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8832public:
8833 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8834 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008835 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008836};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008837
Xiuli Pan972bea82016-03-24 03:57:17 +00008838} // End anonymous namespace.
8839
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008840namespace clang {
8841namespace CodeGen {
8842void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8843 DefaultABIInfo SPIRABI(CGM.getTypes());
8844 SPIRABI.computeInfo(FI);
8845}
8846}
8847}
8848
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008849unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8850 return llvm::CallingConv::SPIR_KERNEL;
8851}
8852
Robert Lytton844aeeb2014-05-02 09:33:20 +00008853static bool appendType(SmallStringEnc &Enc, QualType QType,
8854 const CodeGen::CodeGenModule &CGM,
8855 TypeStringCache &TSC);
8856
8857/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008858/// Builds a SmallVector containing the encoded field types in declaration
8859/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008860static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8861 const RecordDecl *RD,
8862 const CodeGen::CodeGenModule &CGM,
8863 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008864 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008865 SmallStringEnc Enc;
8866 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008867 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008868 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008869 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008870 Enc += "b(";
8871 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008872 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008873 Enc += ':';
8874 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008875 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008876 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008877 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008878 Enc += ')';
8879 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008880 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008881 }
8882 return true;
8883}
8884
8885/// Appends structure and union types to Enc and adds encoding to cache.
8886/// Recursively calls appendType (via extractFieldType) for each field.
8887/// Union types have their fields ordered according to the ABI.
8888static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8889 const CodeGen::CodeGenModule &CGM,
8890 TypeStringCache &TSC, const IdentifierInfo *ID) {
8891 // Append the cached TypeString if we have one.
8892 StringRef TypeString = TSC.lookupStr(ID);
8893 if (!TypeString.empty()) {
8894 Enc += TypeString;
8895 return true;
8896 }
8897
8898 // Start to emit an incomplete TypeString.
8899 size_t Start = Enc.size();
8900 Enc += (RT->isUnionType()? 'u' : 's');
8901 Enc += '(';
8902 if (ID)
8903 Enc += ID->getName();
8904 Enc += "){";
8905
8906 // We collect all encoded fields and order as necessary.
8907 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008908 const RecordDecl *RD = RT->getDecl()->getDefinition();
8909 if (RD && !RD->field_empty()) {
8910 // An incomplete TypeString stub is placed in the cache for this RecordType
8911 // so that recursive calls to this RecordType will use it whilst building a
8912 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008913 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008914 std::string StubEnc(Enc.substr(Start).str());
8915 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8916 TSC.addIncomplete(ID, std::move(StubEnc));
8917 if (!extractFieldType(FE, RD, CGM, TSC)) {
8918 (void) TSC.removeIncomplete(ID);
8919 return false;
8920 }
8921 IsRecursive = TSC.removeIncomplete(ID);
8922 // The ABI requires unions to be sorted but not structures.
8923 // See FieldEncoding::operator< for sort algorithm.
8924 if (RT->isUnionType())
Fangrui Song55fab262018-09-26 22:16:28 +00008925 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008926 // We can now complete the TypeString.
8927 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008928 for (unsigned I = 0; I != E; ++I) {
8929 if (I)
8930 Enc += ',';
8931 Enc += FE[I].str();
8932 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008933 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008934 Enc += '}';
8935 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8936 return true;
8937}
8938
8939/// Appends enum types to Enc and adds the encoding to the cache.
8940static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8941 TypeStringCache &TSC,
8942 const IdentifierInfo *ID) {
8943 // Append the cached TypeString if we have one.
8944 StringRef TypeString = TSC.lookupStr(ID);
8945 if (!TypeString.empty()) {
8946 Enc += TypeString;
8947 return true;
8948 }
8949
8950 size_t Start = Enc.size();
8951 Enc += "e(";
8952 if (ID)
8953 Enc += ID->getName();
8954 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008955
8956 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008957 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008958 SmallVector<FieldEncoding, 16> FE;
8959 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8960 ++I) {
8961 SmallStringEnc EnumEnc;
8962 EnumEnc += "m(";
8963 EnumEnc += I->getName();
8964 EnumEnc += "){";
8965 I->getInitVal().toString(EnumEnc);
8966 EnumEnc += '}';
8967 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8968 }
Fangrui Song55fab262018-09-26 22:16:28 +00008969 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008970 unsigned E = FE.size();
8971 for (unsigned I = 0; I != E; ++I) {
8972 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008973 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008974 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008975 }
8976 }
8977 Enc += '}';
8978 TSC.addIfComplete(ID, Enc.substr(Start), false);
8979 return true;
8980}
8981
8982/// Appends type's qualifier to Enc.
8983/// This is done prior to appending the type's encoding.
8984static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8985 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008986 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008987 int Lookup = 0;
8988 if (QT.isConstQualified())
8989 Lookup += 1<<0;
8990 if (QT.isRestrictQualified())
8991 Lookup += 1<<1;
8992 if (QT.isVolatileQualified())
8993 Lookup += 1<<2;
8994 Enc += Table[Lookup];
8995}
8996
8997/// Appends built-in types to Enc.
8998static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8999 const char *EncType;
9000 switch (BT->getKind()) {
9001 case BuiltinType::Void:
9002 EncType = "0";
9003 break;
9004 case BuiltinType::Bool:
9005 EncType = "b";
9006 break;
9007 case BuiltinType::Char_U:
9008 EncType = "uc";
9009 break;
9010 case BuiltinType::UChar:
9011 EncType = "uc";
9012 break;
9013 case BuiltinType::SChar:
9014 EncType = "sc";
9015 break;
9016 case BuiltinType::UShort:
9017 EncType = "us";
9018 break;
9019 case BuiltinType::Short:
9020 EncType = "ss";
9021 break;
9022 case BuiltinType::UInt:
9023 EncType = "ui";
9024 break;
9025 case BuiltinType::Int:
9026 EncType = "si";
9027 break;
9028 case BuiltinType::ULong:
9029 EncType = "ul";
9030 break;
9031 case BuiltinType::Long:
9032 EncType = "sl";
9033 break;
9034 case BuiltinType::ULongLong:
9035 EncType = "ull";
9036 break;
9037 case BuiltinType::LongLong:
9038 EncType = "sll";
9039 break;
9040 case BuiltinType::Float:
9041 EncType = "ft";
9042 break;
9043 case BuiltinType::Double:
9044 EncType = "d";
9045 break;
9046 case BuiltinType::LongDouble:
9047 EncType = "ld";
9048 break;
9049 default:
9050 return false;
9051 }
9052 Enc += EncType;
9053 return true;
9054}
9055
9056/// Appends a pointer encoding to Enc before calling appendType for the pointee.
9057static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
9058 const CodeGen::CodeGenModule &CGM,
9059 TypeStringCache &TSC) {
9060 Enc += "p(";
9061 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
9062 return false;
9063 Enc += ')';
9064 return true;
9065}
9066
9067/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009068static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
9069 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00009070 const CodeGen::CodeGenModule &CGM,
9071 TypeStringCache &TSC, StringRef NoSizeEnc) {
9072 if (AT->getSizeModifier() != ArrayType::Normal)
9073 return false;
9074 Enc += "a(";
9075 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
9076 CAT->getSize().toStringUnsigned(Enc);
9077 else
9078 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
9079 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00009080 // The Qualifiers should be attached to the type rather than the array.
9081 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00009082 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
9083 return false;
9084 Enc += ')';
9085 return true;
9086}
9087
9088/// Appends a function encoding to Enc, calling appendType for the return type
9089/// and the arguments.
9090static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
9091 const CodeGen::CodeGenModule &CGM,
9092 TypeStringCache &TSC) {
9093 Enc += "f{";
9094 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
9095 return false;
9096 Enc += "}(";
9097 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
9098 // N.B. we are only interested in the adjusted param types.
9099 auto I = FPT->param_type_begin();
9100 auto E = FPT->param_type_end();
9101 if (I != E) {
9102 do {
9103 if (!appendType(Enc, *I, CGM, TSC))
9104 return false;
9105 ++I;
9106 if (I != E)
9107 Enc += ',';
9108 } while (I != E);
9109 if (FPT->isVariadic())
9110 Enc += ",va";
9111 } else {
9112 if (FPT->isVariadic())
9113 Enc += "va";
9114 else
9115 Enc += '0';
9116 }
9117 }
9118 Enc += ')';
9119 return true;
9120}
9121
9122/// Handles the type's qualifier before dispatching a call to handle specific
9123/// type encodings.
9124static bool appendType(SmallStringEnc &Enc, QualType QType,
9125 const CodeGen::CodeGenModule &CGM,
9126 TypeStringCache &TSC) {
9127
9128 QualType QT = QType.getCanonicalType();
9129
Robert Lytton6adb20f2014-06-05 09:06:21 +00009130 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
9131 // The Qualifiers should be attached to the type rather than the array.
9132 // Thus we don't call appendQualifier() here.
9133 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
9134
Robert Lytton844aeeb2014-05-02 09:33:20 +00009135 appendQualifier(Enc, QT);
9136
9137 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
9138 return appendBuiltinType(Enc, BT);
9139
Robert Lytton844aeeb2014-05-02 09:33:20 +00009140 if (const PointerType *PT = QT->getAs<PointerType>())
9141 return appendPointerType(Enc, PT, CGM, TSC);
9142
9143 if (const EnumType *ET = QT->getAs<EnumType>())
9144 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9145
9146 if (const RecordType *RT = QT->getAsStructureType())
9147 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9148
9149 if (const RecordType *RT = QT->getAsUnionType())
9150 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9151
9152 if (const FunctionType *FT = QT->getAs<FunctionType>())
9153 return appendFunctionType(Enc, FT, CGM, TSC);
9154
9155 return false;
9156}
9157
9158static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9159 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9160 if (!D)
9161 return false;
9162
9163 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9164 if (FD->getLanguageLinkage() != CLanguageLinkage)
9165 return false;
9166 return appendType(Enc, FD->getType(), CGM, TSC);
9167 }
9168
9169 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9170 if (VD->getLanguageLinkage() != CLanguageLinkage)
9171 return false;
9172 QualType QT = VD->getType().getCanonicalType();
9173 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9174 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009175 // The Qualifiers should be attached to the type rather than the array.
9176 // Thus we don't call appendQualifier() here.
9177 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00009178 }
9179 return appendType(Enc, QT, CGM, TSC);
9180 }
9181 return false;
9182}
9183
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009184//===----------------------------------------------------------------------===//
9185// RISCV ABI Implementation
9186//===----------------------------------------------------------------------===//
9187
9188namespace {
9189class RISCVABIInfo : public DefaultABIInfo {
9190private:
9191 unsigned XLen; // Size of the integer ('x') registers in bits.
9192 static const int NumArgGPRs = 8;
9193
9194public:
9195 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
9196 : DefaultABIInfo(CGT), XLen(XLen) {}
9197
9198 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9199 // non-virtual, but computeInfo is virtual, so we overload it.
9200 void computeInfo(CGFunctionInfo &FI) const override;
9201
9202 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed,
9203 int &ArgGPRsLeft) const;
9204 ABIArgInfo classifyReturnType(QualType RetTy) const;
9205
9206 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9207 QualType Ty) const override;
9208
9209 ABIArgInfo extendType(QualType Ty) const;
9210};
9211} // end anonymous namespace
9212
9213void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9214 QualType RetTy = FI.getReturnType();
9215 if (!getCXXABI().classifyReturnType(FI))
9216 FI.getReturnInfo() = classifyReturnType(RetTy);
9217
9218 // IsRetIndirect is true if classifyArgumentType indicated the value should
9219 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
9220 // is passed direct in LLVM IR, relying on the backend lowering code to
9221 // rewrite the argument list and pass indirectly on RV32.
9222 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
9223 getContext().getTypeSize(RetTy) > (2 * XLen);
9224
9225 // We must track the number of GPRs used in order to conform to the RISC-V
9226 // ABI, as integer scalars passed in registers should have signext/zeroext
9227 // when promoted, but are anyext if passed on the stack. As GPR usage is
9228 // different for variadic arguments, we must also track whether we are
9229 // examining a vararg or not.
9230 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
9231 int NumFixedArgs = FI.getNumRequiredArgs();
9232
9233 int ArgNum = 0;
9234 for (auto &ArgInfo : FI.arguments()) {
9235 bool IsFixed = ArgNum < NumFixedArgs;
9236 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft);
9237 ArgNum++;
9238 }
9239}
9240
9241ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
9242 int &ArgGPRsLeft) const {
9243 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
9244 Ty = useFirstFieldIfTransparentUnion(Ty);
9245
9246 // Structures with either a non-trivial destructor or a non-trivial
9247 // copy constructor are always passed indirectly.
9248 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
9249 if (ArgGPRsLeft)
9250 ArgGPRsLeft -= 1;
9251 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
9252 CGCXXABI::RAA_DirectInMemory);
9253 }
9254
9255 // Ignore empty structs/unions.
9256 if (isEmptyRecord(getContext(), Ty, true))
9257 return ABIArgInfo::getIgnore();
9258
9259 uint64_t Size = getContext().getTypeSize(Ty);
9260 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
9261 bool MustUseStack = false;
9262 // Determine the number of GPRs needed to pass the current argument
9263 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
9264 // register pairs, so may consume 3 registers.
9265 int NeededArgGPRs = 1;
9266 if (!IsFixed && NeededAlign == 2 * XLen)
9267 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
9268 else if (Size > XLen && Size <= 2 * XLen)
9269 NeededArgGPRs = 2;
9270
9271 if (NeededArgGPRs > ArgGPRsLeft) {
9272 MustUseStack = true;
9273 NeededArgGPRs = ArgGPRsLeft;
9274 }
9275
9276 ArgGPRsLeft -= NeededArgGPRs;
9277
9278 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
9279 // Treat an enum type as its underlying type.
9280 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9281 Ty = EnumTy->getDecl()->getIntegerType();
9282
9283 // All integral types are promoted to XLen width, unless passed on the
9284 // stack.
9285 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9286 return extendType(Ty);
9287 }
9288
9289 return ABIArgInfo::getDirect();
9290 }
9291
9292 // Aggregates which are <= 2*XLen will be passed in registers if possible,
9293 // so coerce to integers.
9294 if (Size <= 2 * XLen) {
9295 unsigned Alignment = getContext().getTypeAlign(Ty);
9296
9297 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9298 // required, and a 2-element XLen array if only XLen alignment is required.
9299 if (Size <= XLen) {
9300 return ABIArgInfo::getDirect(
9301 llvm::IntegerType::get(getVMContext(), XLen));
9302 } else if (Alignment == 2 * XLen) {
9303 return ABIArgInfo::getDirect(
9304 llvm::IntegerType::get(getVMContext(), 2 * XLen));
9305 } else {
9306 return ABIArgInfo::getDirect(llvm::ArrayType::get(
9307 llvm::IntegerType::get(getVMContext(), XLen), 2));
9308 }
9309 }
9310 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9311}
9312
9313ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9314 if (RetTy->isVoidType())
9315 return ABIArgInfo::getIgnore();
9316
9317 int ArgGPRsLeft = 2;
9318
9319 // The rules for return and argument types are the same, so defer to
9320 // classifyArgumentType.
9321 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft);
9322}
9323
9324Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9325 QualType Ty) const {
9326 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9327
9328 // Empty records are ignored for parameter passing purposes.
9329 if (isEmptyRecord(getContext(), Ty, true)) {
9330 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9331 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9332 return Addr;
9333 }
9334
9335 std::pair<CharUnits, CharUnits> SizeAndAlign =
9336 getContext().getTypeInfoInChars(Ty);
9337
9338 // Arguments bigger than 2*Xlen bytes are passed indirectly.
9339 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9340
9341 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9342 SlotSize, /*AllowHigherAlign=*/true);
9343}
9344
9345ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9346 int TySize = getContext().getTypeSize(Ty);
9347 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9348 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9349 return ABIArgInfo::getSignExtend(Ty);
9350 return ABIArgInfo::getExtend(Ty);
9351}
9352
9353namespace {
9354class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9355public:
9356 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
9357 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {}
Ana Pazos1eee1b72018-07-26 17:37:45 +00009358
9359 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9360 CodeGen::CodeGenModule &CGM) const override {
9361 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9362 if (!FD) return;
9363
9364 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9365 if (!Attr)
9366 return;
9367
9368 const char *Kind;
9369 switch (Attr->getInterrupt()) {
9370 case RISCVInterruptAttr::user: Kind = "user"; break;
9371 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9372 case RISCVInterruptAttr::machine: Kind = "machine"; break;
9373 }
9374
9375 auto *Fn = cast<llvm::Function>(GV);
9376
9377 Fn->addFnAttr("interrupt", Kind);
9378 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009379};
9380} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00009381
Robert Lytton0e076492013-08-13 09:43:10 +00009382//===----------------------------------------------------------------------===//
9383// Driver code
9384//===----------------------------------------------------------------------===//
9385
Rafael Espindola9f834732014-09-19 01:54:22 +00009386bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00009387 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00009388}
9389
Chris Lattner2b037972010-07-29 02:01:43 +00009390const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009391 if (TheTargetCodeGenInfo)
9392 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009393
Reid Kleckner9305fd12016-04-13 23:37:17 +00009394 // Helper to set the unique_ptr while still keeping the return value.
9395 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9396 this->TheTargetCodeGenInfo.reset(P);
9397 return *P;
9398 };
9399
John McCallc8e01702013-04-16 22:48:15 +00009400 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00009401 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00009402 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009403 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00009404
Derek Schuff09338a22012-09-06 17:37:28 +00009405 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009406 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00009407 case llvm::Triple::mips:
9408 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00009409 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00009410 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9411 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009412
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00009413 case llvm::Triple::mips64:
9414 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009415 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009416
Dylan McKaye8232d72017-02-08 05:09:26 +00009417 case llvm::Triple::avr:
9418 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9419
Tim Northover25e8a672014-05-24 12:51:25 +00009420 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00009421 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00009422 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00009423 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00009424 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00009425 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00009426 return SetCGInfo(
9427 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00009428
Reid Kleckner9305fd12016-04-13 23:37:17 +00009429 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009430 }
9431
Dan Gohmanc2853072015-09-03 22:51:53 +00009432 case llvm::Triple::wasm32:
9433 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009434 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009435
Daniel Dunbard59655c2009-09-12 00:59:49 +00009436 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009437 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009438 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009439 case llvm::Triple::thumbeb: {
9440 if (Triple.getOS() == llvm::Triple::Win32) {
9441 return SetCGInfo(
9442 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009443 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009444
Reid Kleckner9305fd12016-04-13 23:37:17 +00009445 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9446 StringRef ABIStr = getTarget().getABI();
9447 if (ABIStr == "apcs-gnu")
9448 Kind = ARMABIInfo::APCS;
9449 else if (ABIStr == "aapcs16")
9450 Kind = ARMABIInfo::AAPCS16_VFP;
9451 else if (CodeGenOpts.FloatABI == "hard" ||
9452 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009453 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009454 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009455 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009456 Kind = ARMABIInfo::AAPCS_VFP;
9457
9458 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9459 }
9460
John McCallea8d8bb2010-03-11 00:10:12 +00009461 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009462 return SetCGInfo(
9463 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00009464 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009465 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009466 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009467 if (getTarget().getABI() == "elfv2")
9468 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009469 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009470 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009471
Hal Finkel415c2a32016-10-02 02:10:45 +00009472 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9473 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009474 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009475 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009476 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009477 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009478 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009479 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009480 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009481 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009482 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009483
Hal Finkel415c2a32016-10-02 02:10:45 +00009484 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9485 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009486 }
John McCallea8d8bb2010-03-11 00:10:12 +00009487
Peter Collingbournec947aae2012-05-20 23:28:41 +00009488 case llvm::Triple::nvptx:
9489 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009490 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009491
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009492 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009493 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009494
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009495 case llvm::Triple::riscv32:
9496 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32));
9497 case llvm::Triple::riscv64:
9498 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64));
9499
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009500 case llvm::Triple::systemz: {
9501 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009502 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009503 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009504
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009505 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009506 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009507 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009508
Eli Friedman33465822011-07-08 23:31:17 +00009509 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009510 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009511 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009512 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009513 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009514
John McCall1fe2a8c2013-06-18 02:46:29 +00009515 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009516 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9517 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9518 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009519 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009520 return SetCGInfo(new X86_32TargetCodeGenInfo(
9521 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9522 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
Hans Wennborgd874c052019-06-19 11:34:08 +00009523 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009524 }
Eli Friedman33465822011-07-08 23:31:17 +00009525 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009526
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009527 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009528 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009529 X86AVXABILevel AVXLevel =
9530 (ABI == "avx512"
9531 ? X86AVXABILevel::AVX512
9532 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009533
Chris Lattner04dc9572010-08-31 16:44:54 +00009534 switch (Triple.getOS()) {
9535 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009536 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009537 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009538 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009539 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009540 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009541 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009542 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009543 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009544 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009545 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009546 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009547 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009548 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009549 case llvm::Triple::sparc:
9550 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009551 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009552 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009553 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009554 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00009555 case llvm::Triple::arc:
9556 return SetCGInfo(new ARCTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009557 case llvm::Triple::spir:
9558 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009559 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009560 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009561}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009562
9563/// Create an OpenCL kernel for an enqueued block.
9564///
9565/// The kernel has the same function type as the block invoke function. Its
9566/// name is the name of the block invoke function postfixed with "_kernel".
9567/// It simply calls the block invoke function then returns.
9568llvm::Function *
9569TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9570 llvm::Function *Invoke,
9571 llvm::Value *BlockLiteral) const {
9572 auto *InvokeFT = Invoke->getFunctionType();
9573 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9574 for (auto &P : InvokeFT->params())
9575 ArgTys.push_back(P);
9576 auto &C = CGF.getLLVMContext();
9577 std::string Name = Invoke->getName().str() + "_kernel";
9578 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9579 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9580 &CGF.CGM.getModule());
9581 auto IP = CGF.Builder.saveIP();
9582 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9583 auto &Builder = CGF.Builder;
9584 Builder.SetInsertPoint(BB);
9585 llvm::SmallVector<llvm::Value *, 2> Args;
9586 for (auto &A : F->args())
9587 Args.push_back(&A);
9588 Builder.CreateCall(Invoke, Args);
9589 Builder.CreateRetVoid();
9590 Builder.restoreIP(IP);
9591 return F;
9592}
9593
9594/// Create an OpenCL kernel for an enqueued block.
9595///
9596/// The type of the first argument (the block literal) is the struct type
9597/// of the block literal instead of a pointer type. The first argument
9598/// (block literal) is passed directly by value to the kernel. The kernel
9599/// allocates the same type of struct on stack and stores the block literal
9600/// to it and passes its pointer to the block invoke function. The kernel
9601/// has "enqueued-block" function attribute and kernel argument metadata.
9602llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9603 CodeGenFunction &CGF, llvm::Function *Invoke,
9604 llvm::Value *BlockLiteral) const {
9605 auto &Builder = CGF.Builder;
9606 auto &C = CGF.getLLVMContext();
9607
9608 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9609 auto *InvokeFT = Invoke->getFunctionType();
9610 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9611 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9612 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9613 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9614 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9615 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9616 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9617
9618 ArgTys.push_back(BlockTy);
9619 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9620 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9621 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9622 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9623 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9624 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9625 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9626 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009627 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9628 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9629 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9630 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9631 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9632 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009633 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009634 }
9635 std::string Name = Invoke->getName().str() + "_kernel";
9636 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9637 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9638 &CGF.CGM.getModule());
9639 F->addFnAttr("enqueued-block");
9640 auto IP = CGF.Builder.saveIP();
9641 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9642 Builder.SetInsertPoint(BB);
9643 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9644 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9645 BlockPtr->setAlignment(BlockAlign);
9646 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9647 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9648 llvm::SmallVector<llvm::Value *, 2> Args;
9649 Args.push_back(Cast);
9650 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9651 Args.push_back(I);
9652 Builder.CreateCall(Invoke, Args);
9653 Builder.CreateRetVoid();
9654 Builder.restoreIP(IP);
9655
9656 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9657 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9658 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9659 F->setMetadata("kernel_arg_base_type",
9660 llvm::MDNode::get(C, ArgBaseTypeNames));
9661 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9662 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9663 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9664
9665 return F;
9666}