blob: 231a20c68f5a6bc7359f345fc9ac7c7ce995eaa9 [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 {
Guanzhong Chen82bfd1d2019-08-15 19:33:36 +0000836 bool IsIndirect = isAggregateTypeForABI(Ty) &&
837 !isEmptyRecord(getContext(), Ty, true) &&
838 !isSingleElementStruct(Ty, getContext());
Guanzhong Chen8a503e42019-08-13 21:41:11 +0000839 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000840 getContext().getTypeInfoInChars(Ty),
841 CharUnits::fromQuantity(4),
Guanzhong Chen8a503e42019-08-13 21:41:11 +0000842 /*AllowHigherAlign=*/true);
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000843}
844
Dan Gohmanc2853072015-09-03 22:51:53 +0000845//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000846// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000847//
848// This is a simplified version of the x86_32 ABI. Arguments and return values
849// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000850//===----------------------------------------------------------------------===//
851
852class PNaClABIInfo : public ABIInfo {
853 public:
854 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
855
856 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000857 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000858
Craig Topper4f12f102014-03-12 06:41:41 +0000859 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000860 Address EmitVAArg(CodeGenFunction &CGF,
861 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000862};
863
864class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
865 public:
866 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
867 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
868};
869
870void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000871 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000872 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
873
Reid Kleckner40ca9132014-05-13 22:05:45 +0000874 for (auto &I : FI.arguments())
875 I.info = classifyArgumentType(I.type);
876}
Derek Schuff09338a22012-09-06 17:37:28 +0000877
John McCall7f416cc2015-09-08 08:05:57 +0000878Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
879 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000880 // The PNaCL ABI is a bit odd, in that varargs don't use normal
881 // function classification. Structs get passed directly for varargs
882 // functions, through a rewriting transform in
883 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
884 // this target to actually support a va_arg instructions with an
885 // aggregate type, unlike other targets.
886 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000887}
888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000889/// Classify argument of given type \p Ty.
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000890ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000891 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000892 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000893 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
894 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000895 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
896 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000897 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000898 } else if (Ty->isFloatingType()) {
899 // Floating-point types don't go inreg.
900 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000901 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000902
Alex Bradburye41a5e22018-01-12 20:08:16 +0000903 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
904 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000905}
906
907ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
908 if (RetTy->isVoidType())
909 return ABIArgInfo::getIgnore();
910
Eli Benderskye20dad62013-04-04 22:49:35 +0000911 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000912 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000913 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000914
915 // Treat an enum type as its underlying type.
916 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
917 RetTy = EnumTy->getDecl()->getIntegerType();
918
Alex Bradburye41a5e22018-01-12 20:08:16 +0000919 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
920 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000921}
922
Hans Wennborgd874c052019-06-19 11:34:08 +0000923/// IsX86_MMXType - Return true if this is an MMX type.
924bool IsX86_MMXType(llvm::Type *IRType) {
925 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
926 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
927 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
928 IRType->getScalarSizeInBits() != 64;
929}
930
Jay Foad7c57be32011-07-11 09:56:20 +0000931static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000932 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000933 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000934 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
935 .Cases("y", "&y", "^Ym", true)
936 .Default(false);
937 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000938 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
939 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000940 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000941 }
942
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000943 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000944 }
945
946 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000947 return Ty;
948}
949
Reid Kleckner80944df2014-10-31 22:00:51 +0000950/// Returns true if this type can be passed in SSE registers with the
951/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
952static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
953 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000954 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
955 if (BT->getKind() == BuiltinType::LongDouble) {
956 if (&Context.getTargetInfo().getLongDoubleFormat() ==
957 &llvm::APFloat::x87DoubleExtended())
958 return false;
959 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000960 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000961 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000962 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
963 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
964 // registers specially.
965 unsigned VecSize = Context.getTypeSize(VT);
966 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
967 return true;
968 }
969 return false;
970}
971
972/// Returns true if this aggregate is small enough to be passed in SSE registers
973/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
974static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
975 return NumMembers <= 4;
976}
977
Erich Keane521ed962017-01-05 00:20:51 +0000978/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
979static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
980 auto AI = ABIArgInfo::getDirect(T);
981 AI.setInReg(true);
982 AI.setCanBeFlattened(false);
983 return AI;
984}
985
Chris Lattner0cf24192010-06-28 20:05:43 +0000986//===----------------------------------------------------------------------===//
987// X86-32 ABI Implementation
988//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000990/// Similar to llvm::CCState, but for Clang.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000991struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000992 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000993
994 unsigned CC;
995 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000996 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000997};
998
Erich Keane521ed962017-01-05 00:20:51 +0000999enum {
1000 // Vectorcall only allows the first 6 parameters to be passed in registers.
1001 VectorcallMaxParamNumAsReg = 6
1002};
1003
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001004/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001005class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001006 enum Class {
1007 Integer,
1008 Float
1009 };
1010
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001011 static const unsigned MinABIStackAlignInBytes = 4;
1012
David Chisnallde3a0692009-08-17 23:08:21 +00001013 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +00001014 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001015 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001016 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +00001017 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001018 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001019
1020 static bool isRegisterSize(unsigned Size) {
1021 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1022 }
1023
Reid Kleckner80944df2014-10-31 22:00:51 +00001024 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1025 // FIXME: Assumes vectorcall is in use.
1026 return isX86VectorTypeForVectorCall(getContext(), Ty);
1027 }
1028
1029 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1030 uint64_t NumMembers) const override {
1031 // FIXME: Assumes vectorcall is in use.
1032 return isX86VectorCallAggregateSmallEnough(NumMembers);
1033 }
1034
Reid Kleckner40ca9132014-05-13 22:05:45 +00001035 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001036
Daniel Dunbar557893d2010-04-21 19:10:51 +00001037 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1038 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +00001039 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1040
John McCall7f416cc2015-09-08 08:05:57 +00001041 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +00001042
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001043 /// Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001044 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001045
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001046 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +00001047 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001048 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +00001049
Fangrui Song6907ce22018-07-30 19:24:48 +00001050 /// Updates the number of available free registers, returns
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001051 /// true if any registers were allocated.
1052 bool updateFreeRegs(QualType Ty, CCState &State) const;
1053
1054 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1055 bool &NeedsPadding) const;
1056 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001057
Reid Kleckner04046052016-05-02 17:41:07 +00001058 bool canExpandIndirectArgument(QualType Ty) const;
1059
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001060 /// Rewrite the function info so that all memory arguments use
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001061 /// inalloca.
1062 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1063
1064 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001065 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001066 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001067 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1068 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001069
Rafael Espindola75419dc2012-07-23 23:30:29 +00001070public:
1071
Craig Topper4f12f102014-03-12 06:41:41 +00001072 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001073 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1074 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001075
Michael Kupersteindc745202015-10-19 07:52:25 +00001076 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1077 bool RetSmallStructInRegABI, bool Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001078 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001079 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Fangrui Song6907ce22018-07-30 19:24:48 +00001080 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001081 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001082 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001083 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Hans Wennborgd874c052019-06-19 11:34:08 +00001084 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001085
John McCall56331e22018-01-07 06:28:49 +00001086 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001087 bool asReturnValue) const override {
1088 // LLVM's x86-32 lowering currently only assigns up to three
1089 // integer registers and three fp registers. Oddly, it'll use up to
1090 // four vector registers for vectors, but those can overlap with the
1091 // scalar registers.
1092 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
Fangrui Song6907ce22018-07-30 19:24:48 +00001093 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001094
1095 bool isSwiftErrorInRegister() const override {
1096 // x86-32 lowering does not support passing swifterror in a register.
1097 return false;
1098 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001099};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001100
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001101class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1102public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001103 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1104 bool RetSmallStructInRegABI, bool Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001105 unsigned NumRegisterParameters, bool SoftFloatABI)
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001106 : TargetCodeGenInfo(new X86_32ABIInfo(
1107 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
Hans Wennborgd874c052019-06-19 11:34:08 +00001108 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001109
John McCall1fe2a8c2013-06-18 02:46:29 +00001110 static bool isStructReturnInRegABI(
1111 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1112
Eric Christopher162c91c2015-06-05 22:03:00 +00001113 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001114 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001115
Craig Topper4f12f102014-03-12 06:41:41 +00001116 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001117 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001118 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001119 return 4;
1120 }
1121
1122 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001123 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001124
Jay Foad7c57be32011-07-11 09:56:20 +00001125 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001126 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001127 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001128 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1129 }
1130
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001131 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1132 std::string &Constraints,
1133 std::vector<llvm::Type *> &ResultRegTypes,
1134 std::vector<llvm::Type *> &ResultTruncRegTypes,
1135 std::vector<LValue> &ResultRegDests,
1136 std::string &AsmString,
1137 unsigned NumOutputs) const override;
1138
Craig Topper4f12f102014-03-12 06:41:41 +00001139 llvm::Constant *
1140 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001141 unsigned Sig = (0xeb << 0) | // jmp rel8
1142 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001143 ('v' << 16) |
1144 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001145 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1146 }
John McCall01391782016-02-05 21:37:38 +00001147
1148 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1149 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001150 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001151 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001152};
1153
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001154}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001155
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001156/// Rewrite input constraint references after adding some output constraints.
1157/// In the case where there is one output and one input and we add one output,
1158/// we need to replace all operand references greater than or equal to 1:
1159/// mov $0, $1
1160/// mov eax, $1
1161/// The result will be:
1162/// mov $0, $2
1163/// mov eax, $2
1164static void rewriteInputConstraintReferences(unsigned FirstIn,
1165 unsigned NumNewOuts,
1166 std::string &AsmString) {
1167 std::string Buf;
1168 llvm::raw_string_ostream OS(Buf);
1169 size_t Pos = 0;
1170 while (Pos < AsmString.size()) {
1171 size_t DollarStart = AsmString.find('$', Pos);
1172 if (DollarStart == std::string::npos)
1173 DollarStart = AsmString.size();
1174 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1175 if (DollarEnd == std::string::npos)
1176 DollarEnd = AsmString.size();
1177 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1178 Pos = DollarEnd;
1179 size_t NumDollars = DollarEnd - DollarStart;
1180 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1181 // We have an operand reference.
1182 size_t DigitStart = Pos;
1183 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1184 if (DigitEnd == std::string::npos)
1185 DigitEnd = AsmString.size();
1186 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1187 unsigned OperandIndex;
1188 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1189 if (OperandIndex >= FirstIn)
1190 OperandIndex += NumNewOuts;
1191 OS << OperandIndex;
1192 } else {
1193 OS << OperandStr;
1194 }
1195 Pos = DigitEnd;
1196 }
1197 }
1198 AsmString = std::move(OS.str());
1199}
1200
1201/// Add output constraints for EAX:EDX because they are return registers.
1202void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1203 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1204 std::vector<llvm::Type *> &ResultRegTypes,
1205 std::vector<llvm::Type *> &ResultTruncRegTypes,
1206 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1207 unsigned NumOutputs) const {
1208 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1209
1210 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1211 // larger.
1212 if (!Constraints.empty())
1213 Constraints += ',';
1214 if (RetWidth <= 32) {
1215 Constraints += "={eax}";
1216 ResultRegTypes.push_back(CGF.Int32Ty);
1217 } else {
1218 // Use the 'A' constraint for EAX:EDX.
1219 Constraints += "=A";
1220 ResultRegTypes.push_back(CGF.Int64Ty);
1221 }
1222
1223 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1224 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1225 ResultTruncRegTypes.push_back(CoerceTy);
1226
1227 // Coerce the integer by bitcasting the return slot pointer.
1228 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1229 CoerceTy->getPointerTo()));
1230 ResultRegDests.push_back(ReturnSlot);
1231
1232 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1233}
1234
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001235/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001236/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001237bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1238 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001239 uint64_t Size = Context.getTypeSize(Ty);
1240
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001241 // For i386, type must be register sized.
1242 // For the MCU ABI, it only needs to be <= 8-byte
1243 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1244 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001245
1246 if (Ty->isVectorType()) {
1247 // 64- and 128- bit vectors inside structures are not returned in
1248 // registers.
1249 if (Size == 64 || Size == 128)
1250 return false;
1251
1252 return true;
1253 }
1254
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001255 // If this is a builtin, pointer, enum, complex type, member pointer, or
1256 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001257 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001258 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001259 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001260 return true;
1261
1262 // Arrays are treated like records.
1263 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001264 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001265
1266 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001267 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001268 if (!RT) return false;
1269
Anders Carlsson40446e82010-01-27 03:25:19 +00001270 // FIXME: Traverse bases here too.
1271
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001272 // Structure types are passed in register if all fields would be
1273 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001274 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001275 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001276 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001277 continue;
1278
1279 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001280 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001281 return false;
1282 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001283 return true;
1284}
1285
Reid Kleckner04046052016-05-02 17:41:07 +00001286static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1287 // Treat complex types as the element type.
1288 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1289 Ty = CTy->getElementType();
1290
1291 // Check for a type which we know has a simple scalar argument-passing
1292 // convention without any padding. (We're specifically looking for 32
1293 // and 64-bit integer and integer-equivalents, float, and double.)
1294 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1295 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1296 return false;
1297
1298 uint64_t Size = Context.getTypeSize(Ty);
1299 return Size == 32 || Size == 64;
1300}
1301
Reid Kleckner791bbf62017-01-13 17:18:19 +00001302static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1303 uint64_t &Size) {
1304 for (const auto *FD : RD->fields()) {
1305 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1306 // argument is smaller than 32-bits, expanding the struct will create
1307 // alignment padding.
1308 if (!is32Or64BitBasicType(FD->getType(), Context))
1309 return false;
1310
1311 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1312 // how to expand them yet, and the predicate for telling if a bitfield still
1313 // counts as "basic" is more complicated than what we were doing previously.
1314 if (FD->isBitField())
1315 return false;
1316
1317 Size += Context.getTypeSize(FD->getType());
1318 }
1319 return true;
1320}
1321
1322static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1323 uint64_t &Size) {
1324 // Don't do this if there are any non-empty bases.
1325 for (const CXXBaseSpecifier &Base : RD->bases()) {
1326 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1327 Size))
1328 return false;
1329 }
1330 if (!addFieldSizes(Context, RD, Size))
1331 return false;
1332 return true;
1333}
1334
Reid Kleckner04046052016-05-02 17:41:07 +00001335/// Test whether an argument type which is to be passed indirectly (on the
1336/// stack) would have the equivalent layout if it was expanded into separate
1337/// arguments. If so, we prefer to do the latter to avoid inhibiting
1338/// optimizations.
1339bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1340 // We can only expand structure types.
1341 const RecordType *RT = Ty->getAs<RecordType>();
1342 if (!RT)
1343 return false;
1344 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001345 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001346 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001347 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001348 // On non-Windows, we have to conservatively match our old bitcode
1349 // prototypes in order to be ABI-compatible at the bitcode level.
1350 if (!CXXRD->isCLike())
1351 return false;
1352 } else {
1353 // Don't do this for dynamic classes.
1354 if (CXXRD->isDynamicClass())
1355 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001356 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001357 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001358 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001359 } else {
1360 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001361 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001362 }
1363
1364 // We can do this if there was no alignment padding.
1365 return Size == getContext().getTypeSize(Ty);
1366}
1367
John McCall7f416cc2015-09-08 08:05:57 +00001368ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001369 // If the return value is indirect, then the hidden argument is consuming one
1370 // integer register.
1371 if (State.FreeRegs) {
1372 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001373 if (!IsMCUABI)
1374 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001375 }
John McCall7f416cc2015-09-08 08:05:57 +00001376 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001377}
1378
Eric Christopher7565e0d2015-05-29 23:09:49 +00001379ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1380 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001381 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001382 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001383
Reid Kleckner80944df2014-10-31 22:00:51 +00001384 const Type *Base = nullptr;
1385 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001386 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1387 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001388 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1389 // The LLVM struct type for such an aggregate should lower properly.
1390 return ABIArgInfo::getDirect();
1391 }
1392
Chris Lattner458b2aa2010-07-29 02:16:43 +00001393 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001394 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001395 if (IsDarwinVectorABI) {
Hans Wennborgd874c052019-06-19 11:34:08 +00001396 uint64_t Size = getContext().getTypeSize(RetTy);
1397
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001398 // 128-bit vectors are a special case; they are returned in
1399 // registers and we need to make sure to pick a type the LLVM
1400 // backend will like.
1401 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001402 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001403 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001404
1405 // Always return in register if it fits in a general purpose
1406 // register, or if it is 64 bits and has a single element.
1407 if ((Size == 8 || Size == 16 || Size == 32) ||
1408 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001409 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001410 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001411
John McCall7f416cc2015-09-08 08:05:57 +00001412 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001413 }
1414
1415 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001416 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001417
John McCalla1dee5302010-08-22 10:59:02 +00001418 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001419 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001420 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001421 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001422 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001423 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001424
David Chisnallde3a0692009-08-17 23:08:21 +00001425 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001426 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001427 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001428
Denis Zobnin380b2242016-02-11 11:26:03 +00001429 // Ignore empty structs/unions.
1430 if (isEmptyRecord(getContext(), RetTy, true))
1431 return ABIArgInfo::getIgnore();
1432
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001433 // Small structures which are register sized are generally returned
1434 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001435 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001436 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001437
1438 // As a special-case, if the struct is a "single-element" struct, and
1439 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001440 // floating-point register. (MSVC does not apply this special case.)
1441 // We apply a similar transformation for pointer types to improve the
1442 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001443 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001444 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001445 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001446 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1447
1448 // FIXME: We should be able to narrow this integer in cases with dead
1449 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001450 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001451 }
1452
John McCall7f416cc2015-09-08 08:05:57 +00001453 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001454 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001455
Chris Lattner458b2aa2010-07-29 02:16:43 +00001456 // Treat an enum type as its underlying type.
1457 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1458 RetTy = EnumTy->getDecl()->getIntegerType();
1459
Alex Bradburye41a5e22018-01-12 20:08:16 +00001460 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1461 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001462}
1463
Eli Friedman7919bea2012-06-05 19:40:46 +00001464static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1465 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1466}
1467
Daniel Dunbared23de32010-09-16 20:42:00 +00001468static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1469 const RecordType *RT = Ty->getAs<RecordType>();
1470 if (!RT)
1471 return 0;
1472 const RecordDecl *RD = RT->getDecl();
1473
1474 // If this is a C++ record, check the bases first.
1475 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001476 for (const auto &I : CXXRD->bases())
1477 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001478 return false;
1479
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001480 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001481 QualType FT = i->getType();
1482
Eli Friedman7919bea2012-06-05 19:40:46 +00001483 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001484 return true;
1485
1486 if (isRecordWithSSEVectorType(Context, FT))
1487 return true;
1488 }
1489
1490 return false;
1491}
1492
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001493unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1494 unsigned Align) const {
1495 // Otherwise, if the alignment is less than or equal to the minimum ABI
1496 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001497 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001498 return 0; // Use default alignment.
1499
Pengfei Wang48387ec2019-05-31 01:50:07 +00001500 // On non-Darwin, the stack type alignment is always 4.
1501 if (!IsDarwinVectorABI) {
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001502 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001503 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001504 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001505
Daniel Dunbared23de32010-09-16 20:42:00 +00001506 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001507 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1508 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001509 return 16;
1510
1511 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001512}
1513
Rafael Espindola703c47f2012-10-19 05:04:37 +00001514ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001515 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001516 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001517 if (State.FreeRegs) {
1518 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001519 if (!IsMCUABI)
1520 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001521 }
John McCall7f416cc2015-09-08 08:05:57 +00001522 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001523 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001524
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001525 // Compute the byval alignment.
1526 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1527 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1528 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001529 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001530
1531 // If the stack alignment is less than the type alignment, realign the
1532 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001533 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001534 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1535 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001536}
1537
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001538X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1539 const Type *T = isSingleElementStruct(Ty, getContext());
1540 if (!T)
1541 T = Ty.getTypePtr();
1542
1543 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1544 BuiltinType::Kind K = BT->getKind();
1545 if (K == BuiltinType::Float || K == BuiltinType::Double)
1546 return Float;
1547 }
1548 return Integer;
1549}
1550
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001551bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001552 if (!IsSoftFloatABI) {
1553 Class C = classify(Ty);
1554 if (C == Float)
1555 return false;
1556 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001557
Rafael Espindola077dd592012-10-24 01:58:58 +00001558 unsigned Size = getContext().getTypeSize(Ty);
1559 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001560
1561 if (SizeInRegs == 0)
1562 return false;
1563
Michael Kuperstein68901882015-10-25 08:18:20 +00001564 if (!IsMCUABI) {
1565 if (SizeInRegs > State.FreeRegs) {
1566 State.FreeRegs = 0;
1567 return false;
1568 }
1569 } else {
1570 // The MCU psABI allows passing parameters in-reg even if there are
1571 // earlier parameters that are passed on the stack. Also,
1572 // it does not allow passing >8-byte structs in-register,
1573 // even if there are 3 free registers available.
1574 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1575 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001576 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001577
Reid Kleckner661f35b2014-01-18 01:12:41 +00001578 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001579 return true;
1580}
1581
Fangrui Song6907ce22018-07-30 19:24:48 +00001582bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001583 bool &InReg,
1584 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001585 // On Windows, aggregates other than HFAs are never passed in registers, and
1586 // they do not consume register slots. Homogenous floating-point aggregates
1587 // (HFAs) have already been dealt with at this point.
1588 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1589 return false;
1590
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001591 NeedsPadding = false;
1592 InReg = !IsMCUABI;
1593
1594 if (!updateFreeRegs(Ty, State))
1595 return false;
1596
1597 if (IsMCUABI)
1598 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001599
Reid Kleckner80944df2014-10-31 22:00:51 +00001600 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001601 State.CC == llvm::CallingConv::X86_VectorCall ||
1602 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001603 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001604 NeedsPadding = true;
1605
Rafael Espindola077dd592012-10-24 01:58:58 +00001606 return false;
1607 }
1608
Rafael Espindola703c47f2012-10-19 05:04:37 +00001609 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001610}
1611
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001612bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1613 if (!updateFreeRegs(Ty, State))
1614 return false;
1615
1616 if (IsMCUABI)
1617 return false;
1618
1619 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001620 State.CC == llvm::CallingConv::X86_VectorCall ||
1621 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001622 if (getContext().getTypeSize(Ty) > 32)
1623 return false;
1624
Fangrui Song6907ce22018-07-30 19:24:48 +00001625 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001626 Ty->isReferenceType());
1627 }
1628
1629 return true;
1630}
1631
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001632ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1633 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001634 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001635
Reid Klecknerb1be6832014-11-15 01:41:41 +00001636 Ty = useFirstFieldIfTransparentUnion(Ty);
1637
Reid Kleckner80944df2014-10-31 22:00:51 +00001638 // Check with the C++ ABI first.
1639 const RecordType *RT = Ty->getAs<RecordType>();
1640 if (RT) {
1641 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1642 if (RAA == CGCXXABI::RAA_Indirect) {
1643 return getIndirectResult(Ty, false, State);
1644 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1645 // The field index doesn't matter, we'll fix it up later.
1646 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1647 }
1648 }
1649
Erich Keane4bd39302017-06-21 16:37:22 +00001650 // Regcall uses the concept of a homogenous vector aggregate, similar
1651 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001652 const Type *Base = nullptr;
1653 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001654 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001655 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001656
Erich Keane4bd39302017-06-21 16:37:22 +00001657 if (State.FreeSSERegs >= NumElts) {
1658 State.FreeSSERegs -= NumElts;
1659 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001660 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001661 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001662 }
Erich Keane4bd39302017-06-21 16:37:22 +00001663 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001664 }
1665
1666 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001667 // Structures with flexible arrays are always indirect.
1668 // FIXME: This should not be byval!
1669 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1670 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001671
Reid Kleckner04046052016-05-02 17:41:07 +00001672 // Ignore empty structs/unions on non-Windows.
1673 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001674 return ABIArgInfo::getIgnore();
1675
Rafael Espindolafad28de2012-10-24 01:59:00 +00001676 llvm::LLVMContext &LLVMContext = getVMContext();
1677 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001678 bool NeedsPadding = false;
1679 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001680 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001681 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001682 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001683 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001684 if (InReg)
1685 return ABIArgInfo::getDirectInReg(Result);
1686 else
1687 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001688 }
Craig Topper8a13c412014-05-21 05:09:00 +00001689 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001690
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001691 // Expand small (<= 128-bit) record types when we know that the stack layout
1692 // of those arguments will match the struct. This is important because the
1693 // LLVM backend isn't smart enough to remove byval, which inhibits many
1694 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001695 // Don't do this for the MCU if there are still free integer registers
1696 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001697 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1698 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001699 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001700 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001701 State.CC == llvm::CallingConv::X86_VectorCall ||
1702 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001703 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001704
Reid Kleckner661f35b2014-01-18 01:12:41 +00001705 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001706 }
1707
Chris Lattnerd774ae92010-08-26 20:05:13 +00001708 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001709 // On Darwin, some vectors are passed in memory, we handle this by passing
1710 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001711 if (IsDarwinVectorABI) {
Hans Wennborgd874c052019-06-19 11:34:08 +00001712 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001713 if ((Size == 8 || Size == 16 || Size == 32) ||
1714 (Size == 64 && VT->getNumElements() == 1))
1715 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1716 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001717 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001718
Hans Wennborgd874c052019-06-19 11:34:08 +00001719 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1720 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1721
Chris Lattnerd774ae92010-08-26 20:05:13 +00001722 return ABIArgInfo::getDirect();
1723 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001724
Hans Wennborgd874c052019-06-19 11:34:08 +00001725
Chris Lattner458b2aa2010-07-29 02:16:43 +00001726 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1727 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001728
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001729 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001730
1731 if (Ty->isPromotableIntegerType()) {
1732 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001733 return ABIArgInfo::getExtendInReg(Ty);
1734 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001735 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001736
Rafael Espindola703c47f2012-10-19 05:04:37 +00001737 if (InReg)
1738 return ABIArgInfo::getDirectInReg();
1739 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001740}
1741
Erich Keane521ed962017-01-05 00:20:51 +00001742void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1743 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001744 // Vectorcall x86 works subtly different than in x64, so the format is
1745 // a bit different than the x64 version. First, all vector types (not HVAs)
1746 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1747 // This differs from the x64 implementation, where the first 6 by INDEX get
1748 // registers.
1749 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1750 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1751 // first take up the remaining YMM/XMM registers. If insufficient registers
1752 // remain but an integer register (ECX/EDX) is available, it will be passed
1753 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001754 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001755 // First pass do all the vector types.
1756 const Type *Base = nullptr;
1757 uint64_t NumElts = 0;
1758 const QualType& Ty = I.type;
1759 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1760 isHomogeneousAggregate(Ty, Base, NumElts)) {
1761 if (State.FreeSSERegs >= NumElts) {
1762 State.FreeSSERegs -= NumElts;
1763 I.info = ABIArgInfo::getDirect();
1764 } else {
1765 I.info = classifyArgumentType(Ty, State);
1766 }
1767 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1768 }
Erich Keane521ed962017-01-05 00:20:51 +00001769 }
Erich Keane4bd39302017-06-21 16:37:22 +00001770
Erich Keane521ed962017-01-05 00:20:51 +00001771 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001772 // Second pass, do the rest!
1773 const Type *Base = nullptr;
1774 uint64_t NumElts = 0;
1775 const QualType& Ty = I.type;
1776 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1777
1778 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1779 // Assign true HVAs (non vector/native FP types).
1780 if (State.FreeSSERegs >= NumElts) {
1781 State.FreeSSERegs -= NumElts;
1782 I.info = getDirectX86Hva();
1783 } else {
1784 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1785 }
1786 } else if (!IsHva) {
1787 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1788 I.info = classifyArgumentType(Ty, State);
1789 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1790 }
Erich Keane521ed962017-01-05 00:20:51 +00001791 }
1792}
1793
Rafael Espindolaa6472962012-07-24 00:01:07 +00001794void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001795 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001796 if (IsMCUABI)
1797 State.FreeRegs = 3;
1798 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001799 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001800 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1801 State.FreeRegs = 2;
1802 State.FreeSSERegs = 6;
1803 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001804 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001805 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1806 State.FreeRegs = 5;
1807 State.FreeSSERegs = 8;
1808 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001809 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001810
Akira Hatanakad791e922018-03-19 17:38:40 +00001811 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001812 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001813 } else if (FI.getReturnInfo().isIndirect()) {
1814 // The C++ ABI is not aware of register usage, so we have to check if the
1815 // return value was sret and put it in a register ourselves if appropriate.
1816 if (State.FreeRegs) {
1817 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001818 if (!IsMCUABI)
1819 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001820 }
1821 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001822
Peter Collingbournef7706832014-12-12 23:41:25 +00001823 // The chain argument effectively gives us another free register.
1824 if (FI.isChainCall())
1825 ++State.FreeRegs;
1826
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001827 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001828 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1829 computeVectorCallArgs(FI, State, UsedInAlloca);
1830 } else {
1831 // If not vectorcall, revert to normal behavior.
1832 for (auto &I : FI.arguments()) {
1833 I.info = classifyArgumentType(I.type, State);
1834 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1835 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001836 }
1837
1838 // If we needed to use inalloca for any argument, do a second pass and rewrite
1839 // all the memory arguments to use inalloca.
1840 if (UsedInAlloca)
1841 rewriteWithInAlloca(FI);
1842}
1843
1844void
1845X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001846 CharUnits &StackOffset, ABIArgInfo &Info,
1847 QualType Type) const {
1848 // Arguments are always 4-byte-aligned.
1849 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1850
1851 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001852 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1853 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001854 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001855
John McCall7f416cc2015-09-08 08:05:57 +00001856 // Insert padding bytes to respect alignment.
1857 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001858 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001859 if (StackOffset != FieldEnd) {
1860 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001861 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001862 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001863 FrameFields.push_back(Ty);
1864 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001865}
1866
Reid Kleckner852361d2014-07-26 00:12:26 +00001867static bool isArgInAlloca(const ABIArgInfo &Info) {
1868 // Leave ignored and inreg arguments alone.
1869 switch (Info.getKind()) {
1870 case ABIArgInfo::InAlloca:
1871 return true;
1872 case ABIArgInfo::Indirect:
1873 assert(Info.getIndirectByVal());
1874 return true;
1875 case ABIArgInfo::Ignore:
1876 return false;
1877 case ABIArgInfo::Direct:
1878 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001879 if (Info.getInReg())
1880 return false;
1881 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001882 case ABIArgInfo::Expand:
1883 case ABIArgInfo::CoerceAndExpand:
1884 // These are aggregate types which are never passed in registers when
1885 // inalloca is involved.
1886 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001887 }
1888 llvm_unreachable("invalid enum");
1889}
1890
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001891void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1892 assert(IsWin32StructABI && "inalloca only supported on win32");
1893
1894 // Build a packed struct type for all of the arguments in memory.
1895 SmallVector<llvm::Type *, 6> FrameFields;
1896
John McCall7f416cc2015-09-08 08:05:57 +00001897 // The stack alignment is always 4.
1898 CharUnits StackAlign = CharUnits::fromQuantity(4);
1899
1900 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001901 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1902
1903 // Put 'this' into the struct before 'sret', if necessary.
1904 bool IsThisCall =
1905 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1906 ABIArgInfo &Ret = FI.getReturnInfo();
1907 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1908 isArgInAlloca(I->info)) {
1909 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1910 ++I;
1911 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001912
1913 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001914 if (Ret.isIndirect() && !Ret.getInReg()) {
1915 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1916 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001917 // On Windows, the hidden sret parameter is always returned in eax.
1918 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001919 }
1920
1921 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001922 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001923 ++I;
1924
1925 // Put arguments passed in memory into the struct.
1926 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001927 if (isArgInAlloca(I->info))
1928 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001929 }
1930
1931 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001932 /*isPacked=*/true),
1933 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001934}
1935
John McCall7f416cc2015-09-08 08:05:57 +00001936Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1937 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001938
John McCall7f416cc2015-09-08 08:05:57 +00001939 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001940
John McCall7f416cc2015-09-08 08:05:57 +00001941 // x86-32 changes the alignment of certain arguments on the stack.
1942 //
1943 // Just messing with TypeInfo like this works because we never pass
1944 // anything indirectly.
1945 TypeInfo.second = CharUnits::fromQuantity(
1946 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001947
John McCall7f416cc2015-09-08 08:05:57 +00001948 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1949 TypeInfo, CharUnits::fromQuantity(4),
1950 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001951}
1952
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001953bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1954 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1955 assert(Triple.getArch() == llvm::Triple::x86);
1956
1957 switch (Opts.getStructReturnConvention()) {
1958 case CodeGenOptions::SRCK_Default:
1959 break;
1960 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1961 return false;
1962 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1963 return true;
1964 }
1965
Michael Kupersteind749f232015-10-27 07:46:22 +00001966 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001967 return true;
1968
1969 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001970 case llvm::Triple::DragonFly:
1971 case llvm::Triple::FreeBSD:
1972 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001973 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001974 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001975 default:
1976 return false;
1977 }
1978}
1979
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001980void X86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001981 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1982 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001983 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001984 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001985 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001986 llvm::Function *Fn = cast<llvm::Function>(GV);
Erich Keaneb127a3942018-04-19 14:27:05 +00001987 Fn->addFnAttr("stackrealign");
Charles Davis4ea31ab2010-02-13 15:54:06 +00001988 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001989 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1990 llvm::Function *Fn = cast<llvm::Function>(GV);
1991 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1992 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001993 }
1994}
1995
John McCallbeec5a02010-03-06 00:35:14 +00001996bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1997 CodeGen::CodeGenFunction &CGF,
1998 llvm::Value *Address) const {
1999 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00002000
Chris Lattnerece04092012-02-07 00:39:47 +00002001 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002002
John McCallbeec5a02010-03-06 00:35:14 +00002003 // 0-7 are the eight integer registers; the order is different
2004 // on Darwin (for EH), but the range is the same.
2005 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00002006 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00002007
John McCallc8e01702013-04-16 22:48:15 +00002008 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00002009 // 12-16 are st(0..4). Not sure why we stop at 4.
2010 // These have size 16, which is sizeof(long double) on
2011 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002012 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00002013 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002014
John McCallbeec5a02010-03-06 00:35:14 +00002015 } else {
2016 // 9 is %eflags, which doesn't get a size on Darwin for some
2017 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00002018 Builder.CreateAlignedStore(
2019 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2020 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00002021
2022 // 11-16 are st(0..5). Not sure why we stop at 5.
2023 // These have size 12, which is sizeof(long double) on
2024 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002025 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00002026 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2027 }
John McCallbeec5a02010-03-06 00:35:14 +00002028
2029 return false;
2030}
2031
Chris Lattner0cf24192010-06-28 20:05:43 +00002032//===----------------------------------------------------------------------===//
2033// X86-64 ABI Implementation
2034//===----------------------------------------------------------------------===//
2035
2036
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002037namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002038/// The AVX ABI level for X86 targets.
2039enum class X86AVXABILevel {
2040 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002041 AVX,
2042 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002043};
2044
2045/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2046static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2047 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002048 case X86AVXABILevel::AVX512:
2049 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002050 case X86AVXABILevel::AVX:
2051 return 256;
2052 case X86AVXABILevel::None:
2053 return 128;
2054 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002055 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002056}
2057
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002058/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002059class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002060 enum Class {
2061 Integer = 0,
2062 SSE,
2063 SSEUp,
2064 X87,
2065 X87Up,
2066 ComplexX87,
2067 NoClass,
2068 Memory
2069 };
2070
2071 /// merge - Implement the X86_64 ABI merging algorithm.
2072 ///
2073 /// Merge an accumulating classification \arg Accum with a field
2074 /// classification \arg Field.
2075 ///
2076 /// \param Accum - The accumulating classification. This should
2077 /// always be either NoClass or the result of a previous merge
2078 /// call. In addition, this should never be Memory (the caller
2079 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002080 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002081
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002082 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2083 ///
2084 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2085 /// final MEMORY or SSE classes when necessary.
2086 ///
2087 /// \param AggregateSize - The size of the current aggregate in
2088 /// the classification process.
2089 ///
2090 /// \param Lo - The classification for the parts of the type
2091 /// residing in the low word of the containing object.
2092 ///
2093 /// \param Hi - The classification for the parts of the type
2094 /// residing in the higher words of the containing object.
2095 ///
2096 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2097
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002098 /// classify - Determine the x86_64 register classes in which the
2099 /// given type T should be passed.
2100 ///
2101 /// \param Lo - The classification for the parts of the type
2102 /// residing in the low word of the containing object.
2103 ///
2104 /// \param Hi - The classification for the parts of the type
2105 /// residing in the high word of the containing object.
2106 ///
2107 /// \param OffsetBase - The bit offset of this type in the
2108 /// containing object. Some parameters are classified different
2109 /// depending on whether they straddle an eightbyte boundary.
2110 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002111 /// \param isNamedArg - Whether the argument in question is a "named"
2112 /// argument, as used in AMD64-ABI 3.5.7.
2113 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002114 /// If a word is unused its result will be NoClass; if a type should
2115 /// be passed in Memory then at least the classification of \arg Lo
2116 /// will be Memory.
2117 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002118 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002119 ///
2120 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2121 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002122 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2123 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002124
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002125 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002126 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2127 unsigned IROffset, QualType SourceTy,
2128 unsigned SourceOffset) const;
2129 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2130 unsigned IROffset, QualType SourceTy,
2131 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002132
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002133 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002134 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002135 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002136
2137 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002138 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002139 ///
2140 /// \param freeIntRegs - The number of free integer registers remaining
2141 /// available.
2142 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002143
Chris Lattner458b2aa2010-07-29 02:16:43 +00002144 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002145
Erich Keane757d3172016-11-02 18:29:35 +00002146 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2147 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002148 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002149
Erich Keane757d3172016-11-02 18:29:35 +00002150 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2151 unsigned &NeededSSE) const;
2152
2153 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2154 unsigned &NeededSSE) const;
2155
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002156 bool IsIllegalVectorType(QualType Ty) const;
2157
John McCalle0fda732011-04-21 01:20:55 +00002158 /// The 0.98 ABI revision clarified a lot of ambiguities,
2159 /// unfortunately in ways that were not always consistent with
2160 /// certain previous compilers. In particular, platforms which
2161 /// required strict binary compatibility with older versions of GCC
2162 /// may need to exempt themselves.
2163 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002164 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002165 }
2166
Richard Smithf667ad52017-08-26 01:04:35 +00002167 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2168 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002169 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002170 // Clang <= 3.8 did not do this.
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002171 if (getContext().getLangOpts().getClangABICompat() <=
2172 LangOptions::ClangABI::Ver3_8)
Richard Smithf667ad52017-08-26 01:04:35 +00002173 return false;
2174
David Majnemere2ae2282016-03-04 05:26:16 +00002175 const llvm::Triple &Triple = getTarget().getTriple();
2176 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2177 return false;
2178 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2179 return false;
2180 return true;
2181 }
2182
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002183 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002184 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2185 // 64-bit hardware.
2186 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002187
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002188public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002189 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002190 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002191 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002192 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002193
John McCalla729c622012-02-17 03:33:10 +00002194 bool isPassedUsingAVXType(QualType type) const {
2195 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002196 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002197 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2198 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002199 if (info.isDirect()) {
2200 llvm::Type *ty = info.getCoerceToType();
2201 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2202 return (vectorTy->getBitWidth() > 128);
2203 }
2204 return false;
2205 }
2206
Craig Topper4f12f102014-03-12 06:41:41 +00002207 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002208
John McCall7f416cc2015-09-08 08:05:57 +00002209 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2210 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002211 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2212 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002213
2214 bool has64BitPointers() const {
2215 return Has64BitPointers;
2216 }
John McCall12f23522016-04-04 18:33:08 +00002217
John McCall56331e22018-01-07 06:28:49 +00002218 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002219 bool asReturnValue) const override {
2220 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002221 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002222 bool isSwiftErrorInRegister() const override {
2223 return true;
2224 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002225};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002226
Chris Lattner04dc9572010-08-31 16:44:54 +00002227/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002228class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002229public:
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002230 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2231 : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Reid Kleckner11a17192015-10-28 22:29:52 +00002232 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002233
Craig Topper4f12f102014-03-12 06:41:41 +00002234 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002235
John McCall7f416cc2015-09-08 08:05:57 +00002236 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2237 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002238
2239 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2240 // FIXME: Assumes vectorcall is in use.
2241 return isX86VectorTypeForVectorCall(getContext(), Ty);
2242 }
2243
2244 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2245 uint64_t NumMembers) const override {
2246 // FIXME: Assumes vectorcall is in use.
2247 return isX86VectorCallAggregateSmallEnough(NumMembers);
2248 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002249
John McCall56331e22018-01-07 06:28:49 +00002250 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002251 bool asReturnValue) const override {
2252 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2253 }
2254
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002255 bool isSwiftErrorInRegister() const override {
2256 return true;
2257 }
2258
Reid Kleckner11a17192015-10-28 22:29:52 +00002259private:
Erich Keane521ed962017-01-05 00:20:51 +00002260 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2261 bool IsVectorCall, bool IsRegCall) const;
2262 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2263 const ABIArgInfo &current) const;
2264 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2265 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002266
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002267 X86AVXABILevel AVXLevel;
2268
2269 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002270};
2271
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002272class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2273public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002274 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002275 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002276
John McCalla729c622012-02-17 03:33:10 +00002277 const X86_64ABIInfo &getABIInfo() const {
2278 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2279 }
2280
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002281 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2282 /// the autoreleaseRV/retainRV optimization.
2283 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2284 return true;
2285 }
2286
Craig Topper4f12f102014-03-12 06:41:41 +00002287 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002288 return 7;
2289 }
2290
2291 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002292 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002293 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002294
John McCall943fae92010-05-27 06:19:26 +00002295 // 0-15 are the 16 integer registers.
2296 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002297 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002298 return false;
2299 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002300
Jay Foad7c57be32011-07-11 09:56:20 +00002301 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002302 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002303 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002304 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2305 }
2306
John McCalla729c622012-02-17 03:33:10 +00002307 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002308 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002309 // The default CC on x86-64 sets %al to the number of SSA
2310 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002311 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002312 // that when AVX types are involved: the ABI explicitly states it is
2313 // undefined, and it doesn't work in practice because of how the ABI
2314 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002315 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002316 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002317 for (CallArgList::const_iterator
2318 it = args.begin(), ie = args.end(); it != ie; ++it) {
2319 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2320 HasAVXType = true;
2321 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002322 }
2323 }
John McCalla729c622012-02-17 03:33:10 +00002324
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002325 if (!HasAVXType)
2326 return true;
2327 }
John McCallcbc038a2011-09-21 08:08:30 +00002328
John McCalla729c622012-02-17 03:33:10 +00002329 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002330 }
2331
Craig Topper4f12f102014-03-12 06:41:41 +00002332 llvm::Constant *
2333 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002334 unsigned Sig = (0xeb << 0) | // jmp rel8
2335 (0x06 << 8) | // .+0x08
2336 ('v' << 16) |
2337 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002338 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2339 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002340
2341 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002342 CodeGen::CodeGenModule &CGM) const override {
2343 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002344 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002345 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002346 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002347 llvm::Function *Fn = cast<llvm::Function>(GV);
2348 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002349 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002350 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2351 llvm::Function *Fn = cast<llvm::Function>(GV);
2352 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2353 }
2354 }
2355 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002356};
2357
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002358static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002359 // If the argument does not end in .lib, automatically add the suffix.
2360 // If the argument contains a space, enclose it in quotes.
2361 // This matches the behavior of MSVC.
2362 bool Quote = (Lib.find(" ") != StringRef::npos);
2363 std::string ArgStr = Quote ? "\"" : "";
2364 ArgStr += Lib;
Martin Storsjo3cd67c92018-10-10 09:01:00 +00002365 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002366 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002367 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002368 return ArgStr;
2369}
2370
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002371class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2372public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002373 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002374 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2375 unsigned NumRegisterParameters)
2376 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002377 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002378
Eric Christopher162c91c2015-06-05 22:03:00 +00002379 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002380 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002381
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002382 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002383 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002384 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002385 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002386 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002387
2388 void getDetectMismatchOption(llvm::StringRef Name,
2389 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002390 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002391 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002392 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002393};
2394
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002395static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2396 CodeGen::CodeGenModule &CGM) {
2397 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002398
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002399 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Eric Christopher7565e0d2015-05-29 23:09:49 +00002400 Fn->addFnAttr("stack-probe-size",
2401 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002402 if (CGM.getCodeGenOpts().NoStackArgProbe)
2403 Fn->addFnAttr("no-stack-arg-probe");
Hans Wennborg77dc2362015-01-20 19:45:50 +00002404 }
2405}
2406
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002407void WinX86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002408 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2409 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2410 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002411 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002412 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002413}
2414
Chris Lattner04dc9572010-08-31 16:44:54 +00002415class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2416public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002417 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2418 X86AVXABILevel AVXLevel)
Reid Kleckner3fd3de12019-06-20 20:07:20 +00002419 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002420
Eric Christopher162c91c2015-06-05 22:03:00 +00002421 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002422 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002423
Craig Topper4f12f102014-03-12 06:41:41 +00002424 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002425 return 7;
2426 }
2427
2428 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002429 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002430 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002431
Chris Lattner04dc9572010-08-31 16:44:54 +00002432 // 0-15 are the 16 integer registers.
2433 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002434 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002435 return false;
2436 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002437
2438 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002439 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002440 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002441 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002442 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002443
2444 void getDetectMismatchOption(llvm::StringRef Name,
2445 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002446 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002447 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002448 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002449};
2450
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002451void WinX86_64TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002452 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2453 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2454 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002455 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002456 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002457 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002458 llvm::Function *Fn = cast<llvm::Function>(GV);
2459 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002460 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002461 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2462 llvm::Function *Fn = cast<llvm::Function>(GV);
2463 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2464 }
2465 }
2466
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002467 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002468}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002469}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002470
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002471void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2472 Class &Hi) const {
2473 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2474 //
2475 // (a) If one of the classes is Memory, the whole argument is passed in
2476 // memory.
2477 //
2478 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2479 // memory.
2480 //
2481 // (c) If the size of the aggregate exceeds two eightbytes and the first
2482 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2483 // argument is passed in memory. NOTE: This is necessary to keep the
2484 // ABI working for processors that don't support the __m256 type.
2485 //
2486 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2487 //
2488 // Some of these are enforced by the merging logic. Others can arise
2489 // only with unions; for example:
2490 // union { _Complex double; unsigned; }
2491 //
2492 // Note that clauses (b) and (c) were added in 0.98.
2493 //
2494 if (Hi == Memory)
2495 Lo = Memory;
2496 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2497 Lo = Memory;
2498 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2499 Lo = Memory;
2500 if (Hi == SSEUp && Lo != SSE)
2501 Hi = SSE;
2502}
2503
Chris Lattnerd776fb12010-06-28 21:43:59 +00002504X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002505 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2506 // classified recursively so that always two fields are
2507 // considered. The resulting class is calculated according to
2508 // the classes of the fields in the eightbyte:
2509 //
2510 // (a) If both classes are equal, this is the resulting class.
2511 //
2512 // (b) If one of the classes is NO_CLASS, the resulting class is
2513 // the other class.
2514 //
2515 // (c) If one of the classes is MEMORY, the result is the MEMORY
2516 // class.
2517 //
2518 // (d) If one of the classes is INTEGER, the result is the
2519 // INTEGER.
2520 //
2521 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2522 // MEMORY is used as class.
2523 //
2524 // (f) Otherwise class SSE is used.
2525
2526 // Accum should never be memory (we should have returned) or
2527 // ComplexX87 (because this cannot be passed in a structure).
2528 assert((Accum != Memory && Accum != ComplexX87) &&
2529 "Invalid accumulated classification during merge.");
2530 if (Accum == Field || Field == NoClass)
2531 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002532 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002533 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002534 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002535 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002536 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002538 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2539 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002540 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002541 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002542}
2543
Chris Lattner5c740f12010-06-30 19:14:05 +00002544void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002545 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002546 // FIXME: This code can be simplified by introducing a simple value class for
2547 // Class pairs with appropriate constructor methods for the various
2548 // situations.
2549
2550 // FIXME: Some of the split computations are wrong; unaligned vectors
2551 // shouldn't be passed in registers for example, so there is no chance they
2552 // can straddle an eightbyte. Verify & simplify.
2553
2554 Lo = Hi = NoClass;
2555
2556 Class &Current = OffsetBase < 64 ? Lo : Hi;
2557 Current = Memory;
2558
John McCall9dd450b2009-09-21 23:43:11 +00002559 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002560 BuiltinType::Kind k = BT->getKind();
2561
2562 if (k == BuiltinType::Void) {
2563 Current = NoClass;
2564 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2565 Lo = Integer;
2566 Hi = Integer;
2567 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2568 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002569 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002570 Current = SSE;
2571 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002572 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002573 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002574 Lo = SSE;
2575 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002576 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002577 Lo = X87;
2578 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002579 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002580 Current = SSE;
2581 } else
2582 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002583 }
2584 // FIXME: _Decimal32 and _Decimal64 are SSE.
2585 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002586 return;
2587 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002588
Chris Lattnerd776fb12010-06-28 21:43:59 +00002589 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002590 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002591 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002592 return;
2593 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002594
Chris Lattnerd776fb12010-06-28 21:43:59 +00002595 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002596 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002597 return;
2598 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002599
Chris Lattnerd776fb12010-06-28 21:43:59 +00002600 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002601 if (Ty->isMemberFunctionPointerType()) {
2602 if (Has64BitPointers) {
2603 // If Has64BitPointers, this is an {i64, i64}, so classify both
2604 // Lo and Hi now.
2605 Lo = Hi = Integer;
2606 } else {
2607 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2608 // straddles an eightbyte boundary, Hi should be classified as well.
2609 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2610 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2611 if (EB_FuncPtr != EB_ThisAdj) {
2612 Lo = Hi = Integer;
2613 } else {
2614 Current = Integer;
2615 }
2616 }
2617 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002618 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002619 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002620 return;
2621 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002622
Chris Lattnerd776fb12010-06-28 21:43:59 +00002623 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002624 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002625 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2626 // gcc passes the following as integer:
2627 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2628 // 2 bytes - <2 x char>, <1 x short>
2629 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002630 Current = Integer;
2631
2632 // If this type crosses an eightbyte boundary, it should be
2633 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002634 uint64_t EB_Lo = (OffsetBase) / 64;
2635 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2636 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002637 Hi = Lo;
2638 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002639 QualType ElementType = VT->getElementType();
2640
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002641 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002642 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002643 return;
2644
David Majnemere2ae2282016-03-04 05:26:16 +00002645 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2646 // pass them as integer. For platforms where clang is the de facto
2647 // platform compiler, we must continue to use integer.
2648 if (!classifyIntegerMMXAsSSE() &&
2649 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2650 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2651 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2652 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 Current = Integer;
2654 else
2655 Current = SSE;
2656
2657 // If this type crosses an eightbyte boundary, it should be
2658 // split.
2659 if (OffsetBase && OffsetBase != 64)
2660 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002661 } else if (Size == 128 ||
2662 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002663 // Arguments of 256-bits are split into four eightbyte chunks. The
2664 // least significant one belongs to class SSE and all the others to class
2665 // SSEUP. The original Lo and Hi design considers that types can't be
2666 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2667 // This design isn't correct for 256-bits, but since there're no cases
2668 // where the upper parts would need to be inspected, avoid adding
2669 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002670 //
2671 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2672 // registers if they are "named", i.e. not part of the "..." of a
2673 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002674 //
2675 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2676 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002677 Lo = SSE;
2678 Hi = SSEUp;
2679 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002680 return;
2681 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002682
Chris Lattnerd776fb12010-06-28 21:43:59 +00002683 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002684 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002685
Chris Lattner2b037972010-07-29 02:01:43 +00002686 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002687 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688 if (Size <= 64)
2689 Current = Integer;
2690 else if (Size <= 128)
2691 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002692 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002694 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002695 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002696 } else if (ET == getContext().LongDoubleTy) {
2697 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002698 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002699 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002700 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002701 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002702 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002703 Lo = Hi = SSE;
2704 else
2705 llvm_unreachable("unexpected long double representation!");
2706 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707
2708 // If this complex type crosses an eightbyte boundary then it
2709 // should be split.
2710 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002711 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002712 if (Hi == NoClass && EB_Real != EB_Imag)
2713 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002714
Chris Lattnerd776fb12010-06-28 21:43:59 +00002715 return;
2716 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002717
Chris Lattner2b037972010-07-29 02:01:43 +00002718 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719 // Arrays are treated like structures.
2720
Chris Lattner2b037972010-07-29 02:01:43 +00002721 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002722
2723 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002724 // than eight eightbytes, ..., it has class MEMORY.
2725 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002726 return;
2727
2728 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2729 // fields, it has class MEMORY.
2730 //
2731 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002732 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002733 return;
2734
2735 // Otherwise implement simplified merge. We could be smarter about
2736 // this, but it isn't worth it and would be harder to verify.
2737 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002738 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002739 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002740
2741 // The only case a 256-bit wide vector could be used is when the array
2742 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2743 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002744 //
2745 if (Size > 128 &&
2746 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002747 return;
2748
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002749 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2750 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002751 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002752 Lo = merge(Lo, FieldLo);
2753 Hi = merge(Hi, FieldHi);
2754 if (Lo == Memory || Hi == Memory)
2755 break;
2756 }
2757
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002758 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002759 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002760 return;
2761 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002762
Chris Lattnerd776fb12010-06-28 21:43:59 +00002763 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002764 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002765
2766 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002767 // than eight eightbytes, ..., it has class MEMORY.
2768 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002769 return;
2770
Anders Carlsson20759ad2009-09-16 15:53:40 +00002771 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2772 // copy constructor or a non-trivial destructor, it is passed by invisible
2773 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002774 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002775 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002776
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002777 const RecordDecl *RD = RT->getDecl();
2778
2779 // Assume variable sized types are passed in memory.
2780 if (RD->hasFlexibleArrayMember())
2781 return;
2782
Chris Lattner2b037972010-07-29 02:01:43 +00002783 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002784
2785 // Reset Lo class, this will be recomputed.
2786 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002787
2788 // If this is a C++ record, classify the bases first.
2789 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002790 for (const auto &I : CXXRD->bases()) {
2791 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002792 "Unexpected base class!");
2793 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002794 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002795
2796 // Classify this field.
2797 //
2798 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2799 // single eightbyte, each is classified separately. Each eightbyte gets
2800 // initialized to class NO_CLASS.
2801 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002802 uint64_t Offset =
2803 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002804 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002805 Lo = merge(Lo, FieldLo);
2806 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002807 if (Lo == Memory || Hi == Memory) {
2808 postMerge(Size, Lo, Hi);
2809 return;
2810 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002811 }
2812 }
2813
2814 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002815 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002816 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002817 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002818 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2819 bool BitField = i->isBitField();
2820
David Majnemerb439dfe2016-08-15 07:20:40 +00002821 // Ignore padding bit-fields.
2822 if (BitField && i->isUnnamedBitfield())
2823 continue;
2824
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002825 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2826 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002827 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002828 // The only case a 256-bit wide vector could be used is when the struct
2829 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2830 // to work for sizes wider than 128, early check and fallback to memory.
2831 //
David Majnemerb229cb02016-08-15 06:39:18 +00002832 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2833 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002834 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002835 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002836 return;
2837 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002838 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002839 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002840 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002841 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002842 return;
2843 }
2844
2845 // Classify this field.
2846 //
2847 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2848 // exceeds a single eightbyte, each is classified
2849 // separately. Each eightbyte gets initialized to class
2850 // NO_CLASS.
2851 Class FieldLo, FieldHi;
2852
2853 // Bit-fields require special handling, they do not force the
2854 // structure to be passed in memory even if unaligned, and
2855 // therefore they can straddle an eightbyte.
2856 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002857 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002858 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002859 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002860
2861 uint64_t EB_Lo = Offset / 64;
2862 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002863
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002864 if (EB_Lo) {
2865 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2866 FieldLo = NoClass;
2867 FieldHi = Integer;
2868 } else {
2869 FieldLo = Integer;
2870 FieldHi = EB_Hi ? Integer : NoClass;
2871 }
2872 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002873 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002874 Lo = merge(Lo, FieldLo);
2875 Hi = merge(Hi, FieldHi);
2876 if (Lo == Memory || Hi == Memory)
2877 break;
2878 }
2879
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002880 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002881 }
2882}
2883
Chris Lattner22a931e2010-06-29 06:01:59 +00002884ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002885 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2886 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002887 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002888 // Treat an enum type as its underlying type.
2889 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2890 Ty = EnumTy->getDecl()->getIntegerType();
2891
Alex Bradburye41a5e22018-01-12 20:08:16 +00002892 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2893 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002894 }
2895
John McCall7f416cc2015-09-08 08:05:57 +00002896 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002897}
2898
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002899bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2900 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2901 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002902 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002903 if (Size <= 64 || Size > LargestVector)
2904 return true;
2905 }
2906
2907 return false;
2908}
2909
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002910ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2911 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002912 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2913 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002914 //
2915 // This assumption is optimistic, as there could be free registers available
2916 // when we need to pass this argument in memory, and LLVM could try to pass
2917 // the argument in the free register. This does not seem to happen currently,
2918 // but this code would be much safer if we could mark the argument with
2919 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002920 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002921 // Treat an enum type as its underlying type.
2922 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2923 Ty = EnumTy->getDecl()->getIntegerType();
2924
Alex Bradburye41a5e22018-01-12 20:08:16 +00002925 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2926 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002927 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002928
Mark Lacey3825e832013-10-06 01:33:34 +00002929 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002930 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002931
Chris Lattner44c2b902011-05-22 23:21:23 +00002932 // Compute the byval alignment. We specify the alignment of the byval in all
2933 // cases so that the mid-level optimizer knows the alignment of the byval.
2934 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002935
2936 // Attempt to avoid passing indirect results using byval when possible. This
2937 // is important for good codegen.
2938 //
2939 // We do this by coercing the value into a scalar type which the backend can
2940 // handle naturally (i.e., without using byval).
2941 //
2942 // For simplicity, we currently only do this when we have exhausted all of the
2943 // free integer registers. Doing this when there are free integer registers
2944 // would require more care, as we would have to ensure that the coerced value
2945 // did not claim the unused register. That would require either reording the
2946 // arguments to the function (so that any subsequent inreg values came first),
2947 // or only doing this optimization when there were no following arguments that
2948 // might be inreg.
2949 //
2950 // We currently expect it to be rare (particularly in well written code) for
2951 // arguments to be passed on the stack when there are still free integer
2952 // registers available (this would typically imply large structs being passed
2953 // by value), so this seems like a fair tradeoff for now.
2954 //
2955 // We can revisit this if the backend grows support for 'onstack' parameter
2956 // attributes. See PR12193.
2957 if (freeIntRegs == 0) {
2958 uint64_t Size = getContext().getTypeSize(Ty);
2959
2960 // If this type fits in an eightbyte, coerce it into the matching integral
2961 // type, which will end up on the stack (with alignment 8).
2962 if (Align == 8 && Size <= 64)
2963 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2964 Size));
2965 }
2966
John McCall7f416cc2015-09-08 08:05:57 +00002967 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002968}
2969
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002970/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2971/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002972llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002973 // Wrapper structs/arrays that only contain vectors are passed just like
2974 // vectors; strip them off if present.
2975 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2976 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002977
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002978 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002979 if (isa<llvm::VectorType>(IRType) ||
2980 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002981 return IRType;
2982
2983 // We couldn't find the preferred IR vector type for 'Ty'.
2984 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002985 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002986
2987 // Return a LLVM IR vector type based on the size of 'Ty'.
2988 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2989 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002990}
2991
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002992/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2993/// is known to either be off the end of the specified type or being in
2994/// alignment padding. The user type specified is known to be at most 128 bits
2995/// in size, and have passed through X86_64ABIInfo::classify with a successful
2996/// classification that put one of the two halves in the INTEGER class.
2997///
2998/// It is conservatively correct to return false.
2999static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3000 unsigned EndBit, ASTContext &Context) {
3001 // If the bytes being queried are off the end of the type, there is no user
3002 // data hiding here. This handles analysis of builtins, vectors and other
3003 // types that don't contain interesting padding.
3004 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3005 if (TySize <= StartBit)
3006 return true;
3007
Chris Lattner98076a22010-07-29 07:43:55 +00003008 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3009 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3010 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3011
3012 // Check each element to see if the element overlaps with the queried range.
3013 for (unsigned i = 0; i != NumElts; ++i) {
3014 // If the element is after the span we care about, then we're done..
3015 unsigned EltOffset = i*EltSize;
3016 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003017
Chris Lattner98076a22010-07-29 07:43:55 +00003018 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3019 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3020 EndBit-EltOffset, Context))
3021 return false;
3022 }
3023 // If it overlaps no elements, then it is safe to process as padding.
3024 return true;
3025 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003026
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003027 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3028 const RecordDecl *RD = RT->getDecl();
3029 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003030
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003031 // If this is a C++ record, check the bases first.
3032 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003033 for (const auto &I : CXXRD->bases()) {
3034 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003035 "Unexpected base class!");
3036 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003037 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003038
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003039 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003040 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003041 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003042
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003043 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003044 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003045 EndBit-BaseOffset, Context))
3046 return false;
3047 }
3048 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003049
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003050 // Verify that no field has data that overlaps the region of interest. Yes
3051 // this could be sped up a lot by being smarter about queried fields,
3052 // however we're only looking at structs up to 16 bytes, so we don't care
3053 // much.
3054 unsigned idx = 0;
3055 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3056 i != e; ++i, ++idx) {
3057 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003058
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003059 // If we found a field after the region we care about, then we're done.
3060 if (FieldOffset >= EndBit) break;
3061
3062 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3063 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3064 Context))
3065 return false;
3066 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003067
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003068 // If nothing in this record overlapped the area of interest, then we're
3069 // clean.
3070 return true;
3071 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003072
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003073 return false;
3074}
3075
Chris Lattnere556a712010-07-29 18:39:32 +00003076/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3077/// float member at the specified offset. For example, {int,{float}} has a
3078/// float at offset 4. It is conservatively correct for this routine to return
3079/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003080static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003081 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003082 // Base case if we find a float.
3083 if (IROffset == 0 && IRType->isFloatTy())
3084 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003085
Chris Lattnere556a712010-07-29 18:39:32 +00003086 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003087 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003088 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3089 unsigned Elt = SL->getElementContainingOffset(IROffset);
3090 IROffset -= SL->getElementOffset(Elt);
3091 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3092 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003093
Chris Lattnere556a712010-07-29 18:39:32 +00003094 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003095 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3096 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003097 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3098 IROffset -= IROffset/EltSize*EltSize;
3099 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3100 }
3101
3102 return false;
3103}
3104
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003105
3106/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3107/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003108llvm::Type *X86_64ABIInfo::
3109GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003110 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003111 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003112 // pass as float if the last 4 bytes is just padding. This happens for
3113 // structs that contain 3 floats.
3114 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3115 SourceOffset*8+64, getContext()))
3116 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003117
Chris Lattnere556a712010-07-29 18:39:32 +00003118 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3119 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3120 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003121 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3122 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003123 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003124
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003125 return llvm::Type::getDoubleTy(getVMContext());
3126}
3127
3128
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003129/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3130/// an 8-byte GPR. This means that we either have a scalar or we are talking
3131/// about the high or low part of an up-to-16-byte struct. This routine picks
3132/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003133/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3134/// etc).
3135///
3136/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3137/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3138/// the 8-byte value references. PrefType may be null.
3139///
Alp Toker9907f082014-07-09 14:06:35 +00003140/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003141/// an offset into this that we're processing (which is always either 0 or 8).
3142///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003143llvm::Type *X86_64ABIInfo::
3144GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003145 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003146 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3147 // returning an 8-byte unit starting with it. See if we can safely use it.
3148 if (IROffset == 0) {
3149 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003150 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3151 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003152 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003153
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003154 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3155 // goodness in the source type is just tail padding. This is allowed to
3156 // kick in for struct {double,int} on the int, but not on
3157 // struct{double,int,int} because we wouldn't return the second int. We
3158 // have to do this analysis on the source type because we can't depend on
3159 // unions being lowered a specific way etc.
3160 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003161 IRType->isIntegerTy(32) ||
3162 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3163 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3164 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003165
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003166 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3167 SourceOffset*8+64, getContext()))
3168 return IRType;
3169 }
3170 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003171
Chris Lattner2192fe52011-07-18 04:24:23 +00003172 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003173 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003174 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003175 if (IROffset < SL->getSizeInBytes()) {
3176 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3177 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003178
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003179 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3180 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003181 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003182 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003183
Chris Lattner2192fe52011-07-18 04:24:23 +00003184 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003185 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003186 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003187 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003188 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3189 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003190 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003191
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003192 // Okay, we don't have any better idea of what to pass, so we pass this in an
3193 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003194 unsigned TySizeInBytes =
3195 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003196
Chris Lattner3f763422010-07-29 17:34:39 +00003197 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003198
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003199 // It is always safe to classify this as an integer type up to i64 that
3200 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003201 return llvm::IntegerType::get(getVMContext(),
3202 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003203}
3204
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003205
3206/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3207/// be used as elements of a two register pair to pass or return, return a
3208/// first class aggregate to represent them. For example, if the low part of
3209/// a by-value argument should be passed as i32* and the high part as float,
3210/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003211static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003212GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003213 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003214 // In order to correctly satisfy the ABI, we need to the high part to start
3215 // at offset 8. If the high and low parts we inferred are both 4-byte types
3216 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3217 // the second element at offset 8. Check for this:
3218 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3219 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003220 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003221 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003222
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003223 // To handle this, we have to increase the size of the low part so that the
3224 // second element will start at an 8 byte offset. We can't increase the size
3225 // of the second element because it might make us access off the end of the
3226 // struct.
3227 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003228 // There are usually two sorts of types the ABI generation code can produce
3229 // for the low part of a pair that aren't 8 bytes in size: float or
3230 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3231 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003232 // Promote these to a larger type.
3233 if (Lo->isFloatTy())
3234 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3235 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003236 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3237 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003238 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3239 }
3240 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003241
Serge Guelton1d993272017-05-09 19:31:30 +00003242 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003243
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003244 // Verify that the second element is at an 8-byte offset.
3245 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3246 "Invalid x86-64 argument pair!");
3247 return Result;
3248}
3249
Chris Lattner31faff52010-07-28 23:06:14 +00003250ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003251classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003252 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3253 // classification algorithm.
3254 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003255 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003256
3257 // Check some invariants.
3258 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003259 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3260
Craig Topper8a13c412014-05-21 05:09:00 +00003261 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003262 switch (Lo) {
3263 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003264 if (Hi == NoClass)
3265 return ABIArgInfo::getIgnore();
3266 // If the low part is just padding, it takes no register, leave ResType
3267 // null.
3268 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3269 "Unknown missing lo part");
3270 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003271
3272 case SSEUp:
3273 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003274 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003275
3276 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3277 // hidden argument.
3278 case Memory:
3279 return getIndirectReturnResult(RetTy);
3280
3281 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3282 // available register of the sequence %rax, %rdx is used.
3283 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003284 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003285
Chris Lattner1f3a0632010-07-29 21:42:50 +00003286 // If we have a sign or zero extended integer, make sure to return Extend
3287 // so that the parameter gets the right LLVM IR attributes.
3288 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3289 // Treat an enum type as its underlying type.
3290 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3291 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003292
Chris Lattner1f3a0632010-07-29 21:42:50 +00003293 if (RetTy->isIntegralOrEnumerationType() &&
3294 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003295 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003296 }
Chris Lattner31faff52010-07-28 23:06:14 +00003297 break;
3298
3299 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3300 // available SSE register of the sequence %xmm0, %xmm1 is used.
3301 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003302 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003303 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003304
3305 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3306 // returned on the X87 stack in %st0 as 80-bit x87 number.
3307 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003308 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003309 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003310
3311 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3312 // part of the value is returned in %st0 and the imaginary part in
3313 // %st1.
3314 case ComplexX87:
3315 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003316 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003317 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003318 break;
3319 }
3320
Craig Topper8a13c412014-05-21 05:09:00 +00003321 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003322 switch (Hi) {
3323 // Memory was handled previously and X87 should
3324 // never occur as a hi class.
3325 case Memory:
3326 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003327 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003328
3329 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003330 case NoClass:
3331 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003332
Chris Lattner52b3c132010-09-01 00:20:33 +00003333 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003334 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003335 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3336 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003337 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003338 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003339 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003340 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3341 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003342 break;
3343
3344 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003345 // is passed in the next available eightbyte chunk if the last used
3346 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003347 //
Chris Lattner57540c52011-04-15 05:22:18 +00003348 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003349 case SSEUp:
3350 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003351 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003352 break;
3353
3354 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3355 // returned together with the previous X87 value in %st0.
3356 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003357 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003358 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003359 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003360 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003361 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003362 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003363 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3364 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003365 }
Chris Lattner31faff52010-07-28 23:06:14 +00003366 break;
3367 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003368
Chris Lattner52b3c132010-09-01 00:20:33 +00003369 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003370 // known to pass in the high eightbyte of the result. We do this by forming a
3371 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003372 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003373 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003374
Chris Lattner1f3a0632010-07-29 21:42:50 +00003375 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003376}
3377
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003378ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003379 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3380 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003381 const
3382{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003383 Ty = useFirstFieldIfTransparentUnion(Ty);
3384
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003385 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003386 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003387
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003388 // Check some invariants.
3389 // FIXME: Enforce these by construction.
3390 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003391 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3392
3393 neededInt = 0;
3394 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003395 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003396 switch (Lo) {
3397 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003398 if (Hi == NoClass)
3399 return ABIArgInfo::getIgnore();
3400 // If the low part is just padding, it takes no register, leave ResType
3401 // null.
3402 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3403 "Unknown missing lo part");
3404 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003405
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003406 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3407 // on the stack.
3408 case Memory:
3409
3410 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3411 // COMPLEX_X87, it is passed in memory.
3412 case X87:
3413 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003414 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003415 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003416 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003417
3418 case SSEUp:
3419 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003420 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003421
3422 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3423 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3424 // and %r9 is used.
3425 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003426 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003427
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003428 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003429 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003430
3431 // If we have a sign or zero extended integer, make sure to return Extend
3432 // so that the parameter gets the right LLVM IR attributes.
3433 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3434 // Treat an enum type as its underlying type.
3435 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3436 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003437
Chris Lattner1f3a0632010-07-29 21:42:50 +00003438 if (Ty->isIntegralOrEnumerationType() &&
3439 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003440 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003441 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003442
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003443 break;
3444
3445 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3446 // available SSE register is used, the registers are taken in the
3447 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003448 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003449 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003450 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003451 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003452 break;
3453 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003454 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003455
Craig Topper8a13c412014-05-21 05:09:00 +00003456 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003457 switch (Hi) {
3458 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003459 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003460 // which is passed in memory.
3461 case Memory:
3462 case X87:
3463 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003464 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003465
3466 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003467
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003468 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003469 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003470 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003471 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003472
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003473 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3474 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003475 break;
3476
3477 // X87Up generally doesn't occur here (long double is passed in
3478 // memory), except in situations involving unions.
3479 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003480 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003481 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003482
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003483 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3484 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003485
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003486 ++neededSSE;
3487 break;
3488
3489 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3490 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003491 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003492 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003493 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003494 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003495 break;
3496 }
3497
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003498 // If a high part was specified, merge it together with the low part. It is
3499 // known to pass in the high eightbyte of the result. We do this by forming a
3500 // first class struct aggregate with the high and low part: {low, high}
3501 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003502 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003503
Chris Lattner1f3a0632010-07-29 21:42:50 +00003504 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003505}
3506
Erich Keane757d3172016-11-02 18:29:35 +00003507ABIArgInfo
3508X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3509 unsigned &NeededSSE) const {
3510 auto RT = Ty->getAs<RecordType>();
3511 assert(RT && "classifyRegCallStructType only valid with struct types");
3512
3513 if (RT->getDecl()->hasFlexibleArrayMember())
3514 return getIndirectReturnResult(Ty);
3515
3516 // Sum up bases
3517 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3518 if (CXXRD->isDynamicClass()) {
3519 NeededInt = NeededSSE = 0;
3520 return getIndirectReturnResult(Ty);
3521 }
3522
3523 for (const auto &I : CXXRD->bases())
3524 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3525 .isIndirect()) {
3526 NeededInt = NeededSSE = 0;
3527 return getIndirectReturnResult(Ty);
3528 }
3529 }
3530
3531 // Sum up members
3532 for (const auto *FD : RT->getDecl()->fields()) {
3533 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3534 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3535 .isIndirect()) {
3536 NeededInt = NeededSSE = 0;
3537 return getIndirectReturnResult(Ty);
3538 }
3539 } else {
3540 unsigned LocalNeededInt, LocalNeededSSE;
3541 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3542 LocalNeededSSE, true)
3543 .isIndirect()) {
3544 NeededInt = NeededSSE = 0;
3545 return getIndirectReturnResult(Ty);
3546 }
3547 NeededInt += LocalNeededInt;
3548 NeededSSE += LocalNeededSSE;
3549 }
3550 }
3551
3552 return ABIArgInfo::getDirect();
3553}
3554
3555ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3556 unsigned &NeededInt,
3557 unsigned &NeededSSE) const {
3558
3559 NeededInt = 0;
3560 NeededSSE = 0;
3561
3562 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3563}
3564
Chris Lattner22326a12010-07-29 02:31:05 +00003565void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003566
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003567 const unsigned CallingConv = FI.getCallingConvention();
3568 // It is possible to force Win64 calling convention on any x86_64 target by
3569 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3570 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3571 if (CallingConv == llvm::CallingConv::Win64) {
Reid Kleckner3fd3de12019-06-20 20:07:20 +00003572 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003573 Win64ABIInfo.computeInfo(FI);
3574 return;
3575 }
3576
3577 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003578
3579 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003580 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3581 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3582 unsigned NeededInt, NeededSSE;
3583
Akira Hatanakad791e922018-03-19 17:38:40 +00003584 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Erich Keanede1b2a92017-07-21 18:50:36 +00003585 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3586 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3587 FI.getReturnInfo() =
3588 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3589 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3590 FreeIntRegs -= NeededInt;
3591 FreeSSERegs -= NeededSSE;
3592 } else {
3593 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3594 }
3595 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3596 // Complex Long Double Type is passed in Memory when Regcall
3597 // calling convention is used.
3598 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3599 if (getContext().getCanonicalType(CT->getElementType()) ==
3600 getContext().LongDoubleTy)
3601 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3602 } else
3603 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3604 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003605
3606 // If the return value is indirect, then the hidden argument is consuming one
3607 // integer register.
3608 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003609 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003610
Peter Collingbournef7706832014-12-12 23:41:25 +00003611 // The chain argument effectively gives us another free register.
3612 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003613 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003614
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003615 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003616 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3617 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003618 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003619 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003620 it != ie; ++it, ++ArgNo) {
3621 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003622
Erich Keane757d3172016-11-02 18:29:35 +00003623 if (IsRegCall && it->type->isStructureOrClassType())
3624 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3625 else
3626 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3627 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003628
3629 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3630 // eightbyte of an argument, the whole argument is passed on the
3631 // stack. If registers have already been assigned for some
3632 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003633 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3634 FreeIntRegs -= NeededInt;
3635 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003636 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003637 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003638 }
3639 }
3640}
3641
John McCall7f416cc2015-09-08 08:05:57 +00003642static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3643 Address VAListAddr, QualType Ty) {
James Y Knight751fe282019-02-09 22:22:28 +00003644 Address overflow_arg_area_p =
3645 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003646 llvm::Value *overflow_arg_area =
3647 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3648
3649 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3650 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003651 // It isn't stated explicitly in the standard, but in practice we use
3652 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003653 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3654 if (Align > CharUnits::fromQuantity(8)) {
3655 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3656 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003657 }
3658
3659 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003660 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003661 llvm::Value *Res =
3662 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003663 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003664
3665 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3666 // l->overflow_arg_area + sizeof(type).
3667 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3668 // an 8 byte boundary.
3669
3670 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003671 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003672 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003673 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3674 "overflow_arg_area.next");
3675 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3676
3677 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003678 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003679}
3680
John McCall7f416cc2015-09-08 08:05:57 +00003681Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3682 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003683 // Assume that va_list type is correct; should be pointer to LLVM type:
3684 // struct {
3685 // i32 gp_offset;
3686 // i32 fp_offset;
3687 // i8* overflow_arg_area;
3688 // i8* reg_save_area;
3689 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003690 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003691
John McCall7f416cc2015-09-08 08:05:57 +00003692 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003693 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003694 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003695
3696 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3697 // in the registers. If not go to step 7.
3698 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003699 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003700
3701 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3702 // general purpose registers needed to pass type and num_fp to hold
3703 // the number of floating point registers needed.
3704
3705 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3706 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3707 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3708 //
3709 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3710 // register save space).
3711
Craig Topper8a13c412014-05-21 05:09:00 +00003712 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003713 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3714 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003715 if (neededInt) {
James Y Knight751fe282019-02-09 22:22:28 +00003716 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003717 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003718 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3719 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003720 }
3721
3722 if (neededSSE) {
James Y Knight751fe282019-02-09 22:22:28 +00003723 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003724 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3725 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003726 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3727 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003728 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3729 }
3730
3731 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3732 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3733 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3734 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3735
3736 // Emit code to load the value if it was passed in registers.
3737
3738 CGF.EmitBlock(InRegBlock);
3739
3740 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3741 // an offset of l->gp_offset and/or l->fp_offset. This may require
3742 // copying to a temporary location in case the parameter is passed
3743 // in different register classes or requires an alignment greater
3744 // than 8 for general purpose registers and 16 for XMM registers.
3745 //
3746 // FIXME: This really results in shameful code when we end up needing to
3747 // collect arguments from different places; often what should result in a
3748 // simple assembling of a structure from scattered addresses has many more
3749 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003750 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003751 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
James Y Knight751fe282019-02-09 22:22:28 +00003752 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00003753
3754 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003755 if (neededInt && neededSSE) {
3756 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003757 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003758 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003759 Address Tmp = CGF.CreateMemTemp(Ty);
3760 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003761 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003762 llvm::Type *TyLo = ST->getElementType(0);
3763 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003764 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003765 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003766 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3767 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003768 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3769 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003770 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3771 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003772
John McCall7f416cc2015-09-08 08:05:57 +00003773 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003774 // FIXME: Our choice of alignment here and below is probably pessimistic.
3775 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3776 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3777 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
James Y Knight751fe282019-02-09 22:22:28 +00003778 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
John McCall7f416cc2015-09-08 08:05:57 +00003779
3780 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003781 V = CGF.Builder.CreateAlignedLoad(
3782 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3783 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
James Y Knight751fe282019-02-09 22:22:28 +00003784 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
John McCall7f416cc2015-09-08 08:05:57 +00003785
3786 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003787 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003788 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3789 CharUnits::fromQuantity(8));
3790 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003791
3792 // Copy to a temporary if necessary to ensure the appropriate alignment.
3793 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003794 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003795 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003796 CharUnits TyAlign = SizeAlign.second;
3797
3798 // Copy into a temporary if the type is more aligned than the
3799 // register save area.
3800 if (TyAlign.getQuantity() > 8) {
3801 Address Tmp = CGF.CreateMemTemp(Ty);
3802 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003803 RegAddr = Tmp;
3804 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003805
Chris Lattner0cf24192010-06-28 20:05:43 +00003806 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003807 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3808 CharUnits::fromQuantity(16));
3809 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003810 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003811 assert(neededSSE == 2 && "Invalid number of needed registers!");
3812 // SSE registers are spaced 16 bytes apart in the register save
3813 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003814 // The ABI isn't explicit about this, but it seems reasonable
3815 // to assume that the slots are 16-byte aligned, since the stack is
3816 // naturally 16-byte aligned and the prologue is expected to store
3817 // all the SSE registers to the RSA.
3818 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3819 CharUnits::fromQuantity(16));
3820 Address RegAddrHi =
3821 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3822 CharUnits::fromQuantity(16));
Erich Keane24e68402018-02-02 15:53:35 +00003823 llvm::Type *ST = AI.canHaveCoerceToType()
3824 ? AI.getCoerceToType()
3825 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003826 llvm::Value *V;
3827 Address Tmp = CGF.CreateMemTemp(Ty);
3828 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Erich Keane24e68402018-02-02 15:53:35 +00003829 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3830 RegAddrLo, ST->getStructElementType(0)));
James Y Knight751fe282019-02-09 22:22:28 +00003831 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
Erich Keane24e68402018-02-02 15:53:35 +00003832 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3833 RegAddrHi, ST->getStructElementType(1)));
James Y Knight751fe282019-02-09 22:22:28 +00003834 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
John McCall7f416cc2015-09-08 08:05:57 +00003835
3836 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003837 }
3838
3839 // AMD64-ABI 3.5.7p5: Step 5. Set:
3840 // l->gp_offset = l->gp_offset + num_gp * 8
3841 // l->fp_offset = l->fp_offset + num_fp * 16.
3842 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003843 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003844 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3845 gp_offset_p);
3846 }
3847 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003848 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003849 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3850 fp_offset_p);
3851 }
3852 CGF.EmitBranch(ContBlock);
3853
3854 // Emit code to load the value if it was passed in memory.
3855
3856 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003857 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003858
3859 // Return the appropriate result.
3860
3861 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003862 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3863 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003864 return ResAddr;
3865}
3866
Charles Davisc7d5c942015-09-17 20:55:33 +00003867Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3868 QualType Ty) const {
3869 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3870 CGF.getContext().getTypeInfoInChars(Ty),
3871 CharUnits::fromQuantity(8),
3872 /*allowHigherAlign*/ false);
3873}
3874
Erich Keane521ed962017-01-05 00:20:51 +00003875ABIArgInfo
3876WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3877 const ABIArgInfo &current) const {
3878 // Assumes vectorCall calling convention.
3879 const Type *Base = nullptr;
3880 uint64_t NumElts = 0;
3881
3882 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3883 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3884 FreeSSERegs -= NumElts;
3885 return getDirectX86Hva();
3886 }
3887 return current;
3888}
3889
Reid Kleckner80944df2014-10-31 22:00:51 +00003890ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003891 bool IsReturnType, bool IsVectorCall,
3892 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003893
3894 if (Ty->isVoidType())
3895 return ABIArgInfo::getIgnore();
3896
3897 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3898 Ty = EnumTy->getDecl()->getIntegerType();
3899
Reid Kleckner80944df2014-10-31 22:00:51 +00003900 TypeInfo Info = getContext().getTypeInfo(Ty);
3901 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003902 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003903
Reid Kleckner9005f412014-05-02 00:51:20 +00003904 const RecordType *RT = Ty->getAs<RecordType>();
3905 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003906 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003907 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003908 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003909 }
3910
3911 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003912 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003913
Reid Kleckner9005f412014-05-02 00:51:20 +00003914 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003915
Reid Kleckner80944df2014-10-31 22:00:51 +00003916 const Type *Base = nullptr;
3917 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003918 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3919 // other targets.
3920 if ((IsVectorCall || IsRegCall) &&
3921 isHomogeneousAggregate(Ty, Base, NumElts)) {
3922 if (IsRegCall) {
3923 if (FreeSSERegs >= NumElts) {
3924 FreeSSERegs -= NumElts;
3925 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3926 return ABIArgInfo::getDirect();
3927 return ABIArgInfo::getExpand();
3928 }
3929 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3930 } else if (IsVectorCall) {
3931 if (FreeSSERegs >= NumElts &&
3932 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3933 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003934 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003935 } else if (IsReturnType) {
3936 return ABIArgInfo::getExpand();
3937 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3938 // HVAs are delayed and reclassified in the 2nd step.
3939 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3940 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003941 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003942 }
3943
Reid Klecknerec87fec2014-05-02 01:17:12 +00003944 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003945 // If the member pointer is represented by an LLVM int or ptr, pass it
3946 // directly.
3947 llvm::Type *LLTy = CGT.ConvertType(Ty);
3948 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3949 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003950 }
3951
Michael Kuperstein4f818702015-02-24 09:35:58 +00003952 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003953 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3954 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003955 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003956 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003957
Reid Kleckner9005f412014-05-02 00:51:20 +00003958 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003959 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003960 }
3961
Reid Kleckner08f64e92018-10-31 17:43:55 +00003962 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3963 switch (BT->getKind()) {
3964 case BuiltinType::Bool:
3965 // Bool type is always extended to the ABI, other builtin types are not
3966 // extended.
3967 return ABIArgInfo::getExtend(Ty);
3968
3969 case BuiltinType::LongDouble:
3970 // Mingw64 GCC uses the old 80 bit extended precision floating point
3971 // unit. It passes them indirectly through memory.
3972 if (IsMingw64) {
3973 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3974 if (LDF == &llvm::APFloat::x87DoubleExtended())
3975 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3976 }
3977 break;
3978
3979 case BuiltinType::Int128:
3980 case BuiltinType::UInt128:
3981 // If it's a parameter type, the normal ABI rule is that arguments larger
3982 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3983 // even though it isn't particularly efficient.
3984 if (!IsReturnType)
3985 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3986
3987 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3988 // Clang matches them for compatibility.
3989 return ABIArgInfo::getDirect(
3990 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
3991
3992 default:
3993 break;
3994 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003995 }
3996
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003997 return ABIArgInfo::getDirect();
3998}
3999
Erich Keane521ed962017-01-05 00:20:51 +00004000void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4001 unsigned FreeSSERegs,
4002 bool IsVectorCall,
4003 bool IsRegCall) const {
4004 unsigned Count = 0;
4005 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004006 // Vectorcall in x64 only permits the first 6 arguments to be passed
4007 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00004008 if (Count < VectorcallMaxParamNumAsReg)
4009 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4010 else {
4011 // Since these cannot be passed in registers, pretend no registers
4012 // are left.
4013 unsigned ZeroSSERegsAvail = 0;
4014 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4015 IsVectorCall, IsRegCall);
4016 }
4017 ++Count;
4018 }
4019
Erich Keane521ed962017-01-05 00:20:51 +00004020 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004021 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00004022 }
4023}
4024
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004025void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner3fd3de12019-06-20 20:07:20 +00004026 const unsigned CC = FI.getCallingConvention();
4027 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4028 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4029
4030 // If __attribute__((sysv_abi)) is in use, use the SysV argument
4031 // classification rules.
4032 if (CC == llvm::CallingConv::X86_64_SysV) {
4033 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4034 SysVABIInfo.computeInfo(FI);
4035 return;
4036 }
Reid Kleckner37abaca2014-05-09 22:46:15 +00004037
Erich Keane757d3172016-11-02 18:29:35 +00004038 unsigned FreeSSERegs = 0;
4039 if (IsVectorCall) {
4040 // We can use up to 4 SSE return registers with vectorcall.
4041 FreeSSERegs = 4;
4042 } else if (IsRegCall) {
4043 // RegCall gives us 16 SSE registers.
4044 FreeSSERegs = 16;
4045 }
4046
Reid Kleckner80944df2014-10-31 22:00:51 +00004047 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004048 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4049 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004050
Erich Keane757d3172016-11-02 18:29:35 +00004051 if (IsVectorCall) {
4052 // We can use up to 6 SSE register parameters with vectorcall.
4053 FreeSSERegs = 6;
4054 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004055 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004056 FreeSSERegs = 16;
4057 }
4058
Erich Keane521ed962017-01-05 00:20:51 +00004059 if (IsVectorCall) {
4060 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4061 } else {
4062 for (auto &I : FI.arguments())
4063 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4064 }
4065
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004066}
4067
John McCall7f416cc2015-09-08 08:05:57 +00004068Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4069 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004070
4071 bool IsIndirect = false;
4072
4073 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4074 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4075 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4076 uint64_t Width = getContext().getTypeSize(Ty);
4077 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4078 }
4079
4080 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004081 CGF.getContext().getTypeInfoInChars(Ty),
4082 CharUnits::fromQuantity(8),
4083 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004084}
Chris Lattner0cf24192010-06-28 20:05:43 +00004085
John McCallea8d8bb2010-03-11 00:10:12 +00004086// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004087namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004088/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4089class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004090 bool IsSoftFloatABI;
4091
4092 CharUnits getParamTypeAlignment(QualType Ty) const;
4093
John McCallea8d8bb2010-03-11 00:10:12 +00004094public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004095 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4096 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004097
John McCall7f416cc2015-09-08 08:05:57 +00004098 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4099 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004100};
4101
4102class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4103public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004104 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4105 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004106
Craig Topper4f12f102014-03-12 06:41:41 +00004107 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004108 // This is recovered from gcc output.
4109 return 1; // r1 is the dedicated stack pointer
4110 }
4111
4112 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004113 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004114};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004115}
John McCallea8d8bb2010-03-11 00:10:12 +00004116
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004117CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4118 // Complex types are passed just like their elements
4119 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4120 Ty = CTy->getElementType();
4121
4122 if (Ty->isVectorType())
4123 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4124 : 4);
4125
4126 // For single-element float/vector structs, we consider the whole type
4127 // to have the same alignment requirements as its single element.
4128 const Type *AlignTy = nullptr;
4129 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4130 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4131 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4132 (BT && BT->isFloatingPoint()))
4133 AlignTy = EltType;
4134 }
4135
4136 if (AlignTy)
4137 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4138 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004139}
John McCallea8d8bb2010-03-11 00:10:12 +00004140
James Y Knight29b5f082016-02-24 02:59:33 +00004141// TODO: this implementation is now likely redundant with
4142// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004143Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4144 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004145 if (getTarget().getTriple().isOSDarwin()) {
4146 auto TI = getContext().getTypeInfoInChars(Ty);
4147 TI.second = getParamTypeAlignment(Ty);
4148
4149 CharUnits SlotSize = CharUnits::fromQuantity(4);
4150 return emitVoidPtrVAArg(CGF, VAList, Ty,
4151 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4152 /*AllowHigherAlign=*/true);
4153 }
4154
Roman Divacky039b9702016-02-20 08:31:24 +00004155 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004156 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4157 // TODO: Implement this. For now ignore.
4158 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004159 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004160 }
4161
John McCall7f416cc2015-09-08 08:05:57 +00004162 // struct __va_list_tag {
4163 // unsigned char gpr;
4164 // unsigned char fpr;
4165 // unsigned short reserved;
4166 // void *overflow_arg_area;
4167 // void *reg_save_area;
4168 // };
4169
Roman Divacky8a12d842014-11-03 18:32:54 +00004170 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004171 bool isInt =
4172 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004173 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004174
4175 // All aggregates are passed indirectly? That doesn't seem consistent
4176 // with the argument-lowering code.
4177 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004178
4179 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004180
4181 // The calling convention either uses 1-2 GPRs or 1 FPR.
4182 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004183 if (isInt || IsSoftFloatABI) {
James Y Knight751fe282019-02-09 22:22:28 +00004184 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
John McCall7f416cc2015-09-08 08:05:57 +00004185 } else {
James Y Knight751fe282019-02-09 22:22:28 +00004186 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004187 }
John McCall7f416cc2015-09-08 08:05:57 +00004188
4189 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4190
4191 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004192 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004193 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4194 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4195 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004196
Eric Christopher7565e0d2015-05-29 23:09:49 +00004197 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004198 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004199
4200 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4201 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4202 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4203
4204 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4205
John McCall7f416cc2015-09-08 08:05:57 +00004206 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4207 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004208
John McCall7f416cc2015-09-08 08:05:57 +00004209 // Case 1: consume registers.
4210 Address RegAddr = Address::invalid();
4211 {
4212 CGF.EmitBlock(UsingRegs);
4213
James Y Knight751fe282019-02-09 22:22:28 +00004214 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
John McCall7f416cc2015-09-08 08:05:57 +00004215 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4216 CharUnits::fromQuantity(8));
4217 assert(RegAddr.getElementType() == CGF.Int8Ty);
4218
4219 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004220 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004221 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4222 CharUnits::fromQuantity(32));
4223 }
4224
4225 // Get the address of the saved value by scaling the number of
Fangrui Song6907ce22018-07-30 19:24:48 +00004226 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004227 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004228 llvm::Value *RegOffset =
4229 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4230 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4231 RegAddr.getPointer(), RegOffset),
4232 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4233 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4234
4235 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004236 NumRegs =
Fangrui Song6907ce22018-07-30 19:24:48 +00004237 Builder.CreateAdd(NumRegs,
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004238 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004239 Builder.CreateStore(NumRegs, NumRegsAddr);
4240
4241 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004242 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004243
John McCall7f416cc2015-09-08 08:05:57 +00004244 // Case 2: consume space in the overflow area.
4245 Address MemAddr = Address::invalid();
4246 {
4247 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004248
Roman Divacky039b9702016-02-20 08:31:24 +00004249 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4250
John McCall7f416cc2015-09-08 08:05:57 +00004251 // Everything in the overflow area is rounded up to a size of at least 4.
4252 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4253
4254 CharUnits Size;
4255 if (!isIndirect) {
4256 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004257 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004258 } else {
4259 Size = CGF.getPointerSize();
4260 }
4261
James Y Knight751fe282019-02-09 22:22:28 +00004262 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004263 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004264 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004265 // Round up address of argument to alignment
4266 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4267 if (Align > OverflowAreaAlign) {
4268 llvm::Value *Ptr = OverflowArea.getPointer();
4269 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4270 Align);
4271 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004272
John McCall7f416cc2015-09-08 08:05:57 +00004273 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4274
4275 // Increase the overflow area.
4276 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4277 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4278 CGF.EmitBranch(Cont);
4279 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004280
4281 CGF.EmitBlock(Cont);
4282
John McCall7f416cc2015-09-08 08:05:57 +00004283 // Merge the cases with a phi.
4284 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4285 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004286
John McCall7f416cc2015-09-08 08:05:57 +00004287 // Load the pointer if the argument was passed indirectly.
4288 if (isIndirect) {
4289 Result = Address(Builder.CreateLoad(Result, "aggr"),
4290 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004291 }
4292
4293 return Result;
4294}
4295
John McCallea8d8bb2010-03-11 00:10:12 +00004296bool
4297PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4298 llvm::Value *Address) const {
4299 // This is calculated from the LLVM and GCC tables and verified
4300 // against gcc output. AFAIK all ABIs use the same encoding.
4301
4302 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004303
Chris Lattnerece04092012-02-07 00:39:47 +00004304 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004305 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4306 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4307 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4308
4309 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004310 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004311
4312 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004313 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004314
4315 // 64-76 are various 4-byte special-purpose registers:
4316 // 64: mq
4317 // 65: lr
4318 // 66: ctr
4319 // 67: ap
4320 // 68-75 cr0-7
4321 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004322 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004323
4324 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004325 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004326
4327 // 109: vrsave
4328 // 110: vscr
4329 // 111: spe_acc
4330 // 112: spefscr
4331 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004332 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004333
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004334 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004335}
4336
Roman Divackyd966e722012-05-09 18:22:46 +00004337// PowerPC-64
4338
4339namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004340/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004341class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004342public:
4343 enum ABIKind {
4344 ELFv1 = 0,
4345 ELFv2
4346 };
4347
4348private:
4349 static const unsigned GPRBits = 64;
4350 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004351 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004352 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004353
4354 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4355 // will be passed in a QPX register.
4356 bool IsQPXVectorTy(const Type *Ty) const {
4357 if (!HasQPX)
4358 return false;
4359
4360 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4361 unsigned NumElements = VT->getNumElements();
4362 if (NumElements == 1)
4363 return false;
4364
4365 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4366 if (getContext().getTypeSize(Ty) <= 256)
4367 return true;
4368 } else if (VT->getElementType()->
4369 isSpecificBuiltinType(BuiltinType::Float)) {
4370 if (getContext().getTypeSize(Ty) <= 128)
4371 return true;
4372 }
4373 }
4374
4375 return false;
4376 }
4377
4378 bool IsQPXVectorTy(QualType Ty) const {
4379 return IsQPXVectorTy(Ty.getTypePtr());
4380 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004381
4382public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004383 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4384 bool SoftFloatABI)
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004385 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
Hal Finkel415c2a32016-10-02 02:10:45 +00004386 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004387
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004388 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004389 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004390
4391 ABIArgInfo classifyReturnType(QualType RetTy) const;
4392 ABIArgInfo classifyArgumentType(QualType Ty) const;
4393
Reid Klecknere9f6a712014-10-31 17:10:41 +00004394 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4395 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4396 uint64_t Members) const override;
4397
Bill Schmidt84d37792012-10-12 19:26:17 +00004398 // TODO: We can add more logic to computeInfo to improve performance.
4399 // Example: For aggregate arguments that fit in a register, we could
4400 // use getDirectInReg (as is done below for structs containing a single
4401 // floating-point value) to avoid pushing them to memory on function
4402 // entry. This would require changing the logic in PPCISelLowering
4403 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004404 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004405 if (!getCXXABI().classifyReturnType(FI))
4406 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004407 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004408 // We rely on the default argument classification for the most part.
4409 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004410 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004411 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004412 if (T) {
4413 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004414 if (IsQPXVectorTy(T) ||
4415 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004416 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004417 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004418 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004419 continue;
4420 }
4421 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004422 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004423 }
4424 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004425
John McCall7f416cc2015-09-08 08:05:57 +00004426 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4427 QualType Ty) const override;
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004428
4429 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4430 bool asReturnValue) const override {
4431 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4432 }
4433
4434 bool isSwiftErrorInRegister() const override {
4435 return false;
4436 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004437};
4438
4439class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004440
Bill Schmidt25cb3492012-10-03 19:18:57 +00004441public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004442 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004443 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4444 bool SoftFloatABI)
4445 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4446 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004447
Craig Topper4f12f102014-03-12 06:41:41 +00004448 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004449 // This is recovered from gcc output.
4450 return 1; // r1 is the dedicated stack pointer
4451 }
4452
4453 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004454 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004455};
4456
Roman Divackyd966e722012-05-09 18:22:46 +00004457class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4458public:
4459 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4460
Craig Topper4f12f102014-03-12 06:41:41 +00004461 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004462 // This is recovered from gcc output.
4463 return 1; // r1 is the dedicated stack pointer
4464 }
4465
4466 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004467 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004468};
4469
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004470}
Roman Divackyd966e722012-05-09 18:22:46 +00004471
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004472// Return true if the ABI requires Ty to be passed sign- or zero-
4473// extended to 64 bits.
4474bool
4475PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4476 // Treat an enum type as its underlying type.
4477 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4478 Ty = EnumTy->getDecl()->getIntegerType();
4479
4480 // Promotable integer types are required to be promoted by the ABI.
4481 if (Ty->isPromotableIntegerType())
4482 return true;
4483
4484 // In addition to the usual promotable integer types, we also need to
4485 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4486 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4487 switch (BT->getKind()) {
4488 case BuiltinType::Int:
4489 case BuiltinType::UInt:
4490 return true;
4491 default:
4492 break;
4493 }
4494
4495 return false;
4496}
4497
John McCall7f416cc2015-09-08 08:05:57 +00004498/// isAlignedParamType - Determine whether a type requires 16-byte or
4499/// higher alignment in the parameter area. Always returns at least 8.
4500CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004501 // Complex types are passed just like their elements.
4502 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4503 Ty = CTy->getElementType();
4504
4505 // Only vector types of size 16 bytes need alignment (larger types are
4506 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004507 if (IsQPXVectorTy(Ty)) {
4508 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004509 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004510
John McCall7f416cc2015-09-08 08:05:57 +00004511 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004512 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004513 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004514 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004515
4516 // For single-element float/vector structs, we consider the whole type
4517 // to have the same alignment requirements as its single element.
4518 const Type *AlignAsType = nullptr;
4519 const Type *EltType = isSingleElementStruct(Ty, getContext());
4520 if (EltType) {
4521 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004522 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004523 getContext().getTypeSize(EltType) == 128) ||
4524 (BT && BT->isFloatingPoint()))
4525 AlignAsType = EltType;
4526 }
4527
Ulrich Weigandb7122372014-07-21 00:48:09 +00004528 // Likewise for ELFv2 homogeneous aggregates.
4529 const Type *Base = nullptr;
4530 uint64_t Members = 0;
4531 if (!AlignAsType && Kind == ELFv2 &&
4532 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4533 AlignAsType = Base;
4534
Ulrich Weigand581badc2014-07-10 17:20:07 +00004535 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004536 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4537 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004538 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004539
John McCall7f416cc2015-09-08 08:05:57 +00004540 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004541 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004542 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004543 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004544
4545 // Otherwise, we only need alignment for any aggregate type that
4546 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004547 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4548 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004549 return CharUnits::fromQuantity(32);
4550 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004551 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004552
John McCall7f416cc2015-09-08 08:05:57 +00004553 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004554}
4555
Ulrich Weigandb7122372014-07-21 00:48:09 +00004556/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4557/// aggregate. Base is set to the base element type, and Members is set
4558/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004559bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4560 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004561 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4562 uint64_t NElements = AT->getSize().getZExtValue();
4563 if (NElements == 0)
4564 return false;
4565 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4566 return false;
4567 Members *= NElements;
4568 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4569 const RecordDecl *RD = RT->getDecl();
4570 if (RD->hasFlexibleArrayMember())
4571 return false;
4572
4573 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004574
4575 // If this is a C++ record, check the bases first.
4576 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4577 for (const auto &I : CXXRD->bases()) {
4578 // Ignore empty records.
4579 if (isEmptyRecord(getContext(), I.getType(), true))
4580 continue;
4581
4582 uint64_t FldMembers;
4583 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4584 return false;
4585
4586 Members += FldMembers;
4587 }
4588 }
4589
Ulrich Weigandb7122372014-07-21 00:48:09 +00004590 for (const auto *FD : RD->fields()) {
4591 // Ignore (non-zero arrays of) empty records.
4592 QualType FT = FD->getType();
4593 while (const ConstantArrayType *AT =
4594 getContext().getAsConstantArrayType(FT)) {
4595 if (AT->getSize().getZExtValue() == 0)
4596 return false;
4597 FT = AT->getElementType();
4598 }
4599 if (isEmptyRecord(getContext(), FT, true))
4600 continue;
4601
4602 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4603 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00004604 FD->isZeroLengthBitField(getContext()))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004605 continue;
4606
4607 uint64_t FldMembers;
4608 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4609 return false;
4610
4611 Members = (RD->isUnion() ?
4612 std::max(Members, FldMembers) : Members + FldMembers);
4613 }
4614
4615 if (!Base)
4616 return false;
4617
4618 // Ensure there is no padding.
4619 if (getContext().getTypeSize(Base) * Members !=
4620 getContext().getTypeSize(Ty))
4621 return false;
4622 } else {
4623 Members = 1;
4624 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4625 Members = 2;
4626 Ty = CT->getElementType();
4627 }
4628
Reid Klecknere9f6a712014-10-31 17:10:41 +00004629 // Most ABIs only support float, double, and some vector type widths.
4630 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004631 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004632
4633 // The base type must be the same for all members. Types that
4634 // agree in both total size and mode (float vs. vector) are
4635 // treated as being equivalent here.
4636 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004637 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004638 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004639 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4640 // so make sure to widen it explicitly.
4641 if (const VectorType *VT = Base->getAs<VectorType>()) {
4642 QualType EltTy = VT->getElementType();
4643 unsigned NumElements =
4644 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4645 Base = getContext()
4646 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4647 .getTypePtr();
4648 }
4649 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004650
4651 if (Base->isVectorType() != TyPtr->isVectorType() ||
4652 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4653 return false;
4654 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004655 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4656}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004657
Reid Klecknere9f6a712014-10-31 17:10:41 +00004658bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4659 // Homogeneous aggregates for ELFv2 must have base types of float,
4660 // double, long double, or 128-bit vectors.
4661 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4662 if (BT->getKind() == BuiltinType::Float ||
4663 BT->getKind() == BuiltinType::Double ||
Lei Huang449252d2018-07-05 04:32:01 +00004664 BT->getKind() == BuiltinType::LongDouble ||
4665 (getContext().getTargetInfo().hasFloat128Type() &&
4666 (BT->getKind() == BuiltinType::Float128))) {
Hal Finkel415c2a32016-10-02 02:10:45 +00004667 if (IsSoftFloatABI)
4668 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004669 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004670 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004671 }
4672 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004673 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004674 return true;
4675 }
4676 return false;
4677}
4678
4679bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4680 const Type *Base, uint64_t Members) const {
Lei Huang449252d2018-07-05 04:32:01 +00004681 // Vector and fp128 types require one register, other floating point types
4682 // require one or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004683 uint32_t NumRegs =
Lei Huang449252d2018-07-05 04:32:01 +00004684 ((getContext().getTargetInfo().hasFloat128Type() &&
4685 Base->isFloat128Type()) ||
4686 Base->isVectorType()) ? 1
4687 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004688
4689 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004690 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004691}
4692
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004693ABIArgInfo
4694PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004695 Ty = useFirstFieldIfTransparentUnion(Ty);
4696
Bill Schmidt90b22c92012-11-27 02:46:43 +00004697 if (Ty->isAnyComplexType())
4698 return ABIArgInfo::getDirect();
4699
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004700 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4701 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004702 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004703 uint64_t Size = getContext().getTypeSize(Ty);
4704 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004705 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004706 else if (Size < 128) {
4707 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4708 return ABIArgInfo::getDirect(CoerceTy);
4709 }
4710 }
4711
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004712 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004713 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004714 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004715
John McCall7f416cc2015-09-08 08:05:57 +00004716 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4717 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004718
4719 // ELFv2 homogeneous aggregates are passed as array types.
4720 const Type *Base = nullptr;
4721 uint64_t Members = 0;
4722 if (Kind == ELFv2 &&
4723 isHomogeneousAggregate(Ty, Base, Members)) {
4724 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4725 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4726 return ABIArgInfo::getDirect(CoerceTy);
4727 }
4728
Ulrich Weigand601957f2014-07-21 00:56:36 +00004729 // If an aggregate may end up fully in registers, we do not
4730 // use the ByVal method, but pass the aggregate as array.
4731 // This is usually beneficial since we avoid forcing the
4732 // back-end to store the argument to memory.
4733 uint64_t Bits = getContext().getTypeSize(Ty);
4734 if (Bits > 0 && Bits <= 8 * GPRBits) {
4735 llvm::Type *CoerceTy;
4736
4737 // Types up to 8 bytes are passed as integer type (which will be
4738 // properly aligned in the argument save area doubleword).
4739 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004740 CoerceTy =
4741 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004742 // Larger types are passed as arrays, with the base type selected
4743 // according to the required alignment in the save area.
4744 else {
4745 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004746 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004747 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4748 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4749 }
4750
4751 return ABIArgInfo::getDirect(CoerceTy);
4752 }
4753
Ulrich Weigandb7122372014-07-21 00:48:09 +00004754 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004755 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4756 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004757 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004758 }
4759
Alex Bradburye41a5e22018-01-12 20:08:16 +00004760 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4761 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004762}
4763
4764ABIArgInfo
4765PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4766 if (RetTy->isVoidType())
4767 return ABIArgInfo::getIgnore();
4768
Bill Schmidta3d121c2012-12-17 04:20:17 +00004769 if (RetTy->isAnyComplexType())
4770 return ABIArgInfo::getDirect();
4771
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004772 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4773 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004774 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004775 uint64_t Size = getContext().getTypeSize(RetTy);
4776 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004777 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004778 else if (Size < 128) {
4779 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4780 return ABIArgInfo::getDirect(CoerceTy);
4781 }
4782 }
4783
Ulrich Weigandb7122372014-07-21 00:48:09 +00004784 if (isAggregateTypeForABI(RetTy)) {
4785 // ELFv2 homogeneous aggregates are returned as array types.
4786 const Type *Base = nullptr;
4787 uint64_t Members = 0;
4788 if (Kind == ELFv2 &&
4789 isHomogeneousAggregate(RetTy, Base, Members)) {
4790 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4791 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4792 return ABIArgInfo::getDirect(CoerceTy);
4793 }
4794
4795 // ELFv2 small aggregates are returned in up to two registers.
4796 uint64_t Bits = getContext().getTypeSize(RetTy);
4797 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4798 if (Bits == 0)
4799 return ABIArgInfo::getIgnore();
4800
4801 llvm::Type *CoerceTy;
4802 if (Bits > GPRBits) {
4803 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004804 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004805 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004806 CoerceTy =
4807 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004808 return ABIArgInfo::getDirect(CoerceTy);
4809 }
4810
4811 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004812 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004813 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004814
Alex Bradburye41a5e22018-01-12 20:08:16 +00004815 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4816 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004817}
4818
Bill Schmidt25cb3492012-10-03 19:18:57 +00004819// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004820Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4821 QualType Ty) const {
4822 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4823 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004824
John McCall7f416cc2015-09-08 08:05:57 +00004825 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004826
Bill Schmidt924c4782013-01-14 17:45:36 +00004827 // If we have a complex type and the base type is smaller than 8 bytes,
4828 // the ABI calls for the real and imaginary parts to be right-adjusted
4829 // in separate doublewords. However, Clang expects us to produce a
4830 // pointer to a structure with the two parts packed tightly. So generate
4831 // loads of the real and imaginary parts relative to the va_list pointer,
4832 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004833 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4834 CharUnits EltSize = TypeInfo.first / 2;
4835 if (EltSize < SlotSize) {
4836 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4837 SlotSize * 2, SlotSize,
4838 SlotSize, /*AllowHigher*/ true);
4839
4840 Address RealAddr = Addr;
4841 Address ImagAddr = RealAddr;
4842 if (CGF.CGM.getDataLayout().isBigEndian()) {
4843 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4844 SlotSize - EltSize);
4845 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4846 2 * SlotSize - EltSize);
4847 } else {
4848 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4849 }
4850
4851 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4852 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4853 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4854 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4855 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4856
4857 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4858 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4859 /*init*/ true);
4860 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004861 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004862 }
4863
John McCall7f416cc2015-09-08 08:05:57 +00004864 // Otherwise, just use the general rule.
4865 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4866 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004867}
4868
4869static bool
4870PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4871 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004872 // This is calculated from the LLVM and GCC tables and verified
4873 // against gcc output. AFAIK all ABIs use the same encoding.
4874
4875 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4876
4877 llvm::IntegerType *i8 = CGF.Int8Ty;
4878 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4879 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4880 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4881
4882 // 0-31: r0-31, the 8-byte general-purpose registers
4883 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4884
4885 // 32-63: fp0-31, the 8-byte floating-point registers
4886 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4887
Hal Finkel84832a72016-08-30 02:38:34 +00004888 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004889 // 64: mq
4890 // 65: lr
4891 // 66: ctr
4892 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004893 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4894
4895 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004896 // 68-75 cr0-7
4897 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004898 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004899
4900 // 77-108: v0-31, the 16-byte vector registers
4901 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4902
4903 // 109: vrsave
4904 // 110: vscr
4905 // 111: spe_acc
4906 // 112: spefscr
4907 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004908 // 114: tfhar
4909 // 115: tfiar
4910 // 116: texasr
4911 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004912
4913 return false;
4914}
John McCallea8d8bb2010-03-11 00:10:12 +00004915
Bill Schmidt25cb3492012-10-03 19:18:57 +00004916bool
4917PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4918 CodeGen::CodeGenFunction &CGF,
4919 llvm::Value *Address) const {
4920
4921 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4922}
4923
4924bool
4925PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4926 llvm::Value *Address) const {
4927
4928 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4929}
4930
Chris Lattner0cf24192010-06-28 20:05:43 +00004931//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004932// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004933//===----------------------------------------------------------------------===//
4934
4935namespace {
4936
John McCall12f23522016-04-04 18:33:08 +00004937class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004938public:
4939 enum ABIKind {
4940 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004941 DarwinPCS,
4942 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004943 };
4944
4945private:
4946 ABIKind Kind;
4947
4948public:
John McCall12f23522016-04-04 18:33:08 +00004949 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4950 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004951
4952private:
4953 ABIKind getABIKind() const { return Kind; }
4954 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4955
4956 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004957 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004958 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4959 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4960 uint64_t Members) const override;
4961
Tim Northovera2ee4332014-03-29 15:09:45 +00004962 bool isIllegalVectorType(QualType Ty) const;
4963
David Blaikie1cbb9712014-11-14 19:09:44 +00004964 void computeInfo(CGFunctionInfo &FI) const override {
Akira Hatanakad791e922018-03-19 17:38:40 +00004965 if (!::classifyReturnType(getCXXABI(), FI, *this))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004966 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004967
Tim Northoverb047bfa2014-11-27 21:02:49 +00004968 for (auto &it : FI.arguments())
4969 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004970 }
4971
John McCall7f416cc2015-09-08 08:05:57 +00004972 Address EmitDarwinVAArg(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 EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4976 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004977
John McCall7f416cc2015-09-08 08:05:57 +00004978 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4979 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004980 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4981 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4982 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004983 }
John McCall12f23522016-04-04 18:33:08 +00004984
Martin Storsjo502de222017-07-13 17:59:14 +00004985 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4986 QualType Ty) const override;
4987
John McCall56331e22018-01-07 06:28:49 +00004988 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004989 bool asReturnValue) const override {
4990 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4991 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004992 bool isSwiftErrorInRegister() const override {
4993 return true;
4994 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004995
4996 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4997 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004998};
4999
Tim Northover573cbee2014-05-24 12:52:07 +00005000class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00005001public:
Tim Northover573cbee2014-05-24 12:52:07 +00005002 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5003 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00005004
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005005 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005006 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00005007 }
5008
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005009 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5010 return 31;
5011 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005012
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005013 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005014
5015 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5016 CodeGen::CodeGenModule &CGM) const override {
5017 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5018 if (!FD)
5019 return;
5020 llvm::Function *Fn = cast<llvm::Function>(GV);
5021
5022 auto Kind = CGM.getCodeGenOpts().getSignReturnAddress();
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005023 if (Kind != CodeGenOptions::SignReturnAddressScope::None) {
5024 Fn->addFnAttr("sign-return-address",
5025 Kind == CodeGenOptions::SignReturnAddressScope::All
5026 ? "all"
5027 : "non-leaf");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005028
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005029 auto Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5030 Fn->addFnAttr("sign-return-address-key",
5031 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5032 ? "a_key"
5033 : "b_key");
5034 }
5035
5036 if (CGM.getCodeGenOpts().BranchTargetEnforcement)
5037 Fn->addFnAttr("branch-target-enforcement");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005038 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005039};
Martin Storsjo1c8af272017-07-20 05:47:06 +00005040
5041class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5042public:
5043 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5044 : AArch64TargetCodeGenInfo(CGT, K) {}
5045
Eli Friedman540be6d2018-10-26 01:31:57 +00005046 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5047 CodeGen::CodeGenModule &CGM) const override;
5048
Martin Storsjo1c8af272017-07-20 05:47:06 +00005049 void getDependentLibraryOption(llvm::StringRef Lib,
5050 llvm::SmallString<24> &Opt) const override {
5051 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5052 }
5053
5054 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5055 llvm::SmallString<32> &Opt) const override {
5056 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5057 }
5058};
Eli Friedman540be6d2018-10-26 01:31:57 +00005059
5060void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5061 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5062 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5063 if (GV->isDeclaration())
5064 return;
5065 addStackProbeTargetAttributes(D, GV, CGM);
5066}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005067}
Tim Northovera2ee4332014-03-29 15:09:45 +00005068
Tim Northoverb047bfa2014-11-27 21:02:49 +00005069ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00005070 Ty = useFirstFieldIfTransparentUnion(Ty);
5071
Tim Northovera2ee4332014-03-29 15:09:45 +00005072 // Handle illegal vector types here.
5073 if (isIllegalVectorType(Ty)) {
5074 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005075 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00005076 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005077 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5078 return ABIArgInfo::getDirect(ResType);
5079 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005080 if (Size <= 32) {
5081 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00005082 return ABIArgInfo::getDirect(ResType);
5083 }
5084 if (Size == 64) {
5085 llvm::Type *ResType =
5086 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00005087 return ABIArgInfo::getDirect(ResType);
5088 }
5089 if (Size == 128) {
5090 llvm::Type *ResType =
5091 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00005092 return ABIArgInfo::getDirect(ResType);
5093 }
John McCall7f416cc2015-09-08 08:05:57 +00005094 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005095 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005096
5097 if (!isAggregateTypeForABI(Ty)) {
5098 // Treat an enum type as its underlying type.
5099 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5100 Ty = EnumTy->getDecl()->getIntegerType();
5101
Tim Northovera2ee4332014-03-29 15:09:45 +00005102 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005103 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00005104 : ABIArgInfo::getDirect());
5105 }
5106
5107 // Structures with either a non-trivial destructor or a non-trivial
5108 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005109 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005110 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5111 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005112 }
5113
5114 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5115 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005116 uint64_t Size = getContext().getTypeSize(Ty);
5117 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5118 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005119 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5120 return ABIArgInfo::getIgnore();
5121
Tim Northover23bcad22017-05-05 22:36:06 +00005122 // GNU C mode. The only argument that gets ignored is an empty one with size
5123 // 0.
5124 if (IsEmpty && Size == 0)
5125 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005126 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5127 }
5128
5129 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005130 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005131 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005132 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005133 return ABIArgInfo::getDirect(
5134 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005135 }
5136
5137 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005138 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005139 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5140 // same size and alignment.
5141 if (getTarget().isRenderScriptTarget()) {
5142 return coerceToIntArray(Ty, getContext(), getVMContext());
5143 }
Momchil Velikov20208cc2018-07-30 17:48:23 +00005144 unsigned Alignment;
5145 if (Kind == AArch64ABIInfo::AAPCS) {
5146 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5147 Alignment = Alignment < 128 ? 64 : 128;
5148 } else {
5149 Alignment = getContext().getTypeAlign(Ty);
5150 }
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005151 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005152
Tim Northovera2ee4332014-03-29 15:09:45 +00005153 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5154 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005155 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005156 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5157 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5158 }
5159 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5160 }
5161
John McCall7f416cc2015-09-08 08:05:57 +00005162 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005163}
5164
Tim Northover573cbee2014-05-24 12:52:07 +00005165ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005166 if (RetTy->isVoidType())
5167 return ABIArgInfo::getIgnore();
5168
5169 // Large vector types should be returned via memory.
5170 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005171 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005172
5173 if (!isAggregateTypeForABI(RetTy)) {
5174 // Treat an enum type as its underlying type.
5175 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5176 RetTy = EnumTy->getDecl()->getIntegerType();
5177
Tim Northover4dab6982014-04-18 13:46:08 +00005178 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005179 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005180 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005181 }
5182
Tim Northover23bcad22017-05-05 22:36:06 +00005183 uint64_t Size = getContext().getTypeSize(RetTy);
5184 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005185 return ABIArgInfo::getIgnore();
5186
Craig Topper8a13c412014-05-21 05:09:00 +00005187 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005188 uint64_t Members = 0;
5189 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005190 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5191 return ABIArgInfo::getDirect();
5192
5193 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005194 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005195 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5196 // same size and alignment.
5197 if (getTarget().isRenderScriptTarget()) {
5198 return coerceToIntArray(RetTy, getContext(), getVMContext());
5199 }
Pete Cooper635b5092015-04-17 22:16:24 +00005200 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005201 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005202
5203 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5204 // For aggregates with 16-byte alignment, we use i128.
5205 if (Alignment < 128 && Size == 128) {
5206 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5207 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5208 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005209 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5210 }
5211
John McCall7f416cc2015-09-08 08:05:57 +00005212 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005213}
5214
Tim Northover573cbee2014-05-24 12:52:07 +00005215/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5216bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005217 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5218 // Check whether VT is legal.
5219 unsigned NumElements = VT->getNumElements();
5220 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005221 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005222 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005223 return true;
5224 return Size != 64 && (Size != 128 || NumElements == 1);
5225 }
5226 return false;
5227}
5228
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005229bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5230 llvm::Type *eltTy,
5231 unsigned elts) const {
5232 if (!llvm::isPowerOf2_32(elts))
5233 return false;
5234 if (totalSize.getQuantity() != 8 &&
5235 (totalSize.getQuantity() != 16 || elts == 1))
5236 return false;
5237 return true;
5238}
5239
Reid Klecknere9f6a712014-10-31 17:10:41 +00005240bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5241 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5242 // point type or a short-vector type. This is the same as the 32-bit ABI,
5243 // but with the difference that any floating-point type is allowed,
5244 // including __fp16.
5245 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5246 if (BT->isFloatingPoint())
5247 return true;
5248 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5249 unsigned VecSize = getContext().getTypeSize(VT);
5250 if (VecSize == 64 || VecSize == 128)
5251 return true;
5252 }
5253 return false;
5254}
5255
5256bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5257 uint64_t Members) const {
5258 return Members <= 4;
5259}
5260
John McCall7f416cc2015-09-08 08:05:57 +00005261Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005262 QualType Ty,
5263 CodeGenFunction &CGF) const {
5264 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005265 bool IsIndirect = AI.isIndirect();
5266
Tim Northoverb047bfa2014-11-27 21:02:49 +00005267 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5268 if (IsIndirect)
5269 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5270 else if (AI.getCoerceToType())
5271 BaseTy = AI.getCoerceToType();
5272
5273 unsigned NumRegs = 1;
5274 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5275 BaseTy = ArrTy->getElementType();
5276 NumRegs = ArrTy->getNumElements();
5277 }
5278 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5279
Tim Northovera2ee4332014-03-29 15:09:45 +00005280 // The AArch64 va_list type and handling is specified in the Procedure Call
5281 // Standard, section B.4:
5282 //
5283 // struct {
5284 // void *__stack;
5285 // void *__gr_top;
5286 // void *__vr_top;
5287 // int __gr_offs;
5288 // int __vr_offs;
5289 // };
5290
5291 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5292 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5293 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5294 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005295
John Brawn6c49f582019-05-22 11:42:54 +00005296 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5297 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005298
5299 Address reg_offs_p = Address::invalid();
5300 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005301 int reg_top_index;
John Brawn6c49f582019-05-22 11:42:54 +00005302 int RegSize = IsIndirect ? 8 : TySize.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005303 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005304 // 3 is the field number of __gr_offs
James Y Knight751fe282019-02-09 22:22:28 +00005305 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005306 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5307 reg_top_index = 1; // field number for __gr_top
Rui Ueyama83aa9792016-01-14 21:00:27 +00005308 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005309 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005310 // 4 is the field number of __vr_offs.
James Y Knight751fe282019-02-09 22:22:28 +00005311 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005312 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5313 reg_top_index = 2; // field number for __vr_top
Tim Northoverb047bfa2014-11-27 21:02:49 +00005314 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005315 }
5316
5317 //=======================================
5318 // Find out where argument was passed
5319 //=======================================
5320
5321 // If reg_offs >= 0 we're already using the stack for this type of
5322 // argument. We don't want to keep updating reg_offs (in case it overflows,
5323 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5324 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005325 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005326 UsingStack = CGF.Builder.CreateICmpSGE(
5327 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5328
5329 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5330
5331 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005332 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005333 CGF.EmitBlock(MaybeRegBlock);
5334
5335 // Integer arguments may need to correct register alignment (for example a
5336 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5337 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005338 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5339 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005340
5341 reg_offs = CGF.Builder.CreateAdd(
5342 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5343 "align_regoffs");
5344 reg_offs = CGF.Builder.CreateAnd(
5345 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5346 "aligned_regoffs");
5347 }
5348
5349 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005350 // The fact that this is done unconditionally reflects the fact that
5351 // allocating an argument to the stack also uses up all the remaining
5352 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005353 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005354 NewOffset = CGF.Builder.CreateAdd(
5355 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5356 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5357
5358 // Now we're in a position to decide whether this argument really was in
5359 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005360 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005361 InRegs = CGF.Builder.CreateICmpSLE(
5362 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5363
5364 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5365
5366 //=======================================
5367 // Argument was in registers
5368 //=======================================
5369
5370 // Now we emit the code for if the argument was originally passed in
5371 // registers. First start the appropriate block:
5372 CGF.EmitBlock(InRegBlock);
5373
John McCall7f416cc2015-09-08 08:05:57 +00005374 llvm::Value *reg_top = nullptr;
James Y Knight751fe282019-02-09 22:22:28 +00005375 Address reg_top_p =
5376 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005377 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005378 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5379 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5380 Address RegAddr = Address::invalid();
5381 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005382
5383 if (IsIndirect) {
5384 // If it's been passed indirectly (actually a struct), whatever we find from
5385 // stored registers or on the stack will actually be a struct **.
5386 MemTy = llvm::PointerType::getUnqual(MemTy);
5387 }
5388
Craig Topper8a13c412014-05-21 05:09:00 +00005389 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005390 uint64_t NumMembers = 0;
5391 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005392 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005393 // Homogeneous aggregates passed in registers will have their elements split
5394 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5395 // qN+1, ...). We reload and store into a temporary local variable
5396 // contiguously.
5397 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005398 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005399 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5400 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005401 Address Tmp = CGF.CreateTempAlloca(HFATy,
5402 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005403
John McCall7f416cc2015-09-08 08:05:57 +00005404 // On big-endian platforms, the value will be right-aligned in its slot.
5405 int Offset = 0;
5406 if (CGF.CGM.getDataLayout().isBigEndian() &&
5407 BaseTyInfo.first.getQuantity() < 16)
5408 Offset = 16 - BaseTyInfo.first.getQuantity();
5409
Tim Northovera2ee4332014-03-29 15:09:45 +00005410 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005411 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5412 Address LoadAddr =
5413 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5414 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5415
James Y Knight751fe282019-02-09 22:22:28 +00005416 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
Tim Northovera2ee4332014-03-29 15:09:45 +00005417
5418 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5419 CGF.Builder.CreateStore(Elem, StoreAddr);
5420 }
5421
John McCall7f416cc2015-09-08 08:05:57 +00005422 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005423 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005424 // Otherwise the object is contiguous in memory.
5425
5426 // It might be right-aligned in its slot.
5427 CharUnits SlotSize = BaseAddr.getAlignment();
5428 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005429 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John Brawn6c49f582019-05-22 11:42:54 +00005430 TySize < SlotSize) {
5431 CharUnits Offset = SlotSize - TySize;
John McCall7f416cc2015-09-08 08:05:57 +00005432 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005433 }
5434
John McCall7f416cc2015-09-08 08:05:57 +00005435 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005436 }
5437
5438 CGF.EmitBranch(ContBlock);
5439
5440 //=======================================
5441 // Argument was on the stack
5442 //=======================================
5443 CGF.EmitBlock(OnStackBlock);
5444
James Y Knight751fe282019-02-09 22:22:28 +00005445 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
John McCall7f416cc2015-09-08 08:05:57 +00005446 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005447
John McCall7f416cc2015-09-08 08:05:57 +00005448 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005449 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005450 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5451 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005452
John McCall7f416cc2015-09-08 08:05:57 +00005453 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005454
John McCall7f416cc2015-09-08 08:05:57 +00005455 OnStackPtr = CGF.Builder.CreateAdd(
5456 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005457 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005458 OnStackPtr = CGF.Builder.CreateAnd(
5459 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005460 "align_stack");
5461
John McCall7f416cc2015-09-08 08:05:57 +00005462 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005463 }
John McCall7f416cc2015-09-08 08:05:57 +00005464 Address OnStackAddr(OnStackPtr,
5465 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005466
John McCall7f416cc2015-09-08 08:05:57 +00005467 // All stack slots are multiples of 8 bytes.
5468 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5469 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005470 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005471 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005472 else
John Brawn6c49f582019-05-22 11:42:54 +00005473 StackSize = TySize.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005474
John McCall7f416cc2015-09-08 08:05:57 +00005475 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005476 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005477 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005478
5479 // Write the new value of __stack for the next call to va_arg
5480 CGF.Builder.CreateStore(NewStack, stack_p);
5481
5482 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John Brawn6c49f582019-05-22 11:42:54 +00005483 TySize < StackSlotSize) {
5484 CharUnits Offset = StackSlotSize - TySize;
John McCall7f416cc2015-09-08 08:05:57 +00005485 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005486 }
5487
John McCall7f416cc2015-09-08 08:05:57 +00005488 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005489
5490 CGF.EmitBranch(ContBlock);
5491
5492 //=======================================
5493 // Tidy up
5494 //=======================================
5495 CGF.EmitBlock(ContBlock);
5496
John McCall7f416cc2015-09-08 08:05:57 +00005497 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5498 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005499
5500 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005501 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
John Brawn6c49f582019-05-22 11:42:54 +00005502 TyAlign);
Tim Northovera2ee4332014-03-29 15:09:45 +00005503
5504 return ResAddr;
5505}
5506
John McCall7f416cc2015-09-08 08:05:57 +00005507Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5508 CodeGenFunction &CGF) const {
5509 // The backend's lowering doesn't support va_arg for aggregates or
5510 // illegal vector types. Lower VAArg here for these cases and use
5511 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005512 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005513 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005514
John McCall7f416cc2015-09-08 08:05:57 +00005515 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005516
John McCall7f416cc2015-09-08 08:05:57 +00005517 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005518 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005519 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5520 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5521 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005522 }
5523
John McCall7f416cc2015-09-08 08:05:57 +00005524 // The size of the actual thing passed, which might end up just
5525 // being a pointer for indirect types.
5526 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5527
5528 // Arguments bigger than 16 bytes which aren't homogeneous
5529 // aggregates should be passed indirectly.
5530 bool IsIndirect = false;
5531 if (TyInfo.first.getQuantity() > 16) {
5532 const Type *Base = nullptr;
5533 uint64_t Members = 0;
5534 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005535 }
5536
John McCall7f416cc2015-09-08 08:05:57 +00005537 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5538 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005539}
5540
Martin Storsjo502de222017-07-13 17:59:14 +00005541Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5542 QualType Ty) const {
5543 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5544 CGF.getContext().getTypeInfoInChars(Ty),
5545 CharUnits::fromQuantity(8),
5546 /*allowHigherAlign*/ false);
5547}
5548
Tim Northovera2ee4332014-03-29 15:09:45 +00005549//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005550// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005551//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005552
5553namespace {
5554
John McCall12f23522016-04-04 18:33:08 +00005555class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005556public:
5557 enum ABIKind {
5558 APCS = 0,
5559 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005560 AAPCS_VFP = 2,
5561 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005562 };
5563
5564private:
5565 ABIKind Kind;
5566
5567public:
John McCall12f23522016-04-04 18:33:08 +00005568 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5569 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005570 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005571 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005572
John McCall3480ef22011-08-30 01:42:09 +00005573 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005574 switch (getTarget().getTriple().getEnvironment()) {
5575 case llvm::Triple::Android:
5576 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005577 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005578 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005579 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005580 case llvm::Triple::MuslEABI:
5581 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005582 return true;
5583 default:
5584 return false;
5585 }
John McCall3480ef22011-08-30 01:42:09 +00005586 }
5587
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005588 bool isEABIHF() const {
5589 switch (getTarget().getTriple().getEnvironment()) {
5590 case llvm::Triple::EABIHF:
5591 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005592 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005593 return true;
5594 default:
5595 return false;
5596 }
5597 }
5598
Daniel Dunbar020daa92009-09-12 01:00:39 +00005599 ABIKind getABIKind() const { return Kind; }
5600
Tim Northovera484bc02013-10-01 14:34:25 +00005601private:
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005602 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
5603 unsigned functionCallConv) const;
5604 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
5605 unsigned functionCallConv) const;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005606 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5607 uint64_t Members) const;
5608 ABIArgInfo coerceIllegalVector(QualType Ty) const;
Manman Renfef9e312012-10-16 19:18:39 +00005609 bool isIllegalVectorType(QualType Ty) const;
Mikhail Maltseva45292c2019-06-18 14:34:27 +00005610 bool containsAnyFP16Vectors(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005611
Reid Klecknere9f6a712014-10-31 17:10:41 +00005612 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5613 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5614 uint64_t Members) const override;
5615
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005616 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
5617
Craig Topper4f12f102014-03-12 06:41:41 +00005618 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005619
John McCall7f416cc2015-09-08 08:05:57 +00005620 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5621 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005622
5623 llvm::CallingConv::ID getLLVMDefaultCC() const;
5624 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005625 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005626
John McCall56331e22018-01-07 06:28:49 +00005627 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005628 bool asReturnValue) const override {
5629 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5630 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005631 bool isSwiftErrorInRegister() const override {
5632 return true;
5633 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005634 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5635 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005636};
5637
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005638class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5639public:
Chris Lattner2b037972010-07-29 02:01:43 +00005640 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5641 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005642
John McCall3480ef22011-08-30 01:42:09 +00005643 const ARMABIInfo &getABIInfo() const {
5644 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5645 }
5646
Craig Topper4f12f102014-03-12 06:41:41 +00005647 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005648 return 13;
5649 }
Roman Divackyc1617352011-05-18 19:36:54 +00005650
Craig Topper4f12f102014-03-12 06:41:41 +00005651 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005652 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005653 }
5654
Roman Divackyc1617352011-05-18 19:36:54 +00005655 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005656 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005657 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005658
5659 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005660 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005661 return false;
5662 }
John McCall3480ef22011-08-30 01:42:09 +00005663
Craig Topper4f12f102014-03-12 06:41:41 +00005664 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005665 if (getABIInfo().isEABI()) return 88;
5666 return TargetCodeGenInfo::getSizeOfUnwindException();
5667 }
Tim Northovera484bc02013-10-01 14:34:25 +00005668
Eric Christopher162c91c2015-06-05 22:03:00 +00005669 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005670 CodeGen::CodeGenModule &CGM) const override {
5671 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005672 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005673 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005674 if (!FD)
5675 return;
5676
5677 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5678 if (!Attr)
5679 return;
5680
5681 const char *Kind;
5682 switch (Attr->getInterrupt()) {
5683 case ARMInterruptAttr::Generic: Kind = ""; break;
5684 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5685 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5686 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5687 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5688 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5689 }
5690
5691 llvm::Function *Fn = cast<llvm::Function>(GV);
5692
5693 Fn->addFnAttr("interrupt", Kind);
5694
Tim Northover5627d392015-10-30 16:30:45 +00005695 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5696 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005697 return;
5698
5699 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5700 // however this is not necessarily true on taking any interrupt. Instruct
5701 // the backend to perform a realignment as part of the function prologue.
5702 llvm::AttrBuilder B;
5703 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005704 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005705 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005706};
5707
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005708class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005709public:
5710 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5711 : ARMTargetCodeGenInfo(CGT, K) {}
5712
Eric Christopher162c91c2015-06-05 22:03:00 +00005713 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005714 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005715
5716 void getDependentLibraryOption(llvm::StringRef Lib,
5717 llvm::SmallString<24> &Opt) const override {
5718 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5719 }
5720
5721 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5722 llvm::SmallString<32> &Opt) const override {
5723 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5724 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005725};
5726
Eric Christopher162c91c2015-06-05 22:03:00 +00005727void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005728 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5729 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5730 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005731 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00005732 addStackProbeTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005733}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005734}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005735
Chris Lattner22326a12010-07-29 02:31:05 +00005736void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakad791e922018-03-19 17:38:40 +00005737 if (!::classifyReturnType(getCXXABI(), FI, *this))
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005738 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
5739 FI.getCallingConvention());
Oliver Stannard405bded2014-02-11 09:25:50 +00005740
Tim Northoverbc784d12015-02-24 17:22:40 +00005741 for (auto &I : FI.arguments())
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005742 I.info = classifyArgumentType(I.type, FI.isVariadic(),
5743 FI.getCallingConvention());
5744
Daniel Dunbar020daa92009-09-12 01:00:39 +00005745
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005746 // Always honor user-specified calling convention.
5747 if (FI.getCallingConvention() != llvm::CallingConv::C)
5748 return;
5749
John McCall882987f2013-02-28 19:01:20 +00005750 llvm::CallingConv::ID cc = getRuntimeCC();
5751 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005752 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005753}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005754
John McCall882987f2013-02-28 19:01:20 +00005755/// Return the default calling convention that LLVM will use.
5756llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5757 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005758 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005759 return llvm::CallingConv::ARM_AAPCS_VFP;
5760 else if (isEABI())
5761 return llvm::CallingConv::ARM_AAPCS;
5762 else
5763 return llvm::CallingConv::ARM_APCS;
5764}
5765
5766/// Return the calling convention that our ABI would like us to use
5767/// as the C calling convention.
5768llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005769 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005770 case APCS: return llvm::CallingConv::ARM_APCS;
5771 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5772 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005773 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005774 }
John McCall882987f2013-02-28 19:01:20 +00005775 llvm_unreachable("bad ABI kind");
5776}
5777
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005778void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005779 assert(getRuntimeCC() == llvm::CallingConv::C);
5780
5781 // Don't muddy up the IR with a ton of explicit annotations if
5782 // they'd just match what LLVM will infer from the triple.
5783 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5784 if (abiCC != getLLVMDefaultCC())
5785 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005786}
5787
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005788ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5789 uint64_t Size = getContext().getTypeSize(Ty);
5790 if (Size <= 32) {
5791 llvm::Type *ResType =
5792 llvm::Type::getInt32Ty(getVMContext());
5793 return ABIArgInfo::getDirect(ResType);
5794 }
5795 if (Size == 64 || Size == 128) {
5796 llvm::Type *ResType = llvm::VectorType::get(
5797 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5798 return ABIArgInfo::getDirect(ResType);
5799 }
5800 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5801}
5802
5803ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5804 const Type *Base,
5805 uint64_t Members) const {
5806 assert(Base && "Base class should be set for homogeneous aggregate");
5807 // Base can be a floating-point or a vector.
5808 if (const VectorType *VT = Base->getAs<VectorType>()) {
5809 // FP16 vectors should be converted to integer vectors
Mikhail Maltseva45292c2019-06-18 14:34:27 +00005810 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005811 uint64_t Size = getContext().getTypeSize(VT);
5812 llvm::Type *NewVecTy = llvm::VectorType::get(
5813 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5814 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5815 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5816 }
5817 }
5818 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5819}
5820
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005821ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
5822 unsigned functionCallConv) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005823 // 6.1.2.1 The following argument types are VFP CPRCs:
5824 // A single-precision floating-point type (including promoted
5825 // half-precision types); A double-precision floating-point type;
5826 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5827 // with a Base Type of a single- or double-precision floating-point type,
5828 // 64-bit containerized vectors or 128-bit containerized vectors with one
5829 // to four Elements.
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005830 // Variadic functions should always marshal to the base standard.
5831 bool IsAAPCS_VFP =
5832 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005833
Reid Klecknerb1be6832014-11-15 01:41:41 +00005834 Ty = useFirstFieldIfTransparentUnion(Ty);
5835
Manman Renfef9e312012-10-16 19:18:39 +00005836 // Handle illegal vector types here.
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005837 if (isIllegalVectorType(Ty))
5838 return coerceIllegalVector(Ty);
Manman Renfef9e312012-10-16 19:18:39 +00005839
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005840 // _Float16 and __fp16 get passed as if it were an int or float, but with
5841 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5842 // half type natively, and does not need to interwork with AAPCS code.
5843 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5844 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005845 llvm::Type *ResType = IsAAPCS_VFP ?
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005846 llvm::Type::getFloatTy(getVMContext()) :
5847 llvm::Type::getInt32Ty(getVMContext());
5848 return ABIArgInfo::getDirect(ResType);
5849 }
5850
John McCalla1dee5302010-08-22 10:59:02 +00005851 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005852 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005853 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005854 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005855 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005856
Alex Bradburye41a5e22018-01-12 20:08:16 +00005857 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005858 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005859 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005860
Oliver Stannard405bded2014-02-11 09:25:50 +00005861 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005862 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005863 }
Tim Northover1060eae2013-06-21 22:49:34 +00005864
Daniel Dunbar09d33622009-09-14 21:54:03 +00005865 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005866 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005867 return ABIArgInfo::getIgnore();
5868
Carey Williams2c3c9ca2019-03-22 16:20:45 +00005869 if (IsAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005870 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5871 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005872 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005873 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005874 if (isHomogeneousAggregate(Ty, Base, Members))
5875 return classifyHomogeneousAggregate(Ty, Base, Members);
Tim Northover5627d392015-10-30 16:30:45 +00005876 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5877 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5878 // this convention even for a variadic function: the backend will use GPRs
5879 // if needed.
5880 const Type *Base = nullptr;
5881 uint64_t Members = 0;
5882 if (isHomogeneousAggregate(Ty, Base, Members)) {
5883 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5884 llvm::Type *Ty =
5885 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5886 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5887 }
5888 }
5889
5890 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5891 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5892 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5893 // bigger than 128-bits, they get placed in space allocated by the caller,
5894 // and a pointer is passed.
5895 return ABIArgInfo::getIndirect(
5896 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005897 }
5898
Manman Ren6c30e132012-08-13 21:23:55 +00005899 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005900 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5901 // most 8-byte. We realign the indirect argument if type alignment is bigger
5902 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005903 uint64_t ABIAlign = 4;
Momchil Velikov20208cc2018-07-30 17:48:23 +00005904 uint64_t TyAlign;
Manman Ren505d68f2012-11-05 22:42:46 +00005905 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Momchil Velikov20208cc2018-07-30 17:48:23 +00005906 getABIKind() == ARMABIInfo::AAPCS) {
5907 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
Manman Ren505d68f2012-11-05 22:42:46 +00005908 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Momchil Velikov20208cc2018-07-30 17:48:23 +00005909 } else {
5910 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5911 }
Manman Ren8cd99812012-11-06 04:58:01 +00005912 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005913 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005914 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5915 /*ByVal=*/true,
5916 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005917 }
5918
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005919 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5920 // same size and alignment.
5921 if (getTarget().isRenderScriptTarget()) {
5922 return coerceToIntArray(Ty, getContext(), getVMContext());
5923 }
5924
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005925 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005926 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005927 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005928 // FIXME: Try to match the types of the arguments more accurately where
5929 // we can.
Momchil Velikov20208cc2018-07-30 17:48:23 +00005930 if (TyAlign <= 4) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005931 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5932 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005933 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005934 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5935 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005936 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005937
Tim Northover5a1558e2014-11-07 22:30:50 +00005938 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005939}
5940
Chris Lattner458b2aa2010-07-29 02:16:43 +00005941static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005942 llvm::LLVMContext &VMContext) {
5943 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5944 // is called integer-like if its size is less than or equal to one word, and
5945 // the offset of each of its addressable sub-fields is zero.
5946
5947 uint64_t Size = Context.getTypeSize(Ty);
5948
5949 // Check that the type fits in a word.
5950 if (Size > 32)
5951 return false;
5952
5953 // FIXME: Handle vector types!
5954 if (Ty->isVectorType())
5955 return false;
5956
Daniel Dunbard53bac72009-09-14 02:20:34 +00005957 // Float types are never treated as "integer like".
5958 if (Ty->isRealFloatingType())
5959 return false;
5960
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005961 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005962 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005963 return true;
5964
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005965 // Small complex integer types are "integer like".
5966 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5967 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005968
5969 // Single element and zero sized arrays should be allowed, by the definition
5970 // above, but they are not.
5971
5972 // Otherwise, it must be a record type.
5973 const RecordType *RT = Ty->getAs<RecordType>();
5974 if (!RT) return false;
5975
5976 // Ignore records with flexible arrays.
5977 const RecordDecl *RD = RT->getDecl();
5978 if (RD->hasFlexibleArrayMember())
5979 return false;
5980
5981 // Check that all sub-fields are at offset 0, and are themselves "integer
5982 // like".
5983 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5984
5985 bool HadField = false;
5986 unsigned idx = 0;
5987 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5988 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005989 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005990
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005991 // Bit-fields are not addressable, we only need to verify they are "integer
5992 // like". We still have to disallow a subsequent non-bitfield, for example:
5993 // struct { int : 0; int x }
5994 // is non-integer like according to gcc.
5995 if (FD->isBitField()) {
5996 if (!RD->isUnion())
5997 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005998
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005999 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6000 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006001
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006002 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006003 }
6004
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006005 // Check if this field is at offset 0.
6006 if (Layout.getFieldOffset(idx) != 0)
6007 return false;
6008
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006009 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6010 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00006011
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006012 // Only allow at most one field in a structure. This doesn't match the
6013 // wording above, but follows gcc in situations with a field following an
6014 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006015 if (!RD->isUnion()) {
6016 if (HadField)
6017 return false;
6018
6019 HadField = true;
6020 }
6021 }
6022
6023 return true;
6024}
6025
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006026ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6027 unsigned functionCallConv) const {
6028
6029 // Variadic functions should always marshal to the base standard.
6030 bool IsAAPCS_VFP =
6031 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006032
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006033 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006034 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006035
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006036 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6037 // Large vector types should be returned via memory.
6038 if (getContext().getTypeSize(RetTy) > 128)
6039 return getNaturalAlignIndirect(RetTy);
6040 // FP16 vectors should be converted to integer vectors
6041 if (!getTarget().hasLegalHalfType() &&
6042 (VT->getElementType()->isFloat16Type() ||
6043 VT->getElementType()->isHalfType()))
6044 return coerceIllegalVector(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00006045 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00006046
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00006047 // _Float16 and __fp16 get returned as if it were an int or float, but with
6048 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6049 // half type natively, and does not need to interwork with AAPCS code.
6050 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6051 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006052 llvm::Type *ResType = IsAAPCS_VFP ?
Oliver Stannarddc2854c2015-09-03 12:40:58 +00006053 llvm::Type::getFloatTy(getVMContext()) :
6054 llvm::Type::getInt32Ty(getVMContext());
6055 return ABIArgInfo::getDirect(ResType);
6056 }
6057
John McCalla1dee5302010-08-22 10:59:02 +00006058 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00006059 // Treat an enum type as its underlying type.
6060 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6061 RetTy = EnumTy->getDecl()->getIntegerType();
6062
Alex Bradburye41a5e22018-01-12 20:08:16 +00006063 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00006064 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00006065 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006066
6067 // Are we following APCS?
6068 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00006069 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006070 return ABIArgInfo::getIgnore();
6071
Daniel Dunbareedf1512010-02-01 23:31:19 +00006072 // Complex types are all returned as packed integers.
6073 //
6074 // FIXME: Consider using 2 x vector types if the back end handles them
6075 // correctly.
6076 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006077 return ABIArgInfo::getDirect(llvm::IntegerType::get(
6078 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00006079
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006080 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006081 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006082 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006083 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006084 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006085 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006086 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006087 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6088 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006089 }
6090
6091 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00006092 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006093 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006094
6095 // Otherwise this is an AAPCS variant.
6096
Chris Lattner458b2aa2010-07-29 02:16:43 +00006097 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006098 return ABIArgInfo::getIgnore();
6099
Bob Wilson1d9269a2011-11-02 04:51:36 +00006100 // Check for homogeneous aggregates with AAPCS-VFP.
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006101 if (IsAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00006102 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00006103 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006104 if (isHomogeneousAggregate(RetTy, Base, Members))
6105 return classifyHomogeneousAggregate(RetTy, Base, Members);
Bob Wilson1d9269a2011-11-02 04:51:36 +00006106 }
6107
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006108 // Aggregates <= 4 bytes are returned in r0; other aggregates
6109 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006110 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006111 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00006112 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6113 // same size and alignment.
6114 if (getTarget().isRenderScriptTarget()) {
6115 return coerceToIntArray(RetTy, getContext(), getVMContext());
6116 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00006117 if (getDataLayout().isBigEndian())
6118 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006119 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006120
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006121 // Return in the smallest viable integer type.
6122 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006123 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006124 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006125 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6126 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006127 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6128 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6129 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006130 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006131 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006132 }
6133
John McCall7f416cc2015-09-08 08:05:57 +00006134 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006135}
6136
Manman Renfef9e312012-10-16 19:18:39 +00006137/// isIllegalVector - check whether Ty is an illegal vector type.
6138bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006139 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006140 // On targets that don't support FP16, FP16 is expanded into float, and we
6141 // don't want the ABI to depend on whether or not FP16 is supported in
6142 // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6143 if (!getTarget().hasLegalHalfType() &&
6144 (VT->getElementType()->isFloat16Type() ||
6145 VT->getElementType()->isHalfType()))
6146 return true;
Stephen Hines8267e7d2015-12-04 01:39:30 +00006147 if (isAndroid()) {
6148 // Android shipped using Clang 3.1, which supported a slightly different
6149 // vector ABI. The primary differences were that 3-element vector types
6150 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6151 // accepts that legacy behavior for Android only.
6152 // Check whether VT is legal.
6153 unsigned NumElements = VT->getNumElements();
6154 // NumElements should be power of 2 or equal to 3.
6155 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6156 return true;
6157 } else {
6158 // Check whether VT is legal.
6159 unsigned NumElements = VT->getNumElements();
6160 uint64_t Size = getContext().getTypeSize(VT);
6161 // NumElements should be power of 2.
6162 if (!llvm::isPowerOf2_32(NumElements))
6163 return true;
6164 // Size should be greater than 32 bits.
6165 return Size <= 32;
6166 }
Manman Renfef9e312012-10-16 19:18:39 +00006167 }
6168 return false;
6169}
6170
Mikhail Maltseva45292c2019-06-18 14:34:27 +00006171/// Return true if a type contains any 16-bit floating point vectors
6172bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6173 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6174 uint64_t NElements = AT->getSize().getZExtValue();
6175 if (NElements == 0)
6176 return false;
6177 return containsAnyFP16Vectors(AT->getElementType());
6178 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6179 const RecordDecl *RD = RT->getDecl();
6180
6181 // If this is a C++ record, check the bases first.
6182 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6183 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6184 return containsAnyFP16Vectors(B.getType());
6185 }))
6186 return true;
6187
6188 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6189 return FD && containsAnyFP16Vectors(FD->getType());
6190 }))
6191 return true;
6192
6193 return false;
6194 } else {
6195 if (const VectorType *VT = Ty->getAs<VectorType>())
6196 return (VT->getElementType()->isFloat16Type() ||
6197 VT->getElementType()->isHalfType());
6198 return false;
6199 }
6200}
6201
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006202bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6203 llvm::Type *eltTy,
6204 unsigned numElts) const {
6205 if (!llvm::isPowerOf2_32(numElts))
6206 return false;
6207 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6208 if (size > 64)
6209 return false;
6210 if (vectorSize.getQuantity() != 8 &&
6211 (vectorSize.getQuantity() != 16 || numElts == 1))
6212 return false;
6213 return true;
6214}
6215
Reid Klecknere9f6a712014-10-31 17:10:41 +00006216bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6217 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6218 // double, or 64-bit or 128-bit vectors.
6219 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6220 if (BT->getKind() == BuiltinType::Float ||
6221 BT->getKind() == BuiltinType::Double ||
6222 BT->getKind() == BuiltinType::LongDouble)
6223 return true;
6224 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6225 unsigned VecSize = getContext().getTypeSize(VT);
6226 if (VecSize == 64 || VecSize == 128)
6227 return true;
6228 }
6229 return false;
6230}
6231
6232bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6233 uint64_t Members) const {
6234 return Members <= 4;
6235}
6236
Carey Williams2c3c9ca2019-03-22 16:20:45 +00006237bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6238 bool acceptHalf) const {
6239 // Give precedence to user-specified calling conventions.
6240 if (callConvention != llvm::CallingConv::C)
6241 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6242 else
6243 return (getABIKind() == AAPCS_VFP) ||
6244 (acceptHalf && (getABIKind() == AAPCS16_VFP));
6245}
6246
John McCall7f416cc2015-09-08 08:05:57 +00006247Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6248 QualType Ty) const {
6249 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006250
John McCall7f416cc2015-09-08 08:05:57 +00006251 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006252 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006253 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6254 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6255 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006256 }
6257
John Brawn6c49f582019-05-22 11:42:54 +00006258 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6259 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
Manman Rencca54d02012-10-16 19:01:37 +00006260
John McCall7f416cc2015-09-08 08:05:57 +00006261 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6262 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006263 const Type *Base = nullptr;
6264 uint64_t Members = 0;
John Brawn6c49f582019-05-22 11:42:54 +00006265 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
John McCall7f416cc2015-09-08 08:05:57 +00006266 IsIndirect = true;
6267
Tim Northover5627d392015-10-30 16:30:45 +00006268 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6269 // allocated by the caller.
John Brawn6c49f582019-05-22 11:42:54 +00006270 } else if (TySize > CharUnits::fromQuantity(16) &&
Tim Northover5627d392015-10-30 16:30:45 +00006271 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6272 !isHomogeneousAggregate(Ty, Base, Members)) {
6273 IsIndirect = true;
6274
John McCall7f416cc2015-09-08 08:05:57 +00006275 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006276 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6277 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006278 // Our callers should be prepared to handle an under-aligned address.
6279 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6280 getABIKind() == ARMABIInfo::AAPCS) {
6281 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6282 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006283 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6284 // ARMv7k allows type alignment up to 16 bytes.
6285 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6286 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006287 } else {
6288 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006289 }
Manman Rencca54d02012-10-16 19:01:37 +00006290
John Brawn6c49f582019-05-22 11:42:54 +00006291 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
John McCall7f416cc2015-09-08 08:05:57 +00006292 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6293 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006294}
6295
Chris Lattner0cf24192010-06-28 20:05:43 +00006296//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006297// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006298//===----------------------------------------------------------------------===//
6299
6300namespace {
6301
Justin Holewinski83e96682012-05-24 17:43:12 +00006302class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006303public:
Justin Holewinski36837432013-03-30 14:38:24 +00006304 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006305
6306 ABIArgInfo classifyReturnType(QualType RetTy) const;
6307 ABIArgInfo classifyArgumentType(QualType Ty) const;
6308
Craig Topper4f12f102014-03-12 06:41:41 +00006309 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006310 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6311 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006312};
6313
Justin Holewinski83e96682012-05-24 17:43:12 +00006314class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006315public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006316 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6317 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006318
Eric Christopher162c91c2015-06-05 22:03:00 +00006319 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006320 CodeGen::CodeGenModule &M) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00006321 bool shouldEmitStaticExternCAliases() const override;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006322
Justin Holewinski36837432013-03-30 14:38:24 +00006323private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006324 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6325 // resulting MDNode to the nvvm.annotations MDNode.
6326 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006327};
6328
Alexey Bataev123ad192019-02-27 20:29:45 +00006329/// Checks if the type is unsupported directly by the current target.
6330static bool isUnsupportedType(ASTContext &Context, QualType T) {
6331 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6332 return true;
Alexey Bataev7ae267d2019-06-18 19:04:27 +00006333 if (!Context.getTargetInfo().hasFloat128Type() &&
6334 (T->isFloat128Type() ||
6335 (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
Alexey Bataev123ad192019-02-27 20:29:45 +00006336 return true;
6337 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6338 Context.getTypeSize(T) > 64)
6339 return true;
6340 if (const auto *AT = T->getAsArrayTypeUnsafe())
6341 return isUnsupportedType(Context, AT->getElementType());
6342 const auto *RT = T->getAs<RecordType>();
6343 if (!RT)
6344 return false;
6345 const RecordDecl *RD = RT->getDecl();
6346
6347 // If this is a C++ record, check the bases first.
6348 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6349 for (const CXXBaseSpecifier &I : CXXRD->bases())
6350 if (isUnsupportedType(Context, I.getType()))
6351 return true;
6352
6353 for (const FieldDecl *I : RD->fields())
6354 if (isUnsupportedType(Context, I->getType()))
6355 return true;
6356 return false;
6357}
6358
6359/// Coerce the given type into an array with maximum allowed size of elements.
6360static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context,
6361 llvm::LLVMContext &LLVMContext,
6362 unsigned MaxSize) {
6363 // Alignment and Size are measured in bits.
6364 const uint64_t Size = Context.getTypeSize(Ty);
6365 const uint64_t Alignment = Context.getTypeAlign(Ty);
6366 const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6367 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div);
6368 const uint64_t NumElements = (Size + Div - 1) / Div;
6369 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6370}
6371
Justin Holewinski83e96682012-05-24 17:43:12 +00006372ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006373 if (RetTy->isVoidType())
6374 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006375
Alexey Bataev123ad192019-02-27 20:29:45 +00006376 if (getContext().getLangOpts().OpenMP &&
6377 getContext().getLangOpts().OpenMPIsDevice &&
6378 isUnsupportedType(getContext(), RetTy))
6379 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64);
6380
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006381 // note: this is different from default ABI
6382 if (!RetTy->isScalarType())
6383 return ABIArgInfo::getDirect();
6384
6385 // Treat an enum type as its underlying type.
6386 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6387 RetTy = EnumTy->getDecl()->getIntegerType();
6388
Alex Bradburye41a5e22018-01-12 20:08:16 +00006389 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6390 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006391}
6392
Justin Holewinski83e96682012-05-24 17:43:12 +00006393ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006394 // Treat an enum type as its underlying type.
6395 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6396 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006397
Eli Bendersky95338a02014-10-29 13:43:21 +00006398 // Return aggregates type as indirect by value
6399 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006400 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006401
Alex Bradburye41a5e22018-01-12 20:08:16 +00006402 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6403 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006404}
6405
Justin Holewinski83e96682012-05-24 17:43:12 +00006406void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006407 if (!getCXXABI().classifyReturnType(FI))
6408 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006409 for (auto &I : FI.arguments())
6410 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006411
6412 // Always honor user-specified calling convention.
6413 if (FI.getCallingConvention() != llvm::CallingConv::C)
6414 return;
6415
John McCall882987f2013-02-28 19:01:20 +00006416 FI.setEffectiveCallingConvention(getRuntimeCC());
6417}
6418
John McCall7f416cc2015-09-08 08:05:57 +00006419Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6420 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006421 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006422}
6423
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006424void NVPTXTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006425 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6426 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006427 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006428 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006429 if (!FD) return;
6430
6431 llvm::Function *F = cast<llvm::Function>(GV);
6432
6433 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006434 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006435 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006436 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006437 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006438 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006439 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6440 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006441 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006442 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006443 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006444 }
Justin Holewinski38031972011-10-05 17:58:44 +00006445
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006446 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006447 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006448 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006449 // __global__ functions cannot be called from the device, we do not
6450 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006451 if (FD->hasAttr<CUDAGlobalAttr>()) {
6452 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6453 addNVVMMetadata(F, "kernel", 1);
6454 }
Artem Belevich7093e402015-04-21 22:55:54 +00006455 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006456 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006457 llvm::APSInt MaxThreads(32);
6458 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6459 if (MaxThreads > 0)
6460 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6461
6462 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6463 // not specified in __launch_bounds__ or if the user specified a 0 value,
6464 // we don't have to add a PTX directive.
6465 if (Attr->getMinBlocks()) {
6466 llvm::APSInt MinBlocks(32);
6467 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6468 if (MinBlocks > 0)
6469 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6470 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006471 }
6472 }
Justin Holewinski38031972011-10-05 17:58:44 +00006473 }
6474}
6475
Eli Benderskye06a2c42014-04-15 16:57:05 +00006476void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6477 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006478 llvm::Module *M = F->getParent();
6479 llvm::LLVMContext &Ctx = M->getContext();
6480
6481 // Get "nvvm.annotations" metadata node
6482 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6483
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006484 llvm::Metadata *MDVals[] = {
6485 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6486 llvm::ConstantAsMetadata::get(
6487 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006488 // Append metadata to nvvm.annotations
6489 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6490}
Yaxun Liub0eee292018-03-29 14:50:00 +00006491
6492bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6493 return false;
6494}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006495}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006496
6497//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006498// SystemZ ABI Implementation
6499//===----------------------------------------------------------------------===//
6500
6501namespace {
6502
Bryan Chane3f1ed52016-04-28 13:56:43 +00006503class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006504 bool HasVector;
6505
Ulrich Weigand47445072013-05-06 16:26:41 +00006506public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006507 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006508 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006509
6510 bool isPromotableIntegerType(QualType Ty) const;
6511 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006512 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006513 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006514 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006515
6516 ABIArgInfo classifyReturnType(QualType RetTy) const;
6517 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6518
Craig Topper4f12f102014-03-12 06:41:41 +00006519 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006520 if (!getCXXABI().classifyReturnType(FI))
6521 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006522 for (auto &I : FI.arguments())
6523 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006524 }
6525
John McCall7f416cc2015-09-08 08:05:57 +00006526 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6527 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006528
John McCall56331e22018-01-07 06:28:49 +00006529 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006530 bool asReturnValue) const override {
6531 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6532 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006533 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006534 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006535 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006536};
6537
6538class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6539public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006540 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6541 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006542};
6543
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006544}
Ulrich Weigand47445072013-05-06 16:26:41 +00006545
6546bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6547 // Treat an enum type as its underlying type.
6548 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6549 Ty = EnumTy->getDecl()->getIntegerType();
6550
6551 // Promotable integer types are required to be promoted by the ABI.
6552 if (Ty->isPromotableIntegerType())
6553 return true;
6554
6555 // 32-bit values must also be promoted.
6556 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6557 switch (BT->getKind()) {
6558 case BuiltinType::Int:
6559 case BuiltinType::UInt:
6560 return true;
6561 default:
6562 return false;
6563 }
6564 return false;
6565}
6566
6567bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006568 return (Ty->isAnyComplexType() ||
6569 Ty->isVectorType() ||
6570 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006571}
6572
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006573bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6574 return (HasVector &&
6575 Ty->isVectorType() &&
6576 getContext().getTypeSize(Ty) <= 128);
6577}
6578
Ulrich Weigand47445072013-05-06 16:26:41 +00006579bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6580 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6581 switch (BT->getKind()) {
6582 case BuiltinType::Float:
6583 case BuiltinType::Double:
6584 return true;
6585 default:
6586 return false;
6587 }
6588
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006589 return false;
6590}
6591
6592QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006593 if (const RecordType *RT = Ty->getAsStructureType()) {
6594 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006595 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006596
6597 // If this is a C++ record, check the bases first.
6598 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006599 for (const auto &I : CXXRD->bases()) {
6600 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006601
6602 // Empty bases don't affect things either way.
6603 if (isEmptyRecord(getContext(), Base, true))
6604 continue;
6605
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006606 if (!Found.isNull())
6607 return Ty;
6608 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006609 }
6610
6611 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006612 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006613 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006614 // Unlike isSingleElementStruct(), empty structure and array fields
6615 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006616 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00006617 FD->isZeroLengthBitField(getContext()))
Ulrich Weigand759449c2015-03-30 13:49:01 +00006618 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006619
6620 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006621 // Nested structures still do though.
6622 if (!Found.isNull())
6623 return Ty;
6624 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006625 }
6626
6627 // Unlike isSingleElementStruct(), trailing padding is allowed.
6628 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006629 if (!Found.isNull())
6630 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006631 }
6632
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006633 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006634}
6635
John McCall7f416cc2015-09-08 08:05:57 +00006636Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6637 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006638 // Assume that va_list type is correct; should be pointer to LLVM type:
6639 // struct {
6640 // i64 __gpr;
6641 // i64 __fpr;
6642 // i8 *__overflow_arg_area;
6643 // i8 *__reg_save_area;
6644 // };
6645
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006646 // Every non-vector argument occupies 8 bytes and is passed by preference
6647 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6648 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006649 Ty = getContext().getCanonicalType(Ty);
6650 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006651 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006652 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006653 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006654 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006655 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006656 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006657 CharUnits UnpaddedSize;
6658 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006659 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006660 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6661 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006662 } else {
6663 if (AI.getCoerceToType())
6664 ArgTy = AI.getCoerceToType();
6665 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006666 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006667 UnpaddedSize = TyInfo.first;
6668 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006669 }
John McCall7f416cc2015-09-08 08:05:57 +00006670 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6671 if (IsVector && UnpaddedSize > PaddedSize)
6672 PaddedSize = CharUnits::fromQuantity(16);
6673 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006674
John McCall7f416cc2015-09-08 08:05:57 +00006675 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006676
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006677 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006678 llvm::Value *PaddedSizeV =
6679 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006680
6681 if (IsVector) {
6682 // Work out the address of a vector argument on the stack.
6683 // Vector arguments are always passed in the high bits of a
6684 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006685 Address OverflowArgAreaPtr =
James Y Knight751fe282019-02-09 22:22:28 +00006686 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006687 Address OverflowArgArea =
6688 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6689 TyInfo.second);
6690 Address MemAddr =
6691 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006692
6693 // Update overflow_arg_area_ptr pointer
6694 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006695 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6696 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006697 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6698
6699 return MemAddr;
6700 }
6701
John McCall7f416cc2015-09-08 08:05:57 +00006702 assert(PaddedSize.getQuantity() == 8);
6703
6704 unsigned MaxRegs, RegCountField, RegSaveIndex;
6705 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006706 if (InFPRs) {
6707 MaxRegs = 4; // Maximum of 4 FPR arguments
6708 RegCountField = 1; // __fpr
6709 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006710 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006711 } else {
6712 MaxRegs = 5; // Maximum of 5 GPR arguments
6713 RegCountField = 0; // __gpr
6714 RegSaveIndex = 2; // save offset for r2
6715 RegPadding = Padding; // values are passed in the low bits of a GPR
6716 }
6717
James Y Knight751fe282019-02-09 22:22:28 +00006718 Address RegCountPtr =
6719 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006720 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006721 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6722 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006723 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006724
6725 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6726 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6727 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6728 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6729
6730 // Emit code to load the value if it was passed in registers.
6731 CGF.EmitBlock(InRegBlock);
6732
6733 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006734 llvm::Value *ScaledRegCount =
6735 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6736 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006737 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6738 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006739 llvm::Value *RegOffset =
6740 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006741 Address RegSaveAreaPtr =
James Y Knight751fe282019-02-09 22:22:28 +00006742 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006743 llvm::Value *RegSaveArea =
6744 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006745 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6746 "raw_reg_addr"),
6747 PaddedSize);
6748 Address RegAddr =
6749 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006750
6751 // Update the register count
6752 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6753 llvm::Value *NewRegCount =
6754 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6755 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6756 CGF.EmitBranch(ContBlock);
6757
6758 // Emit code to load the value if it was passed in memory.
6759 CGF.EmitBlock(InMemBlock);
6760
6761 // Work out the address of a stack argument.
James Y Knight751fe282019-02-09 22:22:28 +00006762 Address OverflowArgAreaPtr =
6763 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006764 Address OverflowArgArea =
6765 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6766 PaddedSize);
6767 Address RawMemAddr =
6768 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6769 Address MemAddr =
6770 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006771
6772 // Update overflow_arg_area_ptr pointer
6773 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006774 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6775 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006776 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6777 CGF.EmitBranch(ContBlock);
6778
6779 // Return the appropriate result.
6780 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006781 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6782 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006783
6784 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006785 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6786 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006787
6788 return ResAddr;
6789}
6790
Ulrich Weigand47445072013-05-06 16:26:41 +00006791ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6792 if (RetTy->isVoidType())
6793 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006794 if (isVectorArgumentType(RetTy))
6795 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006796 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006797 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006798 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6799 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006800}
6801
6802ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6803 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006804 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006805 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006806
6807 // Integers and enums are extended to full register width.
6808 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006809 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006810
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006811 // Handle vector types and vector-like structure types. Note that
6812 // as opposed to float-like structure types, we do not allow any
6813 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006814 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006815 QualType SingleElementTy = GetSingleElementType(Ty);
6816 if (isVectorArgumentType(SingleElementTy) &&
6817 getContext().getTypeSize(SingleElementTy) == Size)
6818 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6819
6820 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006821 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006822 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006823
6824 // Handle small structures.
6825 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6826 // Structures with flexible arrays have variable length, so really
6827 // fail the size test above.
6828 const RecordDecl *RD = RT->getDecl();
6829 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006830 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006831
6832 // The structure is passed as an unextended integer, a float, or a double.
6833 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006834 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006835 assert(Size == 32 || Size == 64);
6836 if (Size == 32)
6837 PassTy = llvm::Type::getFloatTy(getVMContext());
6838 else
6839 PassTy = llvm::Type::getDoubleTy(getVMContext());
6840 } else
6841 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6842 return ABIArgInfo::getDirect(PassTy);
6843 }
6844
6845 // Non-structure compounds are passed indirectly.
6846 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006847 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006848
Craig Topper8a13c412014-05-21 05:09:00 +00006849 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006850}
6851
6852//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006853// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006854//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006855
6856namespace {
6857
6858class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6859public:
Chris Lattner2b037972010-07-29 02:01:43 +00006860 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6861 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006862 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006863 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006864};
6865
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006866}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006867
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006868void MSP430TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006869 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6870 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006871 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006872 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006873 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
6874 if (!InterruptAttr)
6875 return;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006876
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006877 // Handle 'interrupt' attribute:
6878 llvm::Function *F = cast<llvm::Function>(GV);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006879
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006880 // Step 1: Set ISR calling convention.
6881 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006882
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006883 // Step 2: Add attributes goodness.
6884 F->addFnAttr(llvm::Attribute::NoInline);
6885 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006886 }
6887}
6888
Chris Lattner0cf24192010-06-28 20:05:43 +00006889//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006890// MIPS ABI Implementation. This works for both little-endian and
6891// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006892//===----------------------------------------------------------------------===//
6893
John McCall943fae92010-05-27 06:19:26 +00006894namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006895class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006896 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006897 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6898 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006899 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006900 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006901 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006902 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006903public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006904 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006905 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006906 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006907
6908 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006909 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006910 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006911 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6912 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006913 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006914};
6915
John McCall943fae92010-05-27 06:19:26 +00006916class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006917 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006918public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006919 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6920 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006921 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006922
Craig Topper4f12f102014-03-12 06:41:41 +00006923 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006924 return 29;
6925 }
6926
Eric Christopher162c91c2015-06-05 22:03:00 +00006927 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006928 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006929 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006930 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006931 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006932
6933 if (FD->hasAttr<MipsLongCallAttr>())
6934 Fn->addFnAttr("long-call");
6935 else if (FD->hasAttr<MipsShortCallAttr>())
6936 Fn->addFnAttr("short-call");
6937
6938 // Other attributes do not have a meaning for declarations.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006939 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006940 return;
6941
Reed Kotler3d5966f2013-03-13 20:40:30 +00006942 if (FD->hasAttr<Mips16Attr>()) {
6943 Fn->addFnAttr("mips16");
6944 }
6945 else if (FD->hasAttr<NoMips16Attr>()) {
6946 Fn->addFnAttr("nomips16");
6947 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006948
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006949 if (FD->hasAttr<MicroMipsAttr>())
6950 Fn->addFnAttr("micromips");
6951 else if (FD->hasAttr<NoMicroMipsAttr>())
6952 Fn->addFnAttr("nomicromips");
6953
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006954 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6955 if (!Attr)
6956 return;
6957
6958 const char *Kind;
6959 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006960 case MipsInterruptAttr::eic: Kind = "eic"; break;
6961 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6962 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6963 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6964 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6965 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6966 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6967 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6968 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6969 }
6970
6971 Fn->addFnAttr("interrupt", Kind);
6972
Reed Kotler373feca2013-01-16 17:10:28 +00006973 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006974
John McCall943fae92010-05-27 06:19:26 +00006975 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006976 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006977
Craig Topper4f12f102014-03-12 06:41:41 +00006978 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006979 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006980 }
John McCall943fae92010-05-27 06:19:26 +00006981};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006982}
John McCall943fae92010-05-27 06:19:26 +00006983
Eric Christopher7565e0d2015-05-29 23:09:49 +00006984void MipsABIInfo::CoerceToIntArgs(
6985 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006986 llvm::IntegerType *IntTy =
6987 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006988
6989 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6990 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6991 ArgList.push_back(IntTy);
6992
6993 // If necessary, add one more integer type to ArgList.
6994 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6995
6996 if (R)
6997 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006998}
6999
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007000// In N32/64, an aligned double precision floating point field is passed in
7001// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007002llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007003 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7004
7005 if (IsO32) {
7006 CoerceToIntArgs(TySize, ArgList);
7007 return llvm::StructType::get(getVMContext(), ArgList);
7008 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007009
Akira Hatanaka02e13e52012-01-12 00:52:17 +00007010 if (Ty->isComplexType())
7011 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00007012
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00007013 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007014
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007015 // Unions/vectors are passed in integer registers.
7016 if (!RT || !RT->isStructureOrClassType()) {
7017 CoerceToIntArgs(TySize, ArgList);
7018 return llvm::StructType::get(getVMContext(), ArgList);
7019 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007020
7021 const RecordDecl *RD = RT->getDecl();
7022 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007023 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00007024
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007025 uint64_t LastOffset = 0;
7026 unsigned idx = 0;
7027 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7028
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00007029 // Iterate over fields in the struct/class and check if there are any aligned
7030 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007031 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7032 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007033 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007034 const BuiltinType *BT = Ty->getAs<BuiltinType>();
7035
7036 if (!BT || BT->getKind() != BuiltinType::Double)
7037 continue;
7038
7039 uint64_t Offset = Layout.getFieldOffset(idx);
7040 if (Offset % 64) // Ignore doubles that are not aligned.
7041 continue;
7042
7043 // Add ((Offset - LastOffset) / 64) args of type i64.
7044 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7045 ArgList.push_back(I64);
7046
7047 // Add double type.
7048 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7049 LastOffset = Offset + 64;
7050 }
7051
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007052 CoerceToIntArgs(TySize - LastOffset, IntArgList);
7053 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00007054
7055 return llvm::StructType::get(getVMContext(), ArgList);
7056}
7057
Akira Hatanakaddd66342013-10-29 18:41:15 +00007058llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7059 uint64_t Offset) const {
7060 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00007061 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00007062
Akira Hatanakaddd66342013-10-29 18:41:15 +00007063 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007064}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00007065
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007066ABIArgInfo
7067MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00007068 Ty = useFirstFieldIfTransparentUnion(Ty);
7069
Akira Hatanaka1632af62012-01-09 19:31:25 +00007070 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007071 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007072 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007073
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007074 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7075 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007076 unsigned CurrOffset = llvm::alignTo(Offset, Align);
7077 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00007078
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007079 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00007080 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007081 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007082 return ABIArgInfo::getIgnore();
7083
Mark Lacey3825e832013-10-06 01:33:34 +00007084 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007085 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00007086 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007087 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00007088
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007089 // If we have reached here, aggregates are passed directly by coercing to
7090 // another structure type. Padding is inserted if the offset of the
7091 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00007092 ABIArgInfo ArgInfo =
7093 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7094 getPaddingType(OrigOffset, CurrOffset));
7095 ArgInfo.setInReg(true);
7096 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007097 }
7098
7099 // Treat an enum type as its underlying type.
7100 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7101 Ty = EnumTy->getDecl()->getIntegerType();
7102
Daniel Sanders5b445b32014-10-24 14:42:42 +00007103 // All integral types are promoted to the GPR width.
7104 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007105 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007106
Akira Hatanakaddd66342013-10-29 18:41:15 +00007107 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00007108 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00007109}
7110
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007111llvm::Type*
7112MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00007113 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007114 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007115
Akira Hatanakab6f74432012-02-09 18:49:26 +00007116 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007117 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00007118 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7119 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007120
Akira Hatanakab6f74432012-02-09 18:49:26 +00007121 // N32/64 returns struct/classes in floating point registers if the
7122 // following conditions are met:
7123 // 1. The size of the struct/class is no larger than 128-bit.
7124 // 2. The struct/class has one or two fields all of which are floating
7125 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007126 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00007127 //
7128 // Any other composite results are returned in integer registers.
7129 //
7130 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7131 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7132 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007133 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007134
Akira Hatanakab6f74432012-02-09 18:49:26 +00007135 if (!BT || !BT->isFloatingPoint())
7136 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007137
David Blaikie2d7c57e2012-04-30 02:36:29 +00007138 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00007139 }
7140
7141 if (b == e)
7142 return llvm::StructType::get(getVMContext(), RTList,
7143 RD->hasAttr<PackedAttr>());
7144
7145 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007146 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007147 }
7148
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007149 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007150 return llvm::StructType::get(getVMContext(), RTList);
7151}
7152
Akira Hatanakab579fe52011-06-02 00:09:17 +00007153ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00007154 uint64_t Size = getContext().getTypeSize(RetTy);
7155
Daniel Sandersed39f582014-09-04 13:28:14 +00007156 if (RetTy->isVoidType())
7157 return ABIArgInfo::getIgnore();
7158
7159 // O32 doesn't treat zero-sized structs differently from other structs.
7160 // However, N32/N64 ignores zero sized return values.
7161 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007162 return ABIArgInfo::getIgnore();
7163
Akira Hatanakac37eddf2012-05-11 21:01:17 +00007164 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007165 if (Size <= 128) {
7166 if (RetTy->isAnyComplexType())
7167 return ABIArgInfo::getDirect();
7168
Daniel Sanderse5018b62014-09-04 15:05:39 +00007169 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00007170 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00007171 if (!IsO32 ||
7172 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7173 ABIArgInfo ArgInfo =
7174 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7175 ArgInfo.setInReg(true);
7176 return ArgInfo;
7177 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007178 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00007179
John McCall7f416cc2015-09-08 08:05:57 +00007180 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007181 }
7182
7183 // Treat an enum type as its underlying type.
7184 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7185 RetTy = EnumTy->getDecl()->getIntegerType();
7186
Stefan Maksimovicb9da8a52018-07-30 10:44:46 +00007187 if (RetTy->isPromotableIntegerType())
7188 return ABIArgInfo::getExtend(RetTy);
7189
7190 if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7191 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7192 return ABIArgInfo::getSignExtend(RetTy);
7193
7194 return ABIArgInfo::getDirect();
Akira Hatanakab579fe52011-06-02 00:09:17 +00007195}
7196
7197void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00007198 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00007199 if (!getCXXABI().classifyReturnType(FI))
7200 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00007201
Eric Christopher7565e0d2015-05-29 23:09:49 +00007202 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007203 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00007204
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007205 for (auto &I : FI.arguments())
7206 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007207}
7208
John McCall7f416cc2015-09-08 08:05:57 +00007209Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7210 QualType OrigTy) const {
7211 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00007212
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007213 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7214 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00007215 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007216 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00007217 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007218 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007219 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007220 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007221 DidPromote = true;
7222 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7223 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007224 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007225
John McCall7f416cc2015-09-08 08:05:57 +00007226 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007227
John McCall7f416cc2015-09-08 08:05:57 +00007228 // The alignment of things in the argument area is never larger than
7229 // StackAlignInBytes.
7230 TyInfo.second =
7231 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7232
7233 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7234 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7235
7236 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7237 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7238
7239
7240 // If there was a promotion, "unpromote" into a temporary.
7241 // TODO: can we just use a pointer into a subset of the original slot?
7242 if (DidPromote) {
7243 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7244 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7245
7246 // Truncate down to the right width.
7247 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7248 : CGF.IntPtrTy);
7249 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7250 if (OrigTy->isPointerType())
7251 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7252
7253 CGF.Builder.CreateStore(V, Temp);
7254 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007255 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007256
John McCall7f416cc2015-09-08 08:05:57 +00007257 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007258}
7259
Alex Bradburye41a5e22018-01-12 20:08:16 +00007260ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007261 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007262
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007263 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7264 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007265 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007266
Alex Bradburye41a5e22018-01-12 20:08:16 +00007267 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007268}
7269
John McCall943fae92010-05-27 06:19:26 +00007270bool
7271MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7272 llvm::Value *Address) const {
7273 // This information comes from gcc's implementation, which seems to
7274 // as canonical as it gets.
7275
John McCall943fae92010-05-27 06:19:26 +00007276 // Everything on MIPS is 4 bytes. Double-precision FP registers
7277 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007278 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007279
7280 // 0-31 are the general purpose registers, $0 - $31.
7281 // 32-63 are the floating-point registers, $f0 - $f31.
7282 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7283 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007284 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007285
7286 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7287 // They are one bit wide and ignored here.
7288
7289 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7290 // (coprocessor 1 is the FP unit)
7291 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7292 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7293 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007294 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007295 return false;
7296}
7297
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007298//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007299// AVR ABI Implementation.
7300//===----------------------------------------------------------------------===//
7301
7302namespace {
7303class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7304public:
7305 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7306 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7307
7308 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007309 CodeGen::CodeGenModule &CGM) const override {
7310 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007311 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007312 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7313 if (!FD) return;
7314 auto *Fn = cast<llvm::Function>(GV);
7315
7316 if (FD->getAttr<AVRInterruptAttr>())
7317 Fn->addFnAttr("interrupt");
7318
7319 if (FD->getAttr<AVRSignalAttr>())
7320 Fn->addFnAttr("signal");
7321 }
7322};
7323}
7324
7325//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007326// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007327// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007328// handling.
7329//===----------------------------------------------------------------------===//
7330
7331namespace {
7332
7333class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7334public:
7335 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7336 : DefaultTargetCodeGenInfo(CGT) {}
7337
Eric Christopher162c91c2015-06-05 22:03:00 +00007338 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007339 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007340};
7341
Eric Christopher162c91c2015-06-05 22:03:00 +00007342void TCETargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007343 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7344 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007345 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007346 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007347 if (!FD) return;
7348
7349 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007350
David Blaikiebbafb8a2012-03-11 07:00:24 +00007351 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007352 if (FD->hasAttr<OpenCLKernelAttr>()) {
7353 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007354 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007355 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7356 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007357 // Convert the reqd_work_group_size() attributes to metadata.
7358 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007359 llvm::NamedMDNode *OpenCLMetadata =
7360 M.getModule().getOrInsertNamedMetadata(
7361 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007362
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007363 SmallVector<llvm::Metadata *, 5> Operands;
7364 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007365
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007366 Operands.push_back(
7367 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7368 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7369 Operands.push_back(
7370 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7371 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7372 Operands.push_back(
7373 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7374 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007375
Eric Christopher7565e0d2015-05-29 23:09:49 +00007376 // Add a boolean constant operand for "required" (true) or "hint"
7377 // (false) for implementing the work_group_size_hint attr later.
7378 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007379 Operands.push_back(
7380 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007381 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7382 }
7383 }
7384 }
7385}
7386
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007387}
John McCall943fae92010-05-27 06:19:26 +00007388
Tony Linthicum76329bf2011-12-12 21:14:55 +00007389//===----------------------------------------------------------------------===//
7390// Hexagon ABI Implementation
7391//===----------------------------------------------------------------------===//
7392
7393namespace {
7394
7395class HexagonABIInfo : public ABIInfo {
7396
7397
7398public:
7399 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7400
7401private:
7402
7403 ABIArgInfo classifyReturnType(QualType RetTy) const;
7404 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7405
Craig Topper4f12f102014-03-12 06:41:41 +00007406 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007407
John McCall7f416cc2015-09-08 08:05:57 +00007408 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7409 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007410};
7411
7412class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7413public:
7414 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7415 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7416
Craig Topper4f12f102014-03-12 06:41:41 +00007417 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007418 return 29;
7419 }
7420};
7421
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007422}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007423
7424void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007425 if (!getCXXABI().classifyReturnType(FI))
7426 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007427 for (auto &I : FI.arguments())
7428 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007429}
7430
7431ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7432 if (!isAggregateTypeForABI(Ty)) {
7433 // Treat an enum type as its underlying type.
7434 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7435 Ty = EnumTy->getDecl()->getIntegerType();
7436
Alex Bradburye41a5e22018-01-12 20:08:16 +00007437 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7438 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007439 }
7440
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007441 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7442 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7443
Tony Linthicum76329bf2011-12-12 21:14:55 +00007444 // Ignore empty records.
7445 if (isEmptyRecord(getContext(), Ty, true))
7446 return ABIArgInfo::getIgnore();
7447
Tony Linthicum76329bf2011-12-12 21:14:55 +00007448 uint64_t Size = getContext().getTypeSize(Ty);
7449 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007450 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007451 // Pass in the smallest viable integer type.
7452 else if (Size > 32)
7453 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7454 else if (Size > 16)
7455 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7456 else if (Size > 8)
7457 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7458 else
7459 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7460}
7461
7462ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7463 if (RetTy->isVoidType())
7464 return ABIArgInfo::getIgnore();
7465
7466 // Large vector types should be returned via memory.
7467 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007468 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007469
7470 if (!isAggregateTypeForABI(RetTy)) {
7471 // Treat an enum type as its underlying type.
7472 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7473 RetTy = EnumTy->getDecl()->getIntegerType();
7474
Alex Bradburye41a5e22018-01-12 20:08:16 +00007475 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7476 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007477 }
7478
Tony Linthicum76329bf2011-12-12 21:14:55 +00007479 if (isEmptyRecord(getContext(), RetTy, true))
7480 return ABIArgInfo::getIgnore();
7481
7482 // Aggregates <= 8 bytes are returned in r0; other aggregates
7483 // are returned indirectly.
7484 uint64_t Size = getContext().getTypeSize(RetTy);
7485 if (Size <= 64) {
7486 // Return in the smallest viable integer type.
7487 if (Size <= 8)
7488 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7489 if (Size <= 16)
7490 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7491 if (Size <= 32)
7492 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7493 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7494 }
7495
John McCall7f416cc2015-09-08 08:05:57 +00007496 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007497}
7498
John McCall7f416cc2015-09-08 08:05:57 +00007499Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7500 QualType Ty) const {
7501 // FIXME: Someone needs to audit that this handle alignment correctly.
7502 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7503 getContext().getTypeInfoInChars(Ty),
7504 CharUnits::fromQuantity(4),
7505 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007506}
7507
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007508//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007509// Lanai ABI Implementation
7510//===----------------------------------------------------------------------===//
7511
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007512namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007513class LanaiABIInfo : public DefaultABIInfo {
7514public:
7515 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7516
7517 bool shouldUseInReg(QualType Ty, CCState &State) const;
7518
7519 void computeInfo(CGFunctionInfo &FI) const override {
7520 CCState State(FI.getCallingConvention());
7521 // Lanai uses 4 registers to pass arguments unless the function has the
7522 // regparm attribute set.
7523 if (FI.getHasRegParm()) {
7524 State.FreeRegs = FI.getRegParm();
7525 } else {
7526 State.FreeRegs = 4;
7527 }
7528
7529 if (!getCXXABI().classifyReturnType(FI))
7530 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7531 for (auto &I : FI.arguments())
7532 I.info = classifyArgumentType(I.type, State);
7533 }
7534
Jacques Pienaare74d9132016-04-26 00:09:29 +00007535 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007536 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7537};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007538} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007539
7540bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7541 unsigned Size = getContext().getTypeSize(Ty);
7542 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7543
7544 if (SizeInRegs == 0)
7545 return false;
7546
7547 if (SizeInRegs > State.FreeRegs) {
7548 State.FreeRegs = 0;
7549 return false;
7550 }
7551
7552 State.FreeRegs -= SizeInRegs;
7553
7554 return true;
7555}
7556
Jacques Pienaare74d9132016-04-26 00:09:29 +00007557ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7558 CCState &State) const {
7559 if (!ByVal) {
7560 if (State.FreeRegs) {
7561 --State.FreeRegs; // Non-byval indirects just use one pointer.
7562 return getNaturalAlignIndirectInReg(Ty);
7563 }
7564 return getNaturalAlignIndirect(Ty, false);
7565 }
7566
7567 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007568 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007569 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7570 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7571 /*Realign=*/TypeAlign >
7572 MinABIStackAlignInBytes);
7573}
7574
Jacques Pienaard964cc22016-03-28 21:02:54 +00007575ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7576 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007577 // Check with the C++ ABI first.
7578 const RecordType *RT = Ty->getAs<RecordType>();
7579 if (RT) {
7580 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7581 if (RAA == CGCXXABI::RAA_Indirect) {
7582 return getIndirectResult(Ty, /*ByVal=*/false, State);
7583 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7584 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7585 }
7586 }
7587
7588 if (isAggregateTypeForABI(Ty)) {
7589 // Structures with flexible arrays are always indirect.
7590 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7591 return getIndirectResult(Ty, /*ByVal=*/true, State);
7592
7593 // Ignore empty structs/unions.
7594 if (isEmptyRecord(getContext(), Ty, true))
7595 return ABIArgInfo::getIgnore();
7596
7597 llvm::LLVMContext &LLVMContext = getVMContext();
7598 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7599 if (SizeInRegs <= State.FreeRegs) {
7600 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7601 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7602 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7603 State.FreeRegs -= SizeInRegs;
7604 return ABIArgInfo::getDirectInReg(Result);
7605 } else {
7606 State.FreeRegs = 0;
7607 }
7608 return getIndirectResult(Ty, true, State);
7609 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007610
7611 // Treat an enum type as its underlying type.
7612 if (const auto *EnumTy = Ty->getAs<EnumType>())
7613 Ty = EnumTy->getDecl()->getIntegerType();
7614
Jacques Pienaare74d9132016-04-26 00:09:29 +00007615 bool InReg = shouldUseInReg(Ty, State);
7616 if (Ty->isPromotableIntegerType()) {
7617 if (InReg)
7618 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007619 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007620 }
7621 if (InReg)
7622 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007623 return ABIArgInfo::getDirect();
7624}
7625
7626namespace {
7627class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7628public:
7629 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7630 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7631};
7632}
7633
7634//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007635// AMDGPU ABI Implementation
7636//===----------------------------------------------------------------------===//
7637
7638namespace {
7639
Matt Arsenault88d7da02016-08-22 19:25:59 +00007640class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007641private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007642 static const unsigned MaxNumRegsForArgsRet = 16;
7643
Matt Arsenault3fe73952017-08-09 21:44:58 +00007644 unsigned numRegsForType(QualType Ty) const;
7645
7646 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7647 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7648 uint64_t Members) const override;
7649
7650public:
7651 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7652 DefaultABIInfo(CGT) {}
7653
7654 ABIArgInfo classifyReturnType(QualType RetTy) const;
7655 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7656 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007657
7658 void computeInfo(CGFunctionInfo &FI) const override;
7659};
7660
Matt Arsenault3fe73952017-08-09 21:44:58 +00007661bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7662 return true;
7663}
7664
7665bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7666 const Type *Base, uint64_t Members) const {
7667 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7668
7669 // Homogeneous Aggregates may occupy at most 16 registers.
7670 return Members * NumRegs <= MaxNumRegsForArgsRet;
7671}
7672
Matt Arsenault3fe73952017-08-09 21:44:58 +00007673/// Estimate number of registers the type will use when passed in registers.
7674unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7675 unsigned NumRegs = 0;
7676
7677 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7678 // Compute from the number of elements. The reported size is based on the
7679 // in-memory size, which includes the padding 4th element for 3-vectors.
7680 QualType EltTy = VT->getElementType();
7681 unsigned EltSize = getContext().getTypeSize(EltTy);
7682
7683 // 16-bit element vectors should be passed as packed.
7684 if (EltSize == 16)
7685 return (VT->getNumElements() + 1) / 2;
7686
7687 unsigned EltNumRegs = (EltSize + 31) / 32;
7688 return EltNumRegs * VT->getNumElements();
7689 }
7690
7691 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7692 const RecordDecl *RD = RT->getDecl();
7693 assert(!RD->hasFlexibleArrayMember());
7694
7695 for (const FieldDecl *Field : RD->fields()) {
7696 QualType FieldTy = Field->getType();
7697 NumRegs += numRegsForType(FieldTy);
7698 }
7699
7700 return NumRegs;
7701 }
7702
7703 return (getContext().getTypeSize(Ty) + 31) / 32;
7704}
7705
Matt Arsenault88d7da02016-08-22 19:25:59 +00007706void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007707 llvm::CallingConv::ID CC = FI.getCallingConvention();
7708
Matt Arsenault88d7da02016-08-22 19:25:59 +00007709 if (!getCXXABI().classifyReturnType(FI))
7710 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7711
Matt Arsenault3fe73952017-08-09 21:44:58 +00007712 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7713 for (auto &Arg : FI.arguments()) {
7714 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7715 Arg.info = classifyKernelArgumentType(Arg.type);
7716 } else {
7717 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7718 }
7719 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007720}
7721
Matt Arsenault3fe73952017-08-09 21:44:58 +00007722ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7723 if (isAggregateTypeForABI(RetTy)) {
7724 // Records with non-trivial destructors/copy-constructors should not be
7725 // returned by value.
7726 if (!getRecordArgABI(RetTy, getCXXABI())) {
7727 // Ignore empty structs/unions.
7728 if (isEmptyRecord(getContext(), RetTy, true))
7729 return ABIArgInfo::getIgnore();
7730
7731 // Lower single-element structs to just return a regular value.
7732 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7733 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7734
7735 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7736 const RecordDecl *RD = RT->getDecl();
7737 if (RD->hasFlexibleArrayMember())
7738 return DefaultABIInfo::classifyReturnType(RetTy);
7739 }
7740
7741 // Pack aggregates <= 4 bytes into single VGPR or pair.
7742 uint64_t Size = getContext().getTypeSize(RetTy);
7743 if (Size <= 16)
7744 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7745
7746 if (Size <= 32)
7747 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7748
7749 if (Size <= 64) {
7750 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7751 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7752 }
7753
7754 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7755 return ABIArgInfo::getDirect();
7756 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007757 }
7758
Matt Arsenault3fe73952017-08-09 21:44:58 +00007759 // Otherwise just do the default thing.
7760 return DefaultABIInfo::classifyReturnType(RetTy);
7761}
7762
7763/// For kernels all parameters are really passed in a special buffer. It doesn't
7764/// make sense to pass anything byval, so everything must be direct.
7765ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7766 Ty = useFirstFieldIfTransparentUnion(Ty);
7767
7768 // TODO: Can we omit empty structs?
7769
Matt Arsenault88d7da02016-08-22 19:25:59 +00007770 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007771 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7772 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007773
7774 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7775 // individual elements, which confuses the Clover OpenCL backend; therefore we
7776 // have to set it to false here. Other args of getDirect() are just defaults.
7777 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7778}
7779
Matt Arsenault3fe73952017-08-09 21:44:58 +00007780ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7781 unsigned &NumRegsLeft) const {
7782 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7783
7784 Ty = useFirstFieldIfTransparentUnion(Ty);
7785
7786 if (isAggregateTypeForABI(Ty)) {
7787 // Records with non-trivial destructors/copy-constructors should not be
7788 // passed by value.
7789 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7790 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7791
7792 // Ignore empty structs/unions.
7793 if (isEmptyRecord(getContext(), Ty, true))
7794 return ABIArgInfo::getIgnore();
7795
7796 // Lower single-element structs to just pass a regular value. TODO: We
7797 // could do reasonable-size multiple-element structs too, using getExpand(),
7798 // though watch out for things like bitfields.
7799 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7800 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7801
7802 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7803 const RecordDecl *RD = RT->getDecl();
7804 if (RD->hasFlexibleArrayMember())
7805 return DefaultABIInfo::classifyArgumentType(Ty);
7806 }
7807
7808 // Pack aggregates <= 8 bytes into single VGPR or pair.
7809 uint64_t Size = getContext().getTypeSize(Ty);
7810 if (Size <= 64) {
7811 unsigned NumRegs = (Size + 31) / 32;
7812 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7813
7814 if (Size <= 16)
7815 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7816
7817 if (Size <= 32)
7818 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7819
7820 // XXX: Should this be i64 instead, and should the limit increase?
7821 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7822 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7823 }
7824
7825 if (NumRegsLeft > 0) {
7826 unsigned NumRegs = numRegsForType(Ty);
7827 if (NumRegsLeft >= NumRegs) {
7828 NumRegsLeft -= NumRegs;
7829 return ABIArgInfo::getDirect();
7830 }
7831 }
7832 }
7833
7834 // Otherwise just do the default thing.
7835 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7836 if (!ArgInfo.isIndirect()) {
7837 unsigned NumRegs = numRegsForType(Ty);
7838 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7839 }
7840
7841 return ArgInfo;
7842}
7843
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007844class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7845public:
7846 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007847 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007848 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007849 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007850 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007851
Yaxun Liu402804b2016-12-15 08:09:08 +00007852 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7853 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007854
Alexander Richardson6d989432017-10-15 18:48:14 +00007855 LangAS getASTAllocaAddressSpace() const override {
7856 return getLangASFromTargetAS(
7857 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007858 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007859 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7860 const VarDecl *D) const override;
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00007861 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
7862 SyncScope Scope,
7863 llvm::AtomicOrdering Ordering,
7864 llvm::LLVMContext &Ctx) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007865 llvm::Function *
7866 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7867 llvm::Function *BlockInvokeFunc,
7868 llvm::Value *BlockLiteral) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00007869 bool shouldEmitStaticExternCAliases() const override;
Yaxun Liu6c10a662018-06-12 00:16:33 +00007870 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007871};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007872}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007873
Scott Linder80a1ee42019-02-12 18:30:38 +00007874static bool requiresAMDGPUProtectedVisibility(const Decl *D,
7875 llvm::GlobalValue *GV) {
7876 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
7877 return false;
7878
7879 return D->hasAttr<OpenCLKernelAttr>() ||
7880 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
Michael Liao38205062019-04-26 19:31:48 +00007881 (isa<VarDecl>(D) &&
Yaxun Liuc3dfe902019-06-26 03:47:37 +00007882 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
7883 D->hasAttr<HIPPinnedShadowAttr>()));
7884}
7885
7886static bool requiresAMDGPUDefaultVisibility(const Decl *D,
7887 llvm::GlobalValue *GV) {
7888 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
7889 return false;
7890
7891 return isa<VarDecl>(D) && D->hasAttr<HIPPinnedShadowAttr>();
Scott Linder80a1ee42019-02-12 18:30:38 +00007892}
7893
Eric Christopher162c91c2015-06-05 22:03:00 +00007894void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007895 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Yaxun Liuc3dfe902019-06-26 03:47:37 +00007896 if (requiresAMDGPUDefaultVisibility(D, GV)) {
7897 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
7898 GV->setDSOLocal(false);
7899 } else if (requiresAMDGPUProtectedVisibility(D, GV)) {
Scott Linder80a1ee42019-02-12 18:30:38 +00007900 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
7901 GV->setDSOLocal(true);
7902 }
7903
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007904 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007905 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007906 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007907 if (!FD)
7908 return;
7909
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007910 llvm::Function *F = cast<llvm::Function>(GV);
7911
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007912 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7913 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
Tony Tye1a3f3a22018-03-23 18:43:15 +00007914
Matt Arsenaulteac783a2019-08-27 19:25:40 +00007915
7916 const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
7917 FD->hasAttr<OpenCLKernelAttr>();
7918 if ((IsOpenCLKernel ||
7919 (M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>())) &&
Tony Tye1a3f3a22018-03-23 18:43:15 +00007920 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
Christudasan Devadasan18ba9d62019-07-10 15:10:08 +00007921 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
Tony Tye1a3f3a22018-03-23 18:43:15 +00007922
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007923 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7924 if (ReqdWGS || FlatWGS) {
Michael Liao7557afa2019-02-26 18:49:36 +00007925 unsigned Min = 0;
7926 unsigned Max = 0;
7927 if (FlatWGS) {
7928 Min = FlatWGS->getMin()
7929 ->EvaluateKnownConstInt(M.getContext())
7930 .getExtValue();
7931 Max = FlatWGS->getMax()
7932 ->EvaluateKnownConstInt(M.getContext())
7933 .getExtValue();
7934 }
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007935 if (ReqdWGS && Min == 0 && Max == 0)
7936 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007937
7938 if (Min != 0) {
7939 assert(Min <= Max && "Min must be less than or equal Max");
7940
7941 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7942 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7943 } else
7944 assert(Max == 0 && "Max must be zero");
Matt Arsenaulteac783a2019-08-27 19:25:40 +00007945 } else if (IsOpenCLKernel) {
7946 // By default, restrict the maximum size to 256.
7947 F->addFnAttr("amdgpu-flat-work-group-size", "1,256");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007948 }
7949
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007950 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
Michael Liao7557afa2019-02-26 18:49:36 +00007951 unsigned Min =
7952 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
7953 unsigned Max = Attr->getMax() ? Attr->getMax()
7954 ->EvaluateKnownConstInt(M.getContext())
7955 .getExtValue()
7956 : 0;
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007957
7958 if (Min != 0) {
7959 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7960
7961 std::string AttrVal = llvm::utostr(Min);
7962 if (Max != 0)
7963 AttrVal = AttrVal + "," + llvm::utostr(Max);
7964 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7965 } else
7966 assert(Max == 0 && "Max must be zero");
7967 }
7968
7969 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007970 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007971
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007972 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007973 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7974 }
7975
7976 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7977 uint32_t NumVGPR = Attr->getNumVGPR();
7978
7979 if (NumVGPR != 0)
7980 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007981 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007982}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007983
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007984unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7985 return llvm::CallingConv::AMDGPU_KERNEL;
7986}
7987
Yaxun Liu402804b2016-12-15 08:09:08 +00007988// Currently LLVM assumes null pointers always have value 0,
7989// which results in incorrectly transformed IR. Therefore, instead of
7990// emitting null pointers in private and local address spaces, a null
7991// pointer in generic address space is emitted which is casted to a
7992// pointer in local or private address space.
7993llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7994 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7995 QualType QT) const {
7996 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7997 return llvm::ConstantPointerNull::get(PT);
7998
7999 auto &Ctx = CGM.getContext();
8000 auto NPT = llvm::PointerType::get(PT->getElementType(),
8001 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
8002 return llvm::ConstantExpr::getAddrSpaceCast(
8003 llvm::ConstantPointerNull::get(NPT), PT);
8004}
8005
Alexander Richardson6d989432017-10-15 18:48:14 +00008006LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00008007AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
8008 const VarDecl *D) const {
8009 assert(!CGM.getLangOpts().OpenCL &&
8010 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
8011 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00008012 LangAS DefaultGlobalAS = getLangASFromTargetAS(
8013 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00008014 if (!D)
8015 return DefaultGlobalAS;
8016
Alexander Richardson6d989432017-10-15 18:48:14 +00008017 LangAS AddrSpace = D->getType().getAddressSpace();
8018 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00008019 if (AddrSpace != LangAS::Default)
8020 return AddrSpace;
8021
8022 if (CGM.isTypeConstant(D->getType(), false)) {
8023 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
8024 return ConstAS.getValue();
8025 }
8026 return DefaultGlobalAS;
8027}
8028
Yaxun Liu39195062017-08-04 18:16:31 +00008029llvm::SyncScope::ID
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00008030AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
8031 SyncScope Scope,
8032 llvm::AtomicOrdering Ordering,
8033 llvm::LLVMContext &Ctx) const {
8034 std::string Name;
8035 switch (Scope) {
Yaxun Liu39195062017-08-04 18:16:31 +00008036 case SyncScope::OpenCLWorkGroup:
8037 Name = "workgroup";
8038 break;
8039 case SyncScope::OpenCLDevice:
8040 Name = "agent";
8041 break;
8042 case SyncScope::OpenCLAllSVMDevices:
8043 Name = "";
8044 break;
8045 case SyncScope::OpenCLSubGroup:
Konstantin Zhuravlyov3161c892019-03-06 20:54:48 +00008046 Name = "wavefront";
Yaxun Liu39195062017-08-04 18:16:31 +00008047 }
Konstantin Zhuravlyovec28a1d2019-03-25 20:54:00 +00008048
8049 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
8050 if (!Name.empty())
8051 Name = Twine(Twine(Name) + Twine("-")).str();
8052
8053 Name = Twine(Twine(Name) + Twine("one-as")).str();
8054 }
8055
8056 return Ctx.getOrInsertSyncScopeID(Name);
Yaxun Liu39195062017-08-04 18:16:31 +00008057}
8058
Yaxun Liub0eee292018-03-29 14:50:00 +00008059bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
8060 return false;
8061}
8062
Yaxun Liu4306f202018-04-20 17:01:03 +00008063void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
Yaxun Liu6c10a662018-06-12 00:16:33 +00008064 const FunctionType *&FT) const {
8065 FT = getABIInfo().getContext().adjustFunctionType(
8066 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
Yaxun Liu4306f202018-04-20 17:01:03 +00008067}
8068
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008069//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008070// SPARC v8 ABI Implementation.
8071// Based on the SPARC Compliance Definition version 2.4.1.
8072//
8073// Ensures that complex values are passed in registers.
8074//
8075namespace {
8076class SparcV8ABIInfo : public DefaultABIInfo {
8077public:
8078 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8079
8080private:
8081 ABIArgInfo classifyReturnType(QualType RetTy) const;
8082 void computeInfo(CGFunctionInfo &FI) const override;
8083};
8084} // end anonymous namespace
8085
8086
8087ABIArgInfo
8088SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
8089 if (Ty->isAnyComplexType()) {
8090 return ABIArgInfo::getDirect();
8091 }
8092 else {
8093 return DefaultABIInfo::classifyReturnType(Ty);
8094 }
8095}
8096
8097void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8098
8099 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8100 for (auto &Arg : FI.arguments())
8101 Arg.info = classifyArgumentType(Arg.type);
8102}
8103
8104namespace {
8105class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
8106public:
8107 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
8108 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
8109};
8110} // end anonymous namespace
8111
8112//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008113// SPARC v9 ABI Implementation.
8114// Based on the SPARC Compliance Definition version 2.4.1.
8115//
8116// Function arguments a mapped to a nominal "parameter array" and promoted to
8117// registers depending on their type. Each argument occupies 8 or 16 bytes in
8118// the array, structs larger than 16 bytes are passed indirectly.
8119//
8120// One case requires special care:
8121//
8122// struct mixed {
8123// int i;
8124// float f;
8125// };
8126//
8127// When a struct mixed is passed by value, it only occupies 8 bytes in the
8128// parameter array, but the int is passed in an integer register, and the float
8129// is passed in a floating point register. This is represented as two arguments
8130// with the LLVM IR inreg attribute:
8131//
8132// declare void f(i32 inreg %i, float inreg %f)
8133//
8134// The code generator will only allocate 4 bytes from the parameter array for
8135// the inreg arguments. All other arguments are allocated a multiple of 8
8136// bytes.
8137//
8138namespace {
8139class SparcV9ABIInfo : public ABIInfo {
8140public:
8141 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
8142
8143private:
8144 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00008145 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00008146 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8147 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008148
8149 // Coercion type builder for structs passed in registers. The coercion type
8150 // serves two purposes:
8151 //
8152 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8153 // in registers.
8154 // 2. Expose aligned floating point elements as first-level elements, so the
8155 // code generator knows to pass them in floating point registers.
8156 //
8157 // We also compute the InReg flag which indicates that the struct contains
8158 // aligned 32-bit floats.
8159 //
8160 struct CoerceBuilder {
8161 llvm::LLVMContext &Context;
8162 const llvm::DataLayout &DL;
8163 SmallVector<llvm::Type*, 8> Elems;
8164 uint64_t Size;
8165 bool InReg;
8166
8167 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8168 : Context(c), DL(dl), Size(0), InReg(false) {}
8169
8170 // Pad Elems with integers until Size is ToSize.
8171 void pad(uint64_t ToSize) {
8172 assert(ToSize >= Size && "Cannot remove elements");
8173 if (ToSize == Size)
8174 return;
8175
8176 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008177 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008178 if (Aligned > Size && Aligned <= ToSize) {
8179 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8180 Size = Aligned;
8181 }
8182
8183 // Add whole 64-bit words.
8184 while (Size + 64 <= ToSize) {
8185 Elems.push_back(llvm::Type::getInt64Ty(Context));
8186 Size += 64;
8187 }
8188
8189 // Final in-word padding.
8190 if (Size < ToSize) {
8191 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8192 Size = ToSize;
8193 }
8194 }
8195
8196 // Add a floating point element at Offset.
8197 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8198 // Unaligned floats are treated as integers.
8199 if (Offset % Bits)
8200 return;
8201 // The InReg flag is only required if there are any floats < 64 bits.
8202 if (Bits < 64)
8203 InReg = true;
8204 pad(Offset);
8205 Elems.push_back(Ty);
8206 Size = Offset + Bits;
8207 }
8208
8209 // Add a struct type to the coercion type, starting at Offset (in bits).
8210 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8211 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8212 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8213 llvm::Type *ElemTy = StrTy->getElementType(i);
8214 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8215 switch (ElemTy->getTypeID()) {
8216 case llvm::Type::StructTyID:
8217 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8218 break;
8219 case llvm::Type::FloatTyID:
8220 addFloat(ElemOffset, ElemTy, 32);
8221 break;
8222 case llvm::Type::DoubleTyID:
8223 addFloat(ElemOffset, ElemTy, 64);
8224 break;
8225 case llvm::Type::FP128TyID:
8226 addFloat(ElemOffset, ElemTy, 128);
8227 break;
8228 case llvm::Type::PointerTyID:
8229 if (ElemOffset % 64 == 0) {
8230 pad(ElemOffset);
8231 Elems.push_back(ElemTy);
8232 Size += 64;
8233 }
8234 break;
8235 default:
8236 break;
8237 }
8238 }
8239 }
8240
8241 // Check if Ty is a usable substitute for the coercion type.
8242 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00008243 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008244 }
8245
8246 // Get the coercion type as a literal struct type.
8247 llvm::Type *getType() const {
8248 if (Elems.size() == 1)
8249 return Elems.front();
8250 else
8251 return llvm::StructType::get(Context, Elems);
8252 }
8253 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008254};
8255} // end anonymous namespace
8256
8257ABIArgInfo
8258SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8259 if (Ty->isVoidType())
8260 return ABIArgInfo::getIgnore();
8261
8262 uint64_t Size = getContext().getTypeSize(Ty);
8263
8264 // Anything too big to fit in registers is passed with an explicit indirect
8265 // pointer / sret pointer.
8266 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00008267 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008268
8269 // Treat an enum type as its underlying type.
8270 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8271 Ty = EnumTy->getDecl()->getIntegerType();
8272
8273 // Integer types smaller than a register are extended.
8274 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00008275 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008276
8277 // Other non-aggregates go in registers.
8278 if (!isAggregateTypeForABI(Ty))
8279 return ABIArgInfo::getDirect();
8280
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008281 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8282 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8283 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00008284 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008285
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008286 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008287 // Build a coercion type from the LLVM struct type.
8288 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8289 if (!StrTy)
8290 return ABIArgInfo::getDirect();
8291
8292 CoerceBuilder CB(getVMContext(), getDataLayout());
8293 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008294 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008295
8296 // Try to use the original type for coercion.
8297 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8298
8299 if (CB.InReg)
8300 return ABIArgInfo::getDirectInReg(CoerceTy);
8301 else
8302 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008303}
8304
John McCall7f416cc2015-09-08 08:05:57 +00008305Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8306 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008307 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8308 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8309 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8310 AI.setCoerceToType(ArgTy);
8311
John McCall7f416cc2015-09-08 08:05:57 +00008312 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008313
John McCall7f416cc2015-09-08 08:05:57 +00008314 CGBuilderTy &Builder = CGF.Builder;
8315 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8316 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8317
8318 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8319
8320 Address ArgAddr = Address::invalid();
8321 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008322 switch (AI.getKind()) {
8323 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008324 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008325 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008326 llvm_unreachable("Unsupported ABI kind for va_arg");
8327
John McCall7f416cc2015-09-08 08:05:57 +00008328 case ABIArgInfo::Extend: {
8329 Stride = SlotSize;
8330 CharUnits Offset = SlotSize - TypeInfo.first;
8331 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008332 break;
John McCall7f416cc2015-09-08 08:05:57 +00008333 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008334
John McCall7f416cc2015-09-08 08:05:57 +00008335 case ABIArgInfo::Direct: {
8336 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008337 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008338 ArgAddr = Addr;
8339 break;
John McCall7f416cc2015-09-08 08:05:57 +00008340 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008341
8342 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008343 Stride = SlotSize;
8344 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8345 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8346 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008347 break;
8348
8349 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008350 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008351 }
8352
8353 // Update VAList.
James Y Knight3d2df5a2019-02-05 19:01:33 +00008354 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
8355 Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008356
John McCall7f416cc2015-09-08 08:05:57 +00008357 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008358}
8359
8360void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8361 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008362 for (auto &I : FI.arguments())
8363 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008364}
8365
8366namespace {
8367class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8368public:
8369 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8370 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008371
Craig Topper4f12f102014-03-12 06:41:41 +00008372 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008373 return 14;
8374 }
8375
8376 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008377 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008378};
8379} // end anonymous namespace
8380
Roman Divackyf02c9942014-02-24 18:46:27 +00008381bool
8382SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8383 llvm::Value *Address) const {
8384 // This is calculated from the LLVM and GCC tables and verified
8385 // against gcc output. AFAIK all ABIs use the same encoding.
8386
8387 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8388
8389 llvm::IntegerType *i8 = CGF.Int8Ty;
8390 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8391 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8392
8393 // 0-31: the 8-byte general-purpose registers
8394 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8395
8396 // 32-63: f0-31, the 4-byte floating-point registers
8397 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8398
8399 // Y = 64
8400 // PSR = 65
8401 // WIM = 66
8402 // TBR = 67
8403 // PC = 68
8404 // NPC = 69
8405 // FSR = 70
8406 // CSR = 71
8407 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008408
Roman Divackyf02c9942014-02-24 18:46:27 +00008409 // 72-87: d0-15, the 8-byte floating-point registers
8410 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8411
8412 return false;
8413}
8414
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008415// ARC ABI implementation.
8416namespace {
8417
8418class ARCABIInfo : public DefaultABIInfo {
8419public:
8420 using DefaultABIInfo::DefaultABIInfo;
8421
8422private:
8423 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8424 QualType Ty) const override;
8425
8426 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
8427 if (!State.FreeRegs)
8428 return;
8429 if (Info.isIndirect() && Info.getInReg())
8430 State.FreeRegs--;
8431 else if (Info.isDirect() && Info.getInReg()) {
8432 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
8433 if (sz < State.FreeRegs)
8434 State.FreeRegs -= sz;
8435 else
8436 State.FreeRegs = 0;
8437 }
8438 }
8439
8440 void computeInfo(CGFunctionInfo &FI) const override {
8441 CCState State(FI.getCallingConvention());
8442 // ARC uses 8 registers to pass arguments.
8443 State.FreeRegs = 8;
8444
8445 if (!getCXXABI().classifyReturnType(FI))
8446 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8447 updateState(FI.getReturnInfo(), FI.getReturnType(), State);
8448 for (auto &I : FI.arguments()) {
8449 I.info = classifyArgumentType(I.type, State.FreeRegs);
8450 updateState(I.info, I.type, State);
8451 }
8452 }
8453
8454 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
8455 ABIArgInfo getIndirectByValue(QualType Ty) const;
8456 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
8457 ABIArgInfo classifyReturnType(QualType RetTy) const;
8458};
8459
8460class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
8461public:
8462 ARCTargetCodeGenInfo(CodeGenTypes &CGT)
8463 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {}
8464};
8465
8466
8467ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
8468 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
8469 getNaturalAlignIndirect(Ty, false);
8470}
8471
8472ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
Daniel Dunbara39bab32019-01-03 23:24:50 +00008473 // Compute the byval alignment.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008474 const unsigned MinABIStackAlignInBytes = 4;
8475 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8476 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8477 TypeAlign > MinABIStackAlignInBytes);
8478}
8479
8480Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8481 QualType Ty) const {
8482 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8483 getContext().getTypeInfoInChars(Ty),
8484 CharUnits::fromQuantity(4), true);
8485}
8486
8487ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
8488 uint8_t FreeRegs) const {
8489 // Handle the generic C++ ABI.
8490 const RecordType *RT = Ty->getAs<RecordType>();
8491 if (RT) {
8492 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8493 if (RAA == CGCXXABI::RAA_Indirect)
8494 return getIndirectByRef(Ty, FreeRegs > 0);
8495
8496 if (RAA == CGCXXABI::RAA_DirectInMemory)
8497 return getIndirectByValue(Ty);
8498 }
8499
8500 // Treat an enum type as its underlying type.
8501 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8502 Ty = EnumTy->getDecl()->getIntegerType();
8503
8504 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
8505
8506 if (isAggregateTypeForABI(Ty)) {
8507 // Structures with flexible arrays are always indirect.
8508 if (RT && RT->getDecl()->hasFlexibleArrayMember())
8509 return getIndirectByValue(Ty);
8510
8511 // Ignore empty structs/unions.
8512 if (isEmptyRecord(getContext(), Ty, true))
8513 return ABIArgInfo::getIgnore();
8514
8515 llvm::LLVMContext &LLVMContext = getVMContext();
8516
8517 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8518 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8519 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8520
8521 return FreeRegs >= SizeInRegs ?
8522 ABIArgInfo::getDirectInReg(Result) :
8523 ABIArgInfo::getDirect(Result, 0, nullptr, false);
8524 }
8525
8526 return Ty->isPromotableIntegerType() ?
8527 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) :
8528 ABIArgInfo::getExtend(Ty)) :
8529 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() :
8530 ABIArgInfo::getDirect());
8531}
8532
8533ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
8534 if (RetTy->isAnyComplexType())
8535 return ABIArgInfo::getDirectInReg();
8536
Daniel Dunbara39bab32019-01-03 23:24:50 +00008537 // Arguments of size > 4 registers are indirect.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008538 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
8539 if (RetSize > 4)
8540 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
8541
8542 return DefaultABIInfo::classifyReturnType(RetTy);
8543}
8544
8545} // End anonymous namespace.
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008546
Robert Lytton0e076492013-08-13 09:43:10 +00008547//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008548// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008549//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008550
Robert Lytton0e076492013-08-13 09:43:10 +00008551namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008552
8553/// A SmallStringEnc instance is used to build up the TypeString by passing
8554/// it by reference between functions that append to it.
8555typedef llvm::SmallString<128> SmallStringEnc;
8556
8557/// TypeStringCache caches the meta encodings of Types.
8558///
8559/// The reason for caching TypeStrings is two fold:
8560/// 1. To cache a type's encoding for later uses;
8561/// 2. As a means to break recursive member type inclusion.
8562///
8563/// A cache Entry can have a Status of:
8564/// NonRecursive: The type encoding is not recursive;
8565/// Recursive: The type encoding is recursive;
8566/// Incomplete: An incomplete TypeString;
8567/// IncompleteUsed: An incomplete TypeString that has been used in a
8568/// Recursive type encoding.
8569///
8570/// A NonRecursive entry will have all of its sub-members expanded as fully
8571/// as possible. Whilst it may contain types which are recursive, the type
8572/// itself is not recursive and thus its encoding may be safely used whenever
8573/// the type is encountered.
8574///
8575/// A Recursive entry will have all of its sub-members expanded as fully as
8576/// possible. The type itself is recursive and it may contain other types which
8577/// are recursive. The Recursive encoding must not be used during the expansion
8578/// of a recursive type's recursive branch. For simplicity the code uses
8579/// IncompleteCount to reject all usage of Recursive encodings for member types.
8580///
8581/// An Incomplete entry is always a RecordType and only encodes its
8582/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8583/// are placed into the cache during type expansion as a means to identify and
8584/// handle recursive inclusion of types as sub-members. If there is recursion
8585/// the entry becomes IncompleteUsed.
8586///
8587/// During the expansion of a RecordType's members:
8588///
8589/// If the cache contains a NonRecursive encoding for the member type, the
8590/// cached encoding is used;
8591///
8592/// If the cache contains a Recursive encoding for the member type, the
8593/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8594///
8595/// If the member is a RecordType, an Incomplete encoding is placed into the
8596/// cache to break potential recursive inclusion of itself as a sub-member;
8597///
8598/// Once a member RecordType has been expanded, its temporary incomplete
8599/// entry is removed from the cache. If a Recursive encoding was swapped out
8600/// it is swapped back in;
8601///
8602/// If an incomplete entry is used to expand a sub-member, the incomplete
8603/// entry is marked as IncompleteUsed. The cache keeps count of how many
8604/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8605///
8606/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8607/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8608/// Else the member is part of a recursive type and thus the recursion has
8609/// been exited too soon for the encoding to be correct for the member.
8610///
8611class TypeStringCache {
8612 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8613 struct Entry {
8614 std::string Str; // The encoded TypeString for the type.
8615 enum Status State; // Information about the encoding in 'Str'.
8616 std::string Swapped; // A temporary place holder for a Recursive encoding
8617 // during the expansion of RecordType's members.
8618 };
8619 std::map<const IdentifierInfo *, struct Entry> Map;
8620 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8621 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8622public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008623 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008624 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8625 bool removeIncomplete(const IdentifierInfo *ID);
8626 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8627 bool IsRecursive);
8628 StringRef lookupStr(const IdentifierInfo *ID);
8629};
8630
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008631/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008632/// FieldEncoding is a helper for this ordering process.
8633class FieldEncoding {
8634 bool HasName;
8635 std::string Enc;
8636public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008637 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008638 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008639 bool operator<(const FieldEncoding &rhs) const {
8640 if (HasName != rhs.HasName) return HasName;
8641 return Enc < rhs.Enc;
8642 }
8643};
8644
Robert Lytton7d1db152013-08-19 09:46:39 +00008645class XCoreABIInfo : public DefaultABIInfo {
8646public:
8647 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008648 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8649 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008650};
8651
Robert Lyttond21e2d72014-03-03 13:45:29 +00008652class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008653 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008654public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008655 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008656 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008657 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8658 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008659};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008660
Robert Lytton2d196952013-10-11 10:29:34 +00008661} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008662
James Y Knight29b5f082016-02-24 02:59:33 +00008663// TODO: this implementation is likely now redundant with the default
8664// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008665Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8666 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008667 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008668
Robert Lytton2d196952013-10-11 10:29:34 +00008669 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008670 CharUnits SlotSize = CharUnits::fromQuantity(4);
8671 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008672
Robert Lytton2d196952013-10-11 10:29:34 +00008673 // Handle the argument.
8674 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008675 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008676 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8677 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8678 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008679 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008680
8681 Address Val = Address::invalid();
8682 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008683 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008684 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008685 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008686 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008687 llvm_unreachable("Unsupported ABI kind for va_arg");
8688 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008689 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8690 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008691 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008692 case ABIArgInfo::Extend:
8693 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008694 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8695 ArgSize = CharUnits::fromQuantity(
8696 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008697 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008698 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008699 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008700 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8701 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8702 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008703 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008704 }
Robert Lytton2d196952013-10-11 10:29:34 +00008705
8706 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008707 if (!ArgSize.isZero()) {
James Y Knight3d2df5a2019-02-05 19:01:33 +00008708 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
8709 Builder.CreateStore(APN.getPointer(), VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008710 }
John McCall7f416cc2015-09-08 08:05:57 +00008711
Robert Lytton2d196952013-10-11 10:29:34 +00008712 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008713}
Robert Lytton0e076492013-08-13 09:43:10 +00008714
Robert Lytton844aeeb2014-05-02 09:33:20 +00008715/// During the expansion of a RecordType, an incomplete TypeString is placed
8716/// into the cache as a means to identify and break recursion.
8717/// If there is a Recursive encoding in the cache, it is swapped out and will
8718/// be reinserted by removeIncomplete().
8719/// All other types of encoding should have been used rather than arriving here.
8720void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8721 std::string StubEnc) {
8722 if (!ID)
8723 return;
8724 Entry &E = Map[ID];
8725 assert( (E.Str.empty() || E.State == Recursive) &&
8726 "Incorrectly use of addIncomplete");
8727 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8728 E.Swapped.swap(E.Str); // swap out the Recursive
8729 E.Str.swap(StubEnc);
8730 E.State = Incomplete;
8731 ++IncompleteCount;
8732}
8733
8734/// Once the RecordType has been expanded, the temporary incomplete TypeString
8735/// must be removed from the cache.
8736/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8737/// Returns true if the RecordType was defined recursively.
8738bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8739 if (!ID)
8740 return false;
8741 auto I = Map.find(ID);
8742 assert(I != Map.end() && "Entry not present");
8743 Entry &E = I->second;
8744 assert( (E.State == Incomplete ||
8745 E.State == IncompleteUsed) &&
8746 "Entry must be an incomplete type");
8747 bool IsRecursive = false;
8748 if (E.State == IncompleteUsed) {
8749 // We made use of our Incomplete encoding, thus we are recursive.
8750 IsRecursive = true;
8751 --IncompleteUsedCount;
8752 }
8753 if (E.Swapped.empty())
8754 Map.erase(I);
8755 else {
8756 // Swap the Recursive back.
8757 E.Swapped.swap(E.Str);
8758 E.Swapped.clear();
8759 E.State = Recursive;
8760 }
8761 --IncompleteCount;
8762 return IsRecursive;
8763}
8764
8765/// Add the encoded TypeString to the cache only if it is NonRecursive or
8766/// Recursive (viz: all sub-members were expanded as fully as possible).
8767void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8768 bool IsRecursive) {
8769 if (!ID || IncompleteUsedCount)
8770 return; // No key or it is is an incomplete sub-type so don't add.
8771 Entry &E = Map[ID];
8772 if (IsRecursive && !E.Str.empty()) {
8773 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8774 "This is not the same Recursive entry");
8775 // The parent container was not recursive after all, so we could have used
8776 // this Recursive sub-member entry after all, but we assumed the worse when
8777 // we started viz: IncompleteCount!=0.
8778 return;
8779 }
8780 assert(E.Str.empty() && "Entry already present");
8781 E.Str = Str.str();
8782 E.State = IsRecursive? Recursive : NonRecursive;
8783}
8784
8785/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8786/// are recursively expanding a type (IncompleteCount != 0) and the cached
8787/// encoding is Recursive, return an empty StringRef.
8788StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8789 if (!ID)
8790 return StringRef(); // We have no key.
8791 auto I = Map.find(ID);
8792 if (I == Map.end())
8793 return StringRef(); // We have no encoding.
8794 Entry &E = I->second;
8795 if (E.State == Recursive && IncompleteCount)
8796 return StringRef(); // We don't use Recursive encodings for member types.
8797
8798 if (E.State == Incomplete) {
8799 // The incomplete type is being used to break out of recursion.
8800 E.State = IncompleteUsed;
8801 ++IncompleteUsedCount;
8802 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008803 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008804}
8805
8806/// The XCore ABI includes a type information section that communicates symbol
8807/// type information to the linker. The linker uses this information to verify
8808/// safety/correctness of things such as array bound and pointers et al.
8809/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8810/// This type information (TypeString) is emitted into meta data for all global
8811/// symbols: definitions, declarations, functions & variables.
8812///
8813/// The TypeString carries type, qualifier, name, size & value details.
8814/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008815/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008816/// The output is tested by test/CodeGen/xcore-stringtype.c.
8817///
8818static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8819 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8820
8821/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8822void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8823 CodeGen::CodeGenModule &CGM) const {
8824 SmallStringEnc Enc;
8825 if (getTypeString(Enc, D, CGM, TSC)) {
8826 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008827 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8828 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008829 llvm::NamedMDNode *MD =
8830 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8831 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8832 }
8833}
8834
Xiuli Pan972bea82016-03-24 03:57:17 +00008835//===----------------------------------------------------------------------===//
8836// SPIR ABI Implementation
8837//===----------------------------------------------------------------------===//
8838
8839namespace {
8840class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8841public:
8842 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8843 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008844 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008845};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008846
Xiuli Pan972bea82016-03-24 03:57:17 +00008847} // End anonymous namespace.
8848
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008849namespace clang {
8850namespace CodeGen {
8851void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8852 DefaultABIInfo SPIRABI(CGM.getTypes());
8853 SPIRABI.computeInfo(FI);
8854}
8855}
8856}
8857
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008858unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8859 return llvm::CallingConv::SPIR_KERNEL;
8860}
8861
Robert Lytton844aeeb2014-05-02 09:33:20 +00008862static bool appendType(SmallStringEnc &Enc, QualType QType,
8863 const CodeGen::CodeGenModule &CGM,
8864 TypeStringCache &TSC);
8865
8866/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008867/// Builds a SmallVector containing the encoded field types in declaration
8868/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008869static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8870 const RecordDecl *RD,
8871 const CodeGen::CodeGenModule &CGM,
8872 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008873 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008874 SmallStringEnc Enc;
8875 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008876 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008877 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008878 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008879 Enc += "b(";
8880 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008881 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008882 Enc += ':';
8883 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008884 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008885 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008886 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008887 Enc += ')';
8888 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008889 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008890 }
8891 return true;
8892}
8893
8894/// Appends structure and union types to Enc and adds encoding to cache.
8895/// Recursively calls appendType (via extractFieldType) for each field.
8896/// Union types have their fields ordered according to the ABI.
8897static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8898 const CodeGen::CodeGenModule &CGM,
8899 TypeStringCache &TSC, const IdentifierInfo *ID) {
8900 // Append the cached TypeString if we have one.
8901 StringRef TypeString = TSC.lookupStr(ID);
8902 if (!TypeString.empty()) {
8903 Enc += TypeString;
8904 return true;
8905 }
8906
8907 // Start to emit an incomplete TypeString.
8908 size_t Start = Enc.size();
8909 Enc += (RT->isUnionType()? 'u' : 's');
8910 Enc += '(';
8911 if (ID)
8912 Enc += ID->getName();
8913 Enc += "){";
8914
8915 // We collect all encoded fields and order as necessary.
8916 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008917 const RecordDecl *RD = RT->getDecl()->getDefinition();
8918 if (RD && !RD->field_empty()) {
8919 // An incomplete TypeString stub is placed in the cache for this RecordType
8920 // so that recursive calls to this RecordType will use it whilst building a
8921 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008922 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008923 std::string StubEnc(Enc.substr(Start).str());
8924 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8925 TSC.addIncomplete(ID, std::move(StubEnc));
8926 if (!extractFieldType(FE, RD, CGM, TSC)) {
8927 (void) TSC.removeIncomplete(ID);
8928 return false;
8929 }
8930 IsRecursive = TSC.removeIncomplete(ID);
8931 // The ABI requires unions to be sorted but not structures.
8932 // See FieldEncoding::operator< for sort algorithm.
8933 if (RT->isUnionType())
Fangrui Song55fab262018-09-26 22:16:28 +00008934 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008935 // We can now complete the TypeString.
8936 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008937 for (unsigned I = 0; I != E; ++I) {
8938 if (I)
8939 Enc += ',';
8940 Enc += FE[I].str();
8941 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008942 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008943 Enc += '}';
8944 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8945 return true;
8946}
8947
8948/// Appends enum types to Enc and adds the encoding to the cache.
8949static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8950 TypeStringCache &TSC,
8951 const IdentifierInfo *ID) {
8952 // Append the cached TypeString if we have one.
8953 StringRef TypeString = TSC.lookupStr(ID);
8954 if (!TypeString.empty()) {
8955 Enc += TypeString;
8956 return true;
8957 }
8958
8959 size_t Start = Enc.size();
8960 Enc += "e(";
8961 if (ID)
8962 Enc += ID->getName();
8963 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008964
8965 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008966 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008967 SmallVector<FieldEncoding, 16> FE;
8968 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8969 ++I) {
8970 SmallStringEnc EnumEnc;
8971 EnumEnc += "m(";
8972 EnumEnc += I->getName();
8973 EnumEnc += "){";
8974 I->getInitVal().toString(EnumEnc);
8975 EnumEnc += '}';
8976 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8977 }
Fangrui Song55fab262018-09-26 22:16:28 +00008978 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008979 unsigned E = FE.size();
8980 for (unsigned I = 0; I != E; ++I) {
8981 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008982 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008983 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008984 }
8985 }
8986 Enc += '}';
8987 TSC.addIfComplete(ID, Enc.substr(Start), false);
8988 return true;
8989}
8990
8991/// Appends type's qualifier to Enc.
8992/// This is done prior to appending the type's encoding.
8993static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8994 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008995 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008996 int Lookup = 0;
8997 if (QT.isConstQualified())
8998 Lookup += 1<<0;
8999 if (QT.isRestrictQualified())
9000 Lookup += 1<<1;
9001 if (QT.isVolatileQualified())
9002 Lookup += 1<<2;
9003 Enc += Table[Lookup];
9004}
9005
9006/// Appends built-in types to Enc.
9007static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
9008 const char *EncType;
9009 switch (BT->getKind()) {
9010 case BuiltinType::Void:
9011 EncType = "0";
9012 break;
9013 case BuiltinType::Bool:
9014 EncType = "b";
9015 break;
9016 case BuiltinType::Char_U:
9017 EncType = "uc";
9018 break;
9019 case BuiltinType::UChar:
9020 EncType = "uc";
9021 break;
9022 case BuiltinType::SChar:
9023 EncType = "sc";
9024 break;
9025 case BuiltinType::UShort:
9026 EncType = "us";
9027 break;
9028 case BuiltinType::Short:
9029 EncType = "ss";
9030 break;
9031 case BuiltinType::UInt:
9032 EncType = "ui";
9033 break;
9034 case BuiltinType::Int:
9035 EncType = "si";
9036 break;
9037 case BuiltinType::ULong:
9038 EncType = "ul";
9039 break;
9040 case BuiltinType::Long:
9041 EncType = "sl";
9042 break;
9043 case BuiltinType::ULongLong:
9044 EncType = "ull";
9045 break;
9046 case BuiltinType::LongLong:
9047 EncType = "sll";
9048 break;
9049 case BuiltinType::Float:
9050 EncType = "ft";
9051 break;
9052 case BuiltinType::Double:
9053 EncType = "d";
9054 break;
9055 case BuiltinType::LongDouble:
9056 EncType = "ld";
9057 break;
9058 default:
9059 return false;
9060 }
9061 Enc += EncType;
9062 return true;
9063}
9064
9065/// Appends a pointer encoding to Enc before calling appendType for the pointee.
9066static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
9067 const CodeGen::CodeGenModule &CGM,
9068 TypeStringCache &TSC) {
9069 Enc += "p(";
9070 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
9071 return false;
9072 Enc += ')';
9073 return true;
9074}
9075
9076/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009077static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
9078 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00009079 const CodeGen::CodeGenModule &CGM,
9080 TypeStringCache &TSC, StringRef NoSizeEnc) {
9081 if (AT->getSizeModifier() != ArrayType::Normal)
9082 return false;
9083 Enc += "a(";
9084 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
9085 CAT->getSize().toStringUnsigned(Enc);
9086 else
9087 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
9088 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00009089 // The Qualifiers should be attached to the type rather than the array.
9090 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00009091 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
9092 return false;
9093 Enc += ')';
9094 return true;
9095}
9096
9097/// Appends a function encoding to Enc, calling appendType for the return type
9098/// and the arguments.
9099static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
9100 const CodeGen::CodeGenModule &CGM,
9101 TypeStringCache &TSC) {
9102 Enc += "f{";
9103 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
9104 return false;
9105 Enc += "}(";
9106 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
9107 // N.B. we are only interested in the adjusted param types.
9108 auto I = FPT->param_type_begin();
9109 auto E = FPT->param_type_end();
9110 if (I != E) {
9111 do {
9112 if (!appendType(Enc, *I, CGM, TSC))
9113 return false;
9114 ++I;
9115 if (I != E)
9116 Enc += ',';
9117 } while (I != E);
9118 if (FPT->isVariadic())
9119 Enc += ",va";
9120 } else {
9121 if (FPT->isVariadic())
9122 Enc += "va";
9123 else
9124 Enc += '0';
9125 }
9126 }
9127 Enc += ')';
9128 return true;
9129}
9130
9131/// Handles the type's qualifier before dispatching a call to handle specific
9132/// type encodings.
9133static bool appendType(SmallStringEnc &Enc, QualType QType,
9134 const CodeGen::CodeGenModule &CGM,
9135 TypeStringCache &TSC) {
9136
9137 QualType QT = QType.getCanonicalType();
9138
Robert Lytton6adb20f2014-06-05 09:06:21 +00009139 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
9140 // The Qualifiers should be attached to the type rather than the array.
9141 // Thus we don't call appendQualifier() here.
9142 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
9143
Robert Lytton844aeeb2014-05-02 09:33:20 +00009144 appendQualifier(Enc, QT);
9145
9146 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
9147 return appendBuiltinType(Enc, BT);
9148
Robert Lytton844aeeb2014-05-02 09:33:20 +00009149 if (const PointerType *PT = QT->getAs<PointerType>())
9150 return appendPointerType(Enc, PT, CGM, TSC);
9151
9152 if (const EnumType *ET = QT->getAs<EnumType>())
9153 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9154
9155 if (const RecordType *RT = QT->getAsStructureType())
9156 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9157
9158 if (const RecordType *RT = QT->getAsUnionType())
9159 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9160
9161 if (const FunctionType *FT = QT->getAs<FunctionType>())
9162 return appendFunctionType(Enc, FT, CGM, TSC);
9163
9164 return false;
9165}
9166
9167static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9168 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9169 if (!D)
9170 return false;
9171
9172 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9173 if (FD->getLanguageLinkage() != CLanguageLinkage)
9174 return false;
9175 return appendType(Enc, FD->getType(), CGM, TSC);
9176 }
9177
9178 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9179 if (VD->getLanguageLinkage() != CLanguageLinkage)
9180 return false;
9181 QualType QT = VD->getType().getCanonicalType();
9182 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9183 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009184 // The Qualifiers should be attached to the type rather than the array.
9185 // Thus we don't call appendQualifier() here.
9186 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00009187 }
9188 return appendType(Enc, QT, CGM, TSC);
9189 }
9190 return false;
9191}
9192
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009193//===----------------------------------------------------------------------===//
9194// RISCV ABI Implementation
9195//===----------------------------------------------------------------------===//
9196
9197namespace {
9198class RISCVABIInfo : public DefaultABIInfo {
9199private:
Alex Bradburye078967a2019-07-18 18:29:59 +00009200 // Size of the integer ('x') registers in bits.
9201 unsigned XLen;
9202 // Size of the floating point ('f') registers in bits. Note that the target
9203 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
9204 // with soft float ABI has FLen==0).
9205 unsigned FLen;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009206 static const int NumArgGPRs = 8;
Alex Bradburye078967a2019-07-18 18:29:59 +00009207 static const int NumArgFPRs = 8;
9208 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9209 llvm::Type *&Field1Ty,
9210 CharUnits &Field1Off,
9211 llvm::Type *&Field2Ty,
9212 CharUnits &Field2Off) const;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009213
9214public:
Alex Bradburye078967a2019-07-18 18:29:59 +00009215 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
9216 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009217
9218 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9219 // non-virtual, but computeInfo is virtual, so we overload it.
9220 void computeInfo(CGFunctionInfo &FI) const override;
9221
Alex Bradburye078967a2019-07-18 18:29:59 +00009222 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
9223 int &ArgFPRsLeft) const;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009224 ABIArgInfo classifyReturnType(QualType RetTy) const;
9225
9226 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9227 QualType Ty) const override;
9228
9229 ABIArgInfo extendType(QualType Ty) const;
Alex Bradburye078967a2019-07-18 18:29:59 +00009230
9231 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9232 CharUnits &Field1Off, llvm::Type *&Field2Ty,
9233 CharUnits &Field2Off, int &NeededArgGPRs,
9234 int &NeededArgFPRs) const;
9235 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
9236 CharUnits Field1Off,
9237 llvm::Type *Field2Ty,
9238 CharUnits Field2Off) const;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009239};
9240} // end anonymous namespace
9241
9242void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9243 QualType RetTy = FI.getReturnType();
9244 if (!getCXXABI().classifyReturnType(FI))
9245 FI.getReturnInfo() = classifyReturnType(RetTy);
9246
9247 // IsRetIndirect is true if classifyArgumentType indicated the value should
9248 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
9249 // is passed direct in LLVM IR, relying on the backend lowering code to
9250 // rewrite the argument list and pass indirectly on RV32.
9251 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
9252 getContext().getTypeSize(RetTy) > (2 * XLen);
9253
9254 // We must track the number of GPRs used in order to conform to the RISC-V
9255 // ABI, as integer scalars passed in registers should have signext/zeroext
9256 // when promoted, but are anyext if passed on the stack. As GPR usage is
9257 // different for variadic arguments, we must also track whether we are
9258 // examining a vararg or not.
9259 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
Alex Bradburye078967a2019-07-18 18:29:59 +00009260 int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009261 int NumFixedArgs = FI.getNumRequiredArgs();
9262
9263 int ArgNum = 0;
9264 for (auto &ArgInfo : FI.arguments()) {
9265 bool IsFixed = ArgNum < NumFixedArgs;
Alex Bradburye078967a2019-07-18 18:29:59 +00009266 ArgInfo.info =
9267 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009268 ArgNum++;
9269 }
9270}
9271
Alex Bradburye078967a2019-07-18 18:29:59 +00009272// Returns true if the struct is a potential candidate for the floating point
9273// calling convention. If this function returns true, the caller is
9274// responsible for checking that if there is only a single field then that
9275// field is a float.
9276bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9277 llvm::Type *&Field1Ty,
9278 CharUnits &Field1Off,
9279 llvm::Type *&Field2Ty,
9280 CharUnits &Field2Off) const {
9281 bool IsInt = Ty->isIntegralOrEnumerationType();
9282 bool IsFloat = Ty->isRealFloatingType();
9283
9284 if (IsInt || IsFloat) {
9285 uint64_t Size = getContext().getTypeSize(Ty);
9286 if (IsInt && Size > XLen)
9287 return false;
9288 // Can't be eligible if larger than the FP registers. Half precision isn't
9289 // currently supported on RISC-V and the ABI hasn't been confirmed, so
9290 // default to the integer ABI in that case.
9291 if (IsFloat && (Size > FLen || Size < 32))
9292 return false;
9293 // Can't be eligible if an integer type was already found (int+int pairs
9294 // are not eligible).
9295 if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
9296 return false;
9297 if (!Field1Ty) {
9298 Field1Ty = CGT.ConvertType(Ty);
9299 Field1Off = CurOff;
9300 return true;
9301 }
9302 if (!Field2Ty) {
9303 Field2Ty = CGT.ConvertType(Ty);
9304 Field2Off = CurOff;
9305 return true;
9306 }
9307 return false;
9308 }
9309
9310 if (auto CTy = Ty->getAs<ComplexType>()) {
9311 if (Field1Ty)
9312 return false;
9313 QualType EltTy = CTy->getElementType();
9314 if (getContext().getTypeSize(EltTy) > FLen)
9315 return false;
9316 Field1Ty = CGT.ConvertType(EltTy);
9317 Field1Off = CurOff;
9318 assert(CurOff.isZero() && "Unexpected offset for first field");
9319 Field2Ty = Field1Ty;
9320 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
9321 return true;
9322 }
9323
9324 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
9325 uint64_t ArraySize = ATy->getSize().getZExtValue();
9326 QualType EltTy = ATy->getElementType();
9327 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
9328 for (uint64_t i = 0; i < ArraySize; ++i) {
9329 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
9330 Field1Off, Field2Ty, Field2Off);
9331 if (!Ret)
9332 return false;
9333 CurOff += EltSize;
9334 }
9335 return true;
9336 }
9337
9338 if (const auto *RTy = Ty->getAs<RecordType>()) {
9339 // Structures with either a non-trivial destructor or a non-trivial
9340 // copy constructor are not eligible for the FP calling convention.
Denis Bakhvalova29002e2019-07-19 21:59:42 +00009341 if (getRecordArgABI(Ty, CGT.getCXXABI()))
Alex Bradburye078967a2019-07-18 18:29:59 +00009342 return false;
9343 if (isEmptyRecord(getContext(), Ty, true))
9344 return true;
9345 const RecordDecl *RD = RTy->getDecl();
9346 // Unions aren't eligible unless they're empty (which is caught above).
9347 if (RD->isUnion())
9348 return false;
9349 int ZeroWidthBitFieldCount = 0;
9350 for (const FieldDecl *FD : RD->fields()) {
9351 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
9352 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
9353 QualType QTy = FD->getType();
9354 if (FD->isBitField()) {
9355 unsigned BitWidth = FD->getBitWidthValue(getContext());
9356 // Allow a bitfield with a type greater than XLen as long as the
9357 // bitwidth is XLen or less.
9358 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
9359 QTy = getContext().getIntTypeForBitwidth(XLen, false);
9360 if (BitWidth == 0) {
9361 ZeroWidthBitFieldCount++;
9362 continue;
9363 }
9364 }
9365
9366 bool Ret = detectFPCCEligibleStructHelper(
9367 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
9368 Field1Ty, Field1Off, Field2Ty, Field2Off);
9369 if (!Ret)
9370 return false;
9371
9372 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
9373 // or int+fp structs, but are ignored for a struct with an fp field and
9374 // any number of zero-width bitfields.
9375 if (Field2Ty && ZeroWidthBitFieldCount > 0)
9376 return false;
9377 }
9378 return Field1Ty != nullptr;
9379 }
9380
9381 return false;
9382}
9383
9384// Determine if a struct is eligible for passing according to the floating
9385// point calling convention (i.e., when flattened it contains a single fp
9386// value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
9387// NeededArgGPRs are incremented appropriately.
9388bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9389 CharUnits &Field1Off,
9390 llvm::Type *&Field2Ty,
9391 CharUnits &Field2Off,
9392 int &NeededArgGPRs,
9393 int &NeededArgFPRs) const {
9394 Field1Ty = nullptr;
9395 Field2Ty = nullptr;
9396 NeededArgGPRs = 0;
9397 NeededArgFPRs = 0;
9398 bool IsCandidate = detectFPCCEligibleStructHelper(
9399 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
9400 // Not really a candidate if we have a single int but no float.
9401 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
9402 return IsCandidate = false;
9403 if (!IsCandidate)
9404 return false;
9405 if (Field1Ty && Field1Ty->isFloatingPointTy())
9406 NeededArgFPRs++;
9407 else if (Field1Ty)
9408 NeededArgGPRs++;
9409 if (Field2Ty && Field2Ty->isFloatingPointTy())
9410 NeededArgFPRs++;
9411 else if (Field2Ty)
9412 NeededArgGPRs++;
9413 return IsCandidate;
9414}
9415
9416// Call getCoerceAndExpand for the two-element flattened struct described by
9417// Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
9418// appropriate coerceToType and unpaddedCoerceToType.
9419ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
9420 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
9421 CharUnits Field2Off) const {
9422 SmallVector<llvm::Type *, 3> CoerceElts;
9423 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
9424 if (!Field1Off.isZero())
9425 CoerceElts.push_back(llvm::ArrayType::get(
9426 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
9427
9428 CoerceElts.push_back(Field1Ty);
9429 UnpaddedCoerceElts.push_back(Field1Ty);
9430
9431 if (!Field2Ty) {
9432 return ABIArgInfo::getCoerceAndExpand(
9433 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
9434 UnpaddedCoerceElts[0]);
9435 }
9436
9437 CharUnits Field2Align =
9438 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
9439 CharUnits Field1Size =
9440 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
9441 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align);
9442
9443 CharUnits Padding = CharUnits::Zero();
9444 if (Field2Off > Field2OffNoPadNoPack)
9445 Padding = Field2Off - Field2OffNoPadNoPack;
9446 else if (Field2Off != Field2Align && Field2Off > Field1Size)
9447 Padding = Field2Off - Field1Size;
9448
9449 bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
9450
9451 if (!Padding.isZero())
9452 CoerceElts.push_back(llvm::ArrayType::get(
9453 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
9454
9455 CoerceElts.push_back(Field2Ty);
9456 UnpaddedCoerceElts.push_back(Field2Ty);
9457
9458 auto CoerceToType =
9459 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
9460 auto UnpaddedCoerceToType =
9461 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
9462
9463 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
9464}
9465
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009466ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
Alex Bradburye078967a2019-07-18 18:29:59 +00009467 int &ArgGPRsLeft,
9468 int &ArgFPRsLeft) const {
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009469 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
9470 Ty = useFirstFieldIfTransparentUnion(Ty);
9471
9472 // Structures with either a non-trivial destructor or a non-trivial
9473 // copy constructor are always passed indirectly.
9474 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
9475 if (ArgGPRsLeft)
9476 ArgGPRsLeft -= 1;
9477 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
9478 CGCXXABI::RAA_DirectInMemory);
9479 }
9480
9481 // Ignore empty structs/unions.
9482 if (isEmptyRecord(getContext(), Ty, true))
9483 return ABIArgInfo::getIgnore();
9484
9485 uint64_t Size = getContext().getTypeSize(Ty);
Alex Bradburye078967a2019-07-18 18:29:59 +00009486
9487 // Pass floating point values via FPRs if possible.
9488 if (IsFixed && Ty->isFloatingType() && FLen >= Size && ArgFPRsLeft) {
9489 ArgFPRsLeft--;
9490 return ABIArgInfo::getDirect();
9491 }
9492
9493 // Complex types for the hard float ABI must be passed direct rather than
9494 // using CoerceAndExpand.
9495 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
9496 QualType EltTy = Ty->getAs<ComplexType>()->getElementType();
9497 if (getContext().getTypeSize(EltTy) <= FLen) {
9498 ArgFPRsLeft -= 2;
9499 return ABIArgInfo::getDirect();
9500 }
9501 }
9502
9503 if (IsFixed && FLen && Ty->isStructureOrClassType()) {
9504 llvm::Type *Field1Ty = nullptr;
9505 llvm::Type *Field2Ty = nullptr;
9506 CharUnits Field1Off = CharUnits::Zero();
9507 CharUnits Field2Off = CharUnits::Zero();
9508 int NeededArgGPRs;
9509 int NeededArgFPRs;
9510 bool IsCandidate =
9511 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
9512 NeededArgGPRs, NeededArgFPRs);
9513 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
9514 NeededArgFPRs <= ArgFPRsLeft) {
9515 ArgGPRsLeft -= NeededArgGPRs;
9516 ArgFPRsLeft -= NeededArgFPRs;
9517 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
9518 Field2Off);
9519 }
9520 }
9521
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009522 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
9523 bool MustUseStack = false;
9524 // Determine the number of GPRs needed to pass the current argument
9525 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
9526 // register pairs, so may consume 3 registers.
9527 int NeededArgGPRs = 1;
9528 if (!IsFixed && NeededAlign == 2 * XLen)
9529 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
9530 else if (Size > XLen && Size <= 2 * XLen)
9531 NeededArgGPRs = 2;
9532
9533 if (NeededArgGPRs > ArgGPRsLeft) {
9534 MustUseStack = true;
9535 NeededArgGPRs = ArgGPRsLeft;
9536 }
9537
9538 ArgGPRsLeft -= NeededArgGPRs;
9539
9540 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
9541 // Treat an enum type as its underlying type.
9542 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9543 Ty = EnumTy->getDecl()->getIntegerType();
9544
9545 // All integral types are promoted to XLen width, unless passed on the
9546 // stack.
9547 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9548 return extendType(Ty);
9549 }
9550
9551 return ABIArgInfo::getDirect();
9552 }
9553
9554 // Aggregates which are <= 2*XLen will be passed in registers if possible,
9555 // so coerce to integers.
9556 if (Size <= 2 * XLen) {
9557 unsigned Alignment = getContext().getTypeAlign(Ty);
9558
9559 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9560 // required, and a 2-element XLen array if only XLen alignment is required.
9561 if (Size <= XLen) {
9562 return ABIArgInfo::getDirect(
9563 llvm::IntegerType::get(getVMContext(), XLen));
9564 } else if (Alignment == 2 * XLen) {
9565 return ABIArgInfo::getDirect(
9566 llvm::IntegerType::get(getVMContext(), 2 * XLen));
9567 } else {
9568 return ABIArgInfo::getDirect(llvm::ArrayType::get(
9569 llvm::IntegerType::get(getVMContext(), XLen), 2));
9570 }
9571 }
9572 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9573}
9574
9575ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9576 if (RetTy->isVoidType())
9577 return ABIArgInfo::getIgnore();
9578
9579 int ArgGPRsLeft = 2;
Alex Bradburye078967a2019-07-18 18:29:59 +00009580 int ArgFPRsLeft = FLen ? 2 : 0;
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009581
9582 // The rules for return and argument types are the same, so defer to
9583 // classifyArgumentType.
Alex Bradburye078967a2019-07-18 18:29:59 +00009584 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
9585 ArgFPRsLeft);
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009586}
9587
9588Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9589 QualType Ty) const {
9590 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9591
9592 // Empty records are ignored for parameter passing purposes.
9593 if (isEmptyRecord(getContext(), Ty, true)) {
9594 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9595 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9596 return Addr;
9597 }
9598
9599 std::pair<CharUnits, CharUnits> SizeAndAlign =
9600 getContext().getTypeInfoInChars(Ty);
9601
9602 // Arguments bigger than 2*Xlen bytes are passed indirectly.
9603 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9604
9605 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9606 SlotSize, /*AllowHigherAlign=*/true);
9607}
9608
9609ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9610 int TySize = getContext().getTypeSize(Ty);
9611 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9612 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9613 return ABIArgInfo::getSignExtend(Ty);
9614 return ABIArgInfo::getExtend(Ty);
9615}
9616
9617namespace {
9618class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9619public:
Alex Bradburye078967a2019-07-18 18:29:59 +00009620 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
9621 unsigned FLen)
9622 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen, FLen)) {}
Ana Pazos1eee1b72018-07-26 17:37:45 +00009623
9624 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9625 CodeGen::CodeGenModule &CGM) const override {
9626 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9627 if (!FD) return;
9628
9629 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9630 if (!Attr)
9631 return;
9632
9633 const char *Kind;
9634 switch (Attr->getInterrupt()) {
9635 case RISCVInterruptAttr::user: Kind = "user"; break;
9636 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9637 case RISCVInterruptAttr::machine: Kind = "machine"; break;
9638 }
9639
9640 auto *Fn = cast<llvm::Function>(GV);
9641
9642 Fn->addFnAttr("interrupt", Kind);
9643 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009644};
9645} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00009646
Robert Lytton0e076492013-08-13 09:43:10 +00009647//===----------------------------------------------------------------------===//
9648// Driver code
9649//===----------------------------------------------------------------------===//
9650
Rafael Espindola9f834732014-09-19 01:54:22 +00009651bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00009652 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00009653}
9654
Chris Lattner2b037972010-07-29 02:01:43 +00009655const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009656 if (TheTargetCodeGenInfo)
9657 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009658
Reid Kleckner9305fd12016-04-13 23:37:17 +00009659 // Helper to set the unique_ptr while still keeping the return value.
9660 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9661 this->TheTargetCodeGenInfo.reset(P);
9662 return *P;
9663 };
9664
John McCallc8e01702013-04-16 22:48:15 +00009665 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00009666 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00009667 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009668 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00009669
Derek Schuff09338a22012-09-06 17:37:28 +00009670 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009671 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00009672 case llvm::Triple::mips:
9673 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00009674 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00009675 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9676 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009677
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00009678 case llvm::Triple::mips64:
9679 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009680 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009681
Dylan McKaye8232d72017-02-08 05:09:26 +00009682 case llvm::Triple::avr:
9683 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9684
Tim Northover25e8a672014-05-24 12:51:25 +00009685 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00009686 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00009687 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00009688 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00009689 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00009690 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00009691 return SetCGInfo(
9692 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00009693
Reid Kleckner9305fd12016-04-13 23:37:17 +00009694 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009695 }
9696
Dan Gohmanc2853072015-09-03 22:51:53 +00009697 case llvm::Triple::wasm32:
9698 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009699 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009700
Daniel Dunbard59655c2009-09-12 00:59:49 +00009701 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009702 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009703 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009704 case llvm::Triple::thumbeb: {
9705 if (Triple.getOS() == llvm::Triple::Win32) {
9706 return SetCGInfo(
9707 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009708 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009709
Reid Kleckner9305fd12016-04-13 23:37:17 +00009710 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9711 StringRef ABIStr = getTarget().getABI();
9712 if (ABIStr == "apcs-gnu")
9713 Kind = ARMABIInfo::APCS;
9714 else if (ABIStr == "aapcs16")
9715 Kind = ARMABIInfo::AAPCS16_VFP;
9716 else if (CodeGenOpts.FloatABI == "hard" ||
9717 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009718 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009719 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009720 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009721 Kind = ARMABIInfo::AAPCS_VFP;
9722
9723 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9724 }
9725
John McCallea8d8bb2010-03-11 00:10:12 +00009726 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009727 return SetCGInfo(
9728 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00009729 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009730 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009731 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009732 if (getTarget().getABI() == "elfv2")
9733 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009734 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009735 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009736
Hal Finkel415c2a32016-10-02 02:10:45 +00009737 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9738 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009739 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009740 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009741 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009742 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009743 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009744 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009745 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009746 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009747 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009748
Hal Finkel415c2a32016-10-02 02:10:45 +00009749 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9750 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009751 }
John McCallea8d8bb2010-03-11 00:10:12 +00009752
Peter Collingbournec947aae2012-05-20 23:28:41 +00009753 case llvm::Triple::nvptx:
9754 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009755 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009756
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009757 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009758 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009759
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009760 case llvm::Triple::riscv32:
Alex Bradburye078967a2019-07-18 18:29:59 +00009761 case llvm::Triple::riscv64: {
9762 StringRef ABIStr = getTarget().getABI();
9763 unsigned XLen = getTarget().getPointerWidth(0);
9764 unsigned ABIFLen = 0;
9765 if (ABIStr.endswith("f"))
9766 ABIFLen = 32;
9767 else if (ABIStr.endswith("d"))
9768 ABIFLen = 64;
9769 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
9770 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009771
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009772 case llvm::Triple::systemz: {
9773 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009774 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009775 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009776
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009777 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009778 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009779 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009780
Eli Friedman33465822011-07-08 23:31:17 +00009781 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009782 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009783 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009784 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009785 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009786
John McCall1fe2a8c2013-06-18 02:46:29 +00009787 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009788 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9789 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9790 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009791 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009792 return SetCGInfo(new X86_32TargetCodeGenInfo(
9793 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9794 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
Hans Wennborgd874c052019-06-19 11:34:08 +00009795 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009796 }
Eli Friedman33465822011-07-08 23:31:17 +00009797 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009798
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009799 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009800 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009801 X86AVXABILevel AVXLevel =
9802 (ABI == "avx512"
9803 ? X86AVXABILevel::AVX512
9804 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009805
Chris Lattner04dc9572010-08-31 16:44:54 +00009806 switch (Triple.getOS()) {
9807 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009808 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009809 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009810 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009811 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009812 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009813 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009814 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009815 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009816 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009817 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009818 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009819 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009820 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009821 case llvm::Triple::sparc:
9822 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009823 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009824 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009825 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009826 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00009827 case llvm::Triple::arc:
9828 return SetCGInfo(new ARCTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009829 case llvm::Triple::spir:
9830 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009831 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009832 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009833}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009834
9835/// Create an OpenCL kernel for an enqueued block.
9836///
9837/// The kernel has the same function type as the block invoke function. Its
9838/// name is the name of the block invoke function postfixed with "_kernel".
9839/// It simply calls the block invoke function then returns.
9840llvm::Function *
9841TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9842 llvm::Function *Invoke,
9843 llvm::Value *BlockLiteral) const {
9844 auto *InvokeFT = Invoke->getFunctionType();
9845 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9846 for (auto &P : InvokeFT->params())
9847 ArgTys.push_back(P);
9848 auto &C = CGF.getLLVMContext();
9849 std::string Name = Invoke->getName().str() + "_kernel";
9850 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9851 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9852 &CGF.CGM.getModule());
9853 auto IP = CGF.Builder.saveIP();
9854 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9855 auto &Builder = CGF.Builder;
9856 Builder.SetInsertPoint(BB);
9857 llvm::SmallVector<llvm::Value *, 2> Args;
9858 for (auto &A : F->args())
9859 Args.push_back(&A);
9860 Builder.CreateCall(Invoke, Args);
9861 Builder.CreateRetVoid();
9862 Builder.restoreIP(IP);
9863 return F;
9864}
9865
9866/// Create an OpenCL kernel for an enqueued block.
9867///
9868/// The type of the first argument (the block literal) is the struct type
9869/// of the block literal instead of a pointer type. The first argument
9870/// (block literal) is passed directly by value to the kernel. The kernel
9871/// allocates the same type of struct on stack and stores the block literal
9872/// to it and passes its pointer to the block invoke function. The kernel
9873/// has "enqueued-block" function attribute and kernel argument metadata.
9874llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9875 CodeGenFunction &CGF, llvm::Function *Invoke,
9876 llvm::Value *BlockLiteral) const {
9877 auto &Builder = CGF.Builder;
9878 auto &C = CGF.getLLVMContext();
9879
9880 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9881 auto *InvokeFT = Invoke->getFunctionType();
9882 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9883 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9884 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9885 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9886 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9887 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9888 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9889
9890 ArgTys.push_back(BlockTy);
9891 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9892 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9893 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9894 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9895 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9896 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9897 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9898 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009899 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9900 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9901 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9902 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9903 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9904 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009905 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009906 }
9907 std::string Name = Invoke->getName().str() + "_kernel";
9908 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9909 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9910 &CGF.CGM.getModule());
9911 F->addFnAttr("enqueued-block");
9912 auto IP = CGF.Builder.saveIP();
9913 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9914 Builder.SetInsertPoint(BB);
9915 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9916 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9917 BlockPtr->setAlignment(BlockAlign);
9918 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9919 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9920 llvm::SmallVector<llvm::Value *, 2> Args;
9921 Args.push_back(Cast);
9922 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9923 Args.push_back(I);
9924 Builder.CreateCall(Invoke, Args);
9925 Builder.CreateRetVoid();
9926 Builder.restoreIP(IP);
9927
9928 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9929 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9930 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9931 F->setMetadata("kernel_arg_base_type",
9932 llvm::MDNode::get(C, ArgBaseTypeNames));
9933 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9934 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9935 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9936
9937 return F;
9938}