blob: 675838ed97f356573f65c138258181f5ece205bb [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);
John McCall7f416cc2015-09-08 08:05:57 +0000312 llvm::Value *NextPtr =
313 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
314 "argp.next");
315 CGF.Builder.CreateStore(NextPtr, VAListAddr);
316
317 // If the argument is smaller than a slot, and this is a big-endian
318 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000319 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
320 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000321 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
322 }
323
324 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
325 return Addr;
326}
327
328/// Emit va_arg for a platform using the common void* representation,
329/// where arguments are simply emitted in an array of slots on the stack.
330///
331/// \param IsIndirect - Values of this type are passed indirectly.
332/// \param ValueInfo - The size and alignment of this type, generally
333/// computed with getContext().getTypeInfoInChars(ValueTy).
334/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
335/// Each argument will be allocated to a multiple of this number of
336/// slots, and all the slots will be aligned to this value.
337/// \param AllowHigherAlign - The slot alignment is not a cap;
338/// an argument type with an alignment greater than the slot size
339/// will be emitted on a higher-alignment address, potentially
340/// leaving one or more empty slots behind as padding.
341static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
342 QualType ValueTy, bool IsIndirect,
343 std::pair<CharUnits, CharUnits> ValueInfo,
344 CharUnits SlotSizeAndAlign,
345 bool AllowHigherAlign) {
346 // The size and alignment of the value that was passed directly.
347 CharUnits DirectSize, DirectAlign;
348 if (IsIndirect) {
349 DirectSize = CGF.getPointerSize();
350 DirectAlign = CGF.getPointerAlign();
351 } else {
352 DirectSize = ValueInfo.first;
353 DirectAlign = ValueInfo.second;
354 }
355
356 // Cast the address we've calculated to the right type.
357 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
358 if (IsIndirect)
359 DirectTy = DirectTy->getPointerTo(0);
360
361 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
362 DirectSize, DirectAlign,
363 SlotSizeAndAlign,
364 AllowHigherAlign);
365
366 if (IsIndirect) {
367 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
368 }
369
370 return Addr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000371
John McCall7f416cc2015-09-08 08:05:57 +0000372}
373
374static Address emitMergePHI(CodeGenFunction &CGF,
375 Address Addr1, llvm::BasicBlock *Block1,
376 Address Addr2, llvm::BasicBlock *Block2,
377 const llvm::Twine &Name = "") {
378 assert(Addr1.getType() == Addr2.getType());
379 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
380 PHI->addIncoming(Addr1.getPointer(), Block1);
381 PHI->addIncoming(Addr2.getPointer(), Block2);
382 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
383 return Address(PHI, Align);
384}
385
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000386TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
387
John McCall3480ef22011-08-30 01:42:09 +0000388// If someone can figure out a general rule for this, that would be great.
389// It's probably just doomed to be platform-dependent, though.
390unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
391 // Verified for:
392 // x86-64 FreeBSD, Linux, Darwin
393 // x86-32 FreeBSD, Linux, Darwin
394 // PowerPC Linux, Darwin
395 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000396 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000397 return 32;
398}
399
John McCalla729c622012-02-17 03:33:10 +0000400bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
401 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000402 // The following conventions are known to require this to be false:
403 // x86_stdcall
404 // MIPS
405 // For everything else, we just prefer false unless we opt out.
406 return false;
407}
408
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000409void
410TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
411 llvm::SmallString<24> &Opt) const {
412 // This assumes the user is passing a library name like "rt" instead of a
413 // filename like "librt.a/so", and that they don't care whether it's static or
414 // dynamic.
415 Opt = "-l";
416 Opt += Lib;
417}
418
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000419unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000420 // OpenCL kernels are called via an explicit runtime API with arguments
421 // set with clSetKernelArg(), not as normal sub-functions.
422 // Return SPIR_KERNEL by default as the kernel calling convention to
423 // ensure the fingerprint is fixed such way that each OpenCL argument
424 // gets one matching argument in the produced kernel function argument
425 // list to enable feasible implementation of clSetKernelArg() with
426 // aggregates etc. In case we would use the default C calling conv here,
427 // clSetKernelArg() might break depending on the target-specific
428 // conventions; different targets might split structs passed as values
429 // to multiple function arguments etc.
430 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000431}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000432
Yaxun Liu402804b2016-12-15 08:09:08 +0000433llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
434 llvm::PointerType *T, QualType QT) const {
435 return llvm::ConstantPointerNull::get(T);
436}
437
Alexander Richardson6d989432017-10-15 18:48:14 +0000438LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
439 const VarDecl *D) const {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000440 assert(!CGM.getLangOpts().OpenCL &&
441 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
442 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +0000443 return D ? D->getType().getAddressSpace() : LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +0000444}
445
Yaxun Liu402804b2016-12-15 08:09:08 +0000446llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Alexander Richardson6d989432017-10-15 18:48:14 +0000447 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
448 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000449 // Since target may map different address spaces in AST to the same address
450 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000451 if (auto *C = dyn_cast<llvm::Constant>(Src))
452 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000453 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000454}
455
Yaxun Liucbf647c2017-07-08 13:24:52 +0000456llvm::Constant *
457TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
Alexander Richardson6d989432017-10-15 18:48:14 +0000458 LangAS SrcAddr, LangAS DestAddr,
Yaxun Liucbf647c2017-07-08 13:24:52 +0000459 llvm::Type *DestTy) const {
460 // Since target may map different address spaces in AST to the same address
461 // space, an address space conversion may end up as a bitcast.
462 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
463}
464
Yaxun Liu39195062017-08-04 18:16:31 +0000465llvm::SyncScope::ID
466TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
467 return C.getOrInsertSyncScopeID(""); /* default sync scope */
468}
469
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000470static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000472/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000473/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000474static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
475 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000476 if (FD->isUnnamedBitfield())
477 return true;
478
479 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000480
Eli Friedman0b3f2012011-11-18 03:47:20 +0000481 // Constant arrays of empty records count as empty, strip them off.
482 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000483 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000484 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
485 if (AT->getSize() == 0)
486 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000487 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000488 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000489
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000490 const RecordType *RT = FT->getAs<RecordType>();
491 if (!RT)
492 return false;
493
494 // C++ record fields are never empty, at least in the Itanium ABI.
495 //
496 // FIXME: We should use a predicate for whether this behavior is true in the
497 // current ABI.
498 if (isa<CXXRecordDecl>(RT->getDecl()))
499 return false;
500
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000501 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000502}
503
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000504/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000505/// fields. Note that a structure with a flexible array member is not
506/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000507static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000508 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000509 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000510 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000511 const RecordDecl *RD = RT->getDecl();
512 if (RD->hasFlexibleArrayMember())
513 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000514
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000515 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000516 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000517 for (const auto &I : CXXRD->bases())
518 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000519 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000520
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000521 for (const auto *I : RD->fields())
522 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000523 return false;
524 return true;
525}
526
527/// isSingleElementStruct - Determine if a structure is a "single
528/// element struct", i.e. it has exactly one non-empty field or
529/// exactly one field which is itself a single element
530/// struct. Structures with flexible array members are never
531/// considered single element structs.
532///
533/// \return The field declaration for the single non-empty field, if
534/// it exists.
535static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000536 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000537 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000538 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000539
540 const RecordDecl *RD = RT->getDecl();
541 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000542 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000543
Craig Topper8a13c412014-05-21 05:09:00 +0000544 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000545
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000546 // If this is a C++ record, check the bases first.
547 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000548 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000549 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000550 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000551 continue;
552
553 // If we already found an element then this isn't a single-element struct.
554 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000555 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000556
557 // If this is non-empty and not a single element struct, the composite
558 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000559 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000560 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000561 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000562 }
563 }
564
565 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000566 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000567 QualType FT = FD->getType();
568
569 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000570 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000571 continue;
572
573 // If we already found an element then this isn't a single-element
574 // struct.
575 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000576 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000577
578 // Treat single element arrays as the element.
579 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
580 if (AT->getSize().getZExtValue() != 1)
581 break;
582 FT = AT->getElementType();
583 }
584
John McCalla1dee5302010-08-22 10:59:02 +0000585 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000586 Found = FT.getTypePtr();
587 } else {
588 Found = isSingleElementStruct(FT, Context);
589 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000590 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000591 }
592 }
593
Eli Friedmanee945342011-11-18 01:25:50 +0000594 // We don't consider a struct a single-element struct if it has
595 // padding beyond the element type.
596 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000597 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000598
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000599 return Found;
600}
601
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000602namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000603Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
604 const ABIArgInfo &AI) {
605 // This default implementation defers to the llvm backend's va_arg
606 // instruction. It can handle only passing arguments directly
607 // (typically only handled in the backend for primitive types), or
608 // aggregates passed indirectly by pointer (NOTE: if the "byval"
609 // flag has ABI impact in the callee, this implementation cannot
610 // work.)
611
612 // Only a few cases are covered here at the moment -- those needed
613 // by the default abi.
614 llvm::Value *Val;
615
616 if (AI.isIndirect()) {
617 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000618 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000619 assert(
620 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000621 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000622
623 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
624 CharUnits TyAlignForABI = TyInfo.second;
625
626 llvm::Type *BaseTy =
627 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
628 llvm::Value *Addr =
629 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
630 return Address(Addr, TyAlignForABI);
631 } else {
632 assert((AI.isDirect() || AI.isExtend()) &&
633 "Unexpected ArgInfo Kind in generic VAArg emitter!");
634
635 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000636 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000637 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000638 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000639 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000640 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000641 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000642 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000643
644 Address Temp = CGF.CreateMemTemp(Ty, "varet");
645 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
646 CGF.Builder.CreateStore(Val, Temp);
647 return Temp;
648 }
649}
650
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000651/// DefaultABIInfo - The default implementation for ABI specific
652/// details. This implementation provides information which results in
653/// self-consistent and sensible LLVM IR generation, but does not
654/// conform to any particular ABI.
655class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000656public:
657 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000658
Chris Lattner458b2aa2010-07-29 02:16:43 +0000659 ABIArgInfo classifyReturnType(QualType RetTy) const;
660 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000661
Craig Topper4f12f102014-03-12 06:41:41 +0000662 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000663 if (!getCXXABI().classifyReturnType(FI))
664 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000665 for (auto &I : FI.arguments())
666 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000667 }
668
John McCall7f416cc2015-09-08 08:05:57 +0000669 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000670 QualType Ty) const override {
671 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
672 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000673};
674
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000675class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
676public:
Chris Lattner2b037972010-07-29 02:01:43 +0000677 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
678 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000679};
680
Chris Lattner458b2aa2010-07-29 02:16:43 +0000681ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000682 Ty = useFirstFieldIfTransparentUnion(Ty);
683
684 if (isAggregateTypeForABI(Ty)) {
685 // Records with non-trivial destructors/copy-constructors should not be
686 // passed by value.
687 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000688 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000689
John McCall7f416cc2015-09-08 08:05:57 +0000690 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000691 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000692
Chris Lattner9723d6c2010-03-11 18:19:55 +0000693 // Treat an enum type as its underlying type.
694 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
695 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000696
Alex Bradburye41a5e22018-01-12 20:08:16 +0000697 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
698 : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000699}
700
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000701ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
702 if (RetTy->isVoidType())
703 return ABIArgInfo::getIgnore();
704
705 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000706 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000707
708 // Treat an enum type as its underlying type.
709 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
710 RetTy = EnumTy->getDecl()->getIntegerType();
711
Alex Bradburye41a5e22018-01-12 20:08:16 +0000712 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
713 : ABIArgInfo::getDirect());
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000714}
715
Derek Schuff09338a22012-09-06 17:37:28 +0000716//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000717// WebAssembly ABI Implementation
718//
719// This is a very simple ABI that relies a lot on DefaultABIInfo.
720//===----------------------------------------------------------------------===//
721
Daniel Dunbara39bab32019-01-03 23:24:50 +0000722class WebAssemblyABIInfo final : public SwiftABIInfo {
723 DefaultABIInfo defaultInfo;
724
Dan Gohmanc2853072015-09-03 22:51:53 +0000725public:
726 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
Daniel Dunbara39bab32019-01-03 23:24:50 +0000727 : SwiftABIInfo(CGT), defaultInfo(CGT) {}
Dan Gohmanc2853072015-09-03 22:51:53 +0000728
729private:
730 ABIArgInfo classifyReturnType(QualType RetTy) const;
731 ABIArgInfo classifyArgumentType(QualType Ty) const;
732
733 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000734 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000735 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000736 void computeInfo(CGFunctionInfo &FI) const override {
737 if (!getCXXABI().classifyReturnType(FI))
738 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
739 for (auto &Arg : FI.arguments())
740 Arg.info = classifyArgumentType(Arg.type);
741 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000742
743 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
744 QualType Ty) const override;
Daniel Dunbara39bab32019-01-03 23:24:50 +0000745
746 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
747 bool asReturnValue) const override {
748 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
749 }
750
751 bool isSwiftErrorInRegister() const override {
752 return false;
753 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000754};
755
756class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
757public:
758 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
759 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
Sam Clegg6fd7d682018-06-25 18:47:32 +0000760
761 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
762 CodeGen::CodeGenModule &CGM) const override {
Dan Gohmanb4323692019-01-24 21:08:30 +0000763 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
764 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
765 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
766 llvm::Function *Fn = cast<llvm::Function>(GV);
767 llvm::AttrBuilder B;
768 B.addAttribute("wasm-import-module", Attr->getImportModuleName());
769 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
770 }
771 }
772
Sam Clegg6fd7d682018-06-25 18:47:32 +0000773 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
774 llvm::Function *Fn = cast<llvm::Function>(GV);
775 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
776 Fn->addFnAttr("no-prototype");
777 }
778 }
Dan Gohmanc2853072015-09-03 22:51:53 +0000779};
780
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000781/// Classify argument of given type \p Ty.
Dan Gohmanc2853072015-09-03 22:51:53 +0000782ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
783 Ty = useFirstFieldIfTransparentUnion(Ty);
784
785 if (isAggregateTypeForABI(Ty)) {
786 // Records with non-trivial destructors/copy-constructors should not be
787 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000788 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000789 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000790 // Ignore empty structs/unions.
791 if (isEmptyRecord(getContext(), Ty, true))
792 return ABIArgInfo::getIgnore();
793 // Lower single-element structs to just pass a regular value. TODO: We
794 // could do reasonable-size multiple-element structs too, using getExpand(),
795 // though watch out for things like bitfields.
796 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
797 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000798 }
799
800 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000801 return defaultInfo.classifyArgumentType(Ty);
Dan Gohmanc2853072015-09-03 22:51:53 +0000802}
803
804ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
805 if (isAggregateTypeForABI(RetTy)) {
806 // Records with non-trivial destructors/copy-constructors should not be
807 // returned by value.
808 if (!getRecordArgABI(RetTy, getCXXABI())) {
809 // Ignore empty structs/unions.
810 if (isEmptyRecord(getContext(), RetTy, true))
811 return ABIArgInfo::getIgnore();
812 // Lower single-element structs to just return a regular value. TODO: We
813 // could do reasonable-size multiple-element structs too, using
814 // ABIArgInfo::getDirect().
815 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
816 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
817 }
818 }
819
820 // Otherwise just do the default thing.
Daniel Dunbara39bab32019-01-03 23:24:50 +0000821 return defaultInfo.classifyReturnType(RetTy);
Dan Gohmanc2853072015-09-03 22:51:53 +0000822}
823
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000824Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
825 QualType Ty) const {
826 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
827 getContext().getTypeInfoInChars(Ty),
828 CharUnits::fromQuantity(4),
829 /*AllowHigherAlign=*/ true);
830}
831
Dan Gohmanc2853072015-09-03 22:51:53 +0000832//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000833// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000834//
835// This is a simplified version of the x86_32 ABI. Arguments and return values
836// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000837//===----------------------------------------------------------------------===//
838
839class PNaClABIInfo : public ABIInfo {
840 public:
841 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
842
843 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000844 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000845
Craig Topper4f12f102014-03-12 06:41:41 +0000846 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000847 Address EmitVAArg(CodeGenFunction &CGF,
848 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000849};
850
851class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
852 public:
853 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
854 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
855};
856
857void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000858 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000859 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
860
Reid Kleckner40ca9132014-05-13 22:05:45 +0000861 for (auto &I : FI.arguments())
862 I.info = classifyArgumentType(I.type);
863}
Derek Schuff09338a22012-09-06 17:37:28 +0000864
John McCall7f416cc2015-09-08 08:05:57 +0000865Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
866 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000867 // The PNaCL ABI is a bit odd, in that varargs don't use normal
868 // function classification. Structs get passed directly for varargs
869 // functions, through a rewriting transform in
870 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
871 // this target to actually support a va_arg instructions with an
872 // aggregate type, unlike other targets.
873 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000874}
875
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000876/// Classify argument of given type \p Ty.
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000877ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000878 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000879 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000880 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
881 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000882 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
883 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000884 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000885 } else if (Ty->isFloatingType()) {
886 // Floating-point types don't go inreg.
887 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000888 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000889
Alex Bradburye41a5e22018-01-12 20:08:16 +0000890 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
891 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000892}
893
894ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
895 if (RetTy->isVoidType())
896 return ABIArgInfo::getIgnore();
897
Eli Benderskye20dad62013-04-04 22:49:35 +0000898 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000899 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000900 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000901
902 // Treat an enum type as its underlying type.
903 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
904 RetTy = EnumTy->getDecl()->getIntegerType();
905
Alex Bradburye41a5e22018-01-12 20:08:16 +0000906 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
907 : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000908}
909
Chad Rosier651c1832013-03-25 21:00:27 +0000910/// IsX86_MMXType - Return true if this is an MMX type.
911bool IsX86_MMXType(llvm::Type *IRType) {
912 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
Bill Wendling5cd41c42010-10-18 03:41:31 +0000913 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
914 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
915 IRType->getScalarSizeInBits() != 64;
916}
917
Jay Foad7c57be32011-07-11 09:56:20 +0000918static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000919 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000920 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000921 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
922 .Cases("y", "&y", "^Ym", true)
923 .Default(false);
924 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000925 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
926 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000927 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000928 }
929
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000930 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000931 }
932
933 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000934 return Ty;
935}
936
Reid Kleckner80944df2014-10-31 22:00:51 +0000937/// Returns true if this type can be passed in SSE registers with the
938/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
939static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
940 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000941 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
942 if (BT->getKind() == BuiltinType::LongDouble) {
943 if (&Context.getTargetInfo().getLongDoubleFormat() ==
944 &llvm::APFloat::x87DoubleExtended())
945 return false;
946 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000947 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000948 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000949 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
950 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
951 // registers specially.
952 unsigned VecSize = Context.getTypeSize(VT);
953 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
954 return true;
955 }
956 return false;
957}
958
959/// Returns true if this aggregate is small enough to be passed in SSE registers
960/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
961static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
962 return NumMembers <= 4;
963}
964
Erich Keane521ed962017-01-05 00:20:51 +0000965/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
966static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
967 auto AI = ABIArgInfo::getDirect(T);
968 AI.setInReg(true);
969 AI.setCanBeFlattened(false);
970 return AI;
971}
972
Chris Lattner0cf24192010-06-28 20:05:43 +0000973//===----------------------------------------------------------------------===//
974// X86-32 ABI Implementation
975//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000976
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000977/// Similar to llvm::CCState, but for Clang.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000978struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000979 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000980
981 unsigned CC;
982 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000983 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000984};
985
Erich Keane521ed962017-01-05 00:20:51 +0000986enum {
987 // Vectorcall only allows the first 6 parameters to be passed in registers.
988 VectorcallMaxParamNumAsReg = 6
989};
990
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000991/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000992class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000993 enum Class {
994 Integer,
995 Float
996 };
997
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000998 static const unsigned MinABIStackAlignInBytes = 4;
999
David Chisnallde3a0692009-08-17 23:08:21 +00001000 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +00001001 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001002 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001003 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +00001004 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001005 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001006
1007 static bool isRegisterSize(unsigned Size) {
1008 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1009 }
1010
Reid Kleckner80944df2014-10-31 22:00:51 +00001011 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1012 // FIXME: Assumes vectorcall is in use.
1013 return isX86VectorTypeForVectorCall(getContext(), Ty);
1014 }
1015
1016 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1017 uint64_t NumMembers) const override {
1018 // FIXME: Assumes vectorcall is in use.
1019 return isX86VectorCallAggregateSmallEnough(NumMembers);
1020 }
1021
Reid Kleckner40ca9132014-05-13 22:05:45 +00001022 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001023
Daniel Dunbar557893d2010-04-21 19:10:51 +00001024 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1025 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +00001026 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1027
John McCall7f416cc2015-09-08 08:05:57 +00001028 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +00001029
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001030 /// Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001031 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001032
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001033 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +00001034 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001035 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +00001036
Fangrui Song6907ce22018-07-30 19:24:48 +00001037 /// Updates the number of available free registers, returns
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001038 /// true if any registers were allocated.
1039 bool updateFreeRegs(QualType Ty, CCState &State) const;
1040
1041 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1042 bool &NeedsPadding) const;
1043 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001044
Reid Kleckner04046052016-05-02 17:41:07 +00001045 bool canExpandIndirectArgument(QualType Ty) const;
1046
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001047 /// Rewrite the function info so that all memory arguments use
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001048 /// inalloca.
1049 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1050
1051 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001052 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001053 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001054 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1055 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001056
Rafael Espindola75419dc2012-07-23 23:30:29 +00001057public:
1058
Craig Topper4f12f102014-03-12 06:41:41 +00001059 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001060 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1061 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001062
Michael Kupersteindc745202015-10-19 07:52:25 +00001063 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1064 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001065 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001066 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Fangrui Song6907ce22018-07-30 19:24:48 +00001067 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001068 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001069 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001070 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001071 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001072
John McCall56331e22018-01-07 06:28:49 +00001073 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00001074 bool asReturnValue) const override {
1075 // LLVM's x86-32 lowering currently only assigns up to three
1076 // integer registers and three fp registers. Oddly, it'll use up to
1077 // four vector registers for vectors, but those can overlap with the
1078 // scalar registers.
1079 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
Fangrui Song6907ce22018-07-30 19:24:48 +00001080 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001081
1082 bool isSwiftErrorInRegister() const override {
1083 // x86-32 lowering does not support passing swifterror in a register.
1084 return false;
1085 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001086};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001087
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001088class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1089public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001090 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1091 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001092 unsigned NumRegisterParameters, bool SoftFloatABI)
1093 : TargetCodeGenInfo(new X86_32ABIInfo(
1094 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1095 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001096
John McCall1fe2a8c2013-06-18 02:46:29 +00001097 static bool isStructReturnInRegABI(
1098 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1099
Eric Christopher162c91c2015-06-05 22:03:00 +00001100 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001101 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001102
Craig Topper4f12f102014-03-12 06:41:41 +00001103 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001104 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001105 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001106 return 4;
1107 }
1108
1109 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001110 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001111
Jay Foad7c57be32011-07-11 09:56:20 +00001112 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001113 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001114 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001115 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1116 }
1117
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001118 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1119 std::string &Constraints,
1120 std::vector<llvm::Type *> &ResultRegTypes,
1121 std::vector<llvm::Type *> &ResultTruncRegTypes,
1122 std::vector<LValue> &ResultRegDests,
1123 std::string &AsmString,
1124 unsigned NumOutputs) const override;
1125
Craig Topper4f12f102014-03-12 06:41:41 +00001126 llvm::Constant *
1127 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001128 unsigned Sig = (0xeb << 0) | // jmp rel8
1129 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001130 ('v' << 16) |
1131 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001132 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1133 }
John McCall01391782016-02-05 21:37:38 +00001134
1135 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1136 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001137 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001138 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001139};
1140
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001141}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001142
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001143/// Rewrite input constraint references after adding some output constraints.
1144/// In the case where there is one output and one input and we add one output,
1145/// we need to replace all operand references greater than or equal to 1:
1146/// mov $0, $1
1147/// mov eax, $1
1148/// The result will be:
1149/// mov $0, $2
1150/// mov eax, $2
1151static void rewriteInputConstraintReferences(unsigned FirstIn,
1152 unsigned NumNewOuts,
1153 std::string &AsmString) {
1154 std::string Buf;
1155 llvm::raw_string_ostream OS(Buf);
1156 size_t Pos = 0;
1157 while (Pos < AsmString.size()) {
1158 size_t DollarStart = AsmString.find('$', Pos);
1159 if (DollarStart == std::string::npos)
1160 DollarStart = AsmString.size();
1161 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1162 if (DollarEnd == std::string::npos)
1163 DollarEnd = AsmString.size();
1164 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1165 Pos = DollarEnd;
1166 size_t NumDollars = DollarEnd - DollarStart;
1167 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1168 // We have an operand reference.
1169 size_t DigitStart = Pos;
1170 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1171 if (DigitEnd == std::string::npos)
1172 DigitEnd = AsmString.size();
1173 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1174 unsigned OperandIndex;
1175 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1176 if (OperandIndex >= FirstIn)
1177 OperandIndex += NumNewOuts;
1178 OS << OperandIndex;
1179 } else {
1180 OS << OperandStr;
1181 }
1182 Pos = DigitEnd;
1183 }
1184 }
1185 AsmString = std::move(OS.str());
1186}
1187
1188/// Add output constraints for EAX:EDX because they are return registers.
1189void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1190 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1191 std::vector<llvm::Type *> &ResultRegTypes,
1192 std::vector<llvm::Type *> &ResultTruncRegTypes,
1193 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1194 unsigned NumOutputs) const {
1195 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1196
1197 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1198 // larger.
1199 if (!Constraints.empty())
1200 Constraints += ',';
1201 if (RetWidth <= 32) {
1202 Constraints += "={eax}";
1203 ResultRegTypes.push_back(CGF.Int32Ty);
1204 } else {
1205 // Use the 'A' constraint for EAX:EDX.
1206 Constraints += "=A";
1207 ResultRegTypes.push_back(CGF.Int64Ty);
1208 }
1209
1210 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1211 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1212 ResultTruncRegTypes.push_back(CoerceTy);
1213
1214 // Coerce the integer by bitcasting the return slot pointer.
1215 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1216 CoerceTy->getPointerTo()));
1217 ResultRegDests.push_back(ReturnSlot);
1218
1219 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1220}
1221
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001222/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001223/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001224bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1225 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001226 uint64_t Size = Context.getTypeSize(Ty);
1227
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001228 // For i386, type must be register sized.
1229 // For the MCU ABI, it only needs to be <= 8-byte
1230 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1231 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001232
1233 if (Ty->isVectorType()) {
1234 // 64- and 128- bit vectors inside structures are not returned in
1235 // registers.
1236 if (Size == 64 || Size == 128)
1237 return false;
1238
1239 return true;
1240 }
1241
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001242 // If this is a builtin, pointer, enum, complex type, member pointer, or
1243 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001244 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001245 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001246 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247 return true;
1248
1249 // Arrays are treated like records.
1250 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001251 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001252
1253 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001254 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001255 if (!RT) return false;
1256
Anders Carlsson40446e82010-01-27 03:25:19 +00001257 // FIXME: Traverse bases here too.
1258
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001259 // Structure types are passed in register if all fields would be
1260 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001261 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001262 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001263 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001264 continue;
1265
1266 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001267 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001268 return false;
1269 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001270 return true;
1271}
1272
Reid Kleckner04046052016-05-02 17:41:07 +00001273static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1274 // Treat complex types as the element type.
1275 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1276 Ty = CTy->getElementType();
1277
1278 // Check for a type which we know has a simple scalar argument-passing
1279 // convention without any padding. (We're specifically looking for 32
1280 // and 64-bit integer and integer-equivalents, float, and double.)
1281 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1282 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1283 return false;
1284
1285 uint64_t Size = Context.getTypeSize(Ty);
1286 return Size == 32 || Size == 64;
1287}
1288
Reid Kleckner791bbf62017-01-13 17:18:19 +00001289static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1290 uint64_t &Size) {
1291 for (const auto *FD : RD->fields()) {
1292 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1293 // argument is smaller than 32-bits, expanding the struct will create
1294 // alignment padding.
1295 if (!is32Or64BitBasicType(FD->getType(), Context))
1296 return false;
1297
1298 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1299 // how to expand them yet, and the predicate for telling if a bitfield still
1300 // counts as "basic" is more complicated than what we were doing previously.
1301 if (FD->isBitField())
1302 return false;
1303
1304 Size += Context.getTypeSize(FD->getType());
1305 }
1306 return true;
1307}
1308
1309static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1310 uint64_t &Size) {
1311 // Don't do this if there are any non-empty bases.
1312 for (const CXXBaseSpecifier &Base : RD->bases()) {
1313 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1314 Size))
1315 return false;
1316 }
1317 if (!addFieldSizes(Context, RD, Size))
1318 return false;
1319 return true;
1320}
1321
Reid Kleckner04046052016-05-02 17:41:07 +00001322/// Test whether an argument type which is to be passed indirectly (on the
1323/// stack) would have the equivalent layout if it was expanded into separate
1324/// arguments. If so, we prefer to do the latter to avoid inhibiting
1325/// optimizations.
1326bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1327 // We can only expand structure types.
1328 const RecordType *RT = Ty->getAs<RecordType>();
1329 if (!RT)
1330 return false;
1331 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001332 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001333 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001334 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001335 // On non-Windows, we have to conservatively match our old bitcode
1336 // prototypes in order to be ABI-compatible at the bitcode level.
1337 if (!CXXRD->isCLike())
1338 return false;
1339 } else {
1340 // Don't do this for dynamic classes.
1341 if (CXXRD->isDynamicClass())
1342 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001343 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001344 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001345 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001346 } else {
1347 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001348 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001349 }
1350
1351 // We can do this if there was no alignment padding.
1352 return Size == getContext().getTypeSize(Ty);
1353}
1354
John McCall7f416cc2015-09-08 08:05:57 +00001355ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001356 // If the return value is indirect, then the hidden argument is consuming one
1357 // integer register.
1358 if (State.FreeRegs) {
1359 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001360 if (!IsMCUABI)
1361 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001362 }
John McCall7f416cc2015-09-08 08:05:57 +00001363 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001364}
1365
Eric Christopher7565e0d2015-05-29 23:09:49 +00001366ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1367 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001368 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001369 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001370
Reid Kleckner80944df2014-10-31 22:00:51 +00001371 const Type *Base = nullptr;
1372 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001373 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1374 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001375 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1376 // The LLVM struct type for such an aggregate should lower properly.
1377 return ABIArgInfo::getDirect();
1378 }
1379
Chris Lattner458b2aa2010-07-29 02:16:43 +00001380 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001381 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001382 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001383 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001384
1385 // 128-bit vectors are a special case; they are returned in
1386 // registers and we need to make sure to pick a type the LLVM
1387 // backend will like.
1388 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001389 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001390 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001391
1392 // Always return in register if it fits in a general purpose
1393 // register, or if it is 64 bits and has a single element.
1394 if ((Size == 8 || Size == 16 || Size == 32) ||
1395 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001396 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001397 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001398
John McCall7f416cc2015-09-08 08:05:57 +00001399 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400 }
1401
1402 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001403 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001404
John McCalla1dee5302010-08-22 10:59:02 +00001405 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001406 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001407 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001408 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001409 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001410 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001411
David Chisnallde3a0692009-08-17 23:08:21 +00001412 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001413 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001414 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001415
Denis Zobnin380b2242016-02-11 11:26:03 +00001416 // Ignore empty structs/unions.
1417 if (isEmptyRecord(getContext(), RetTy, true))
1418 return ABIArgInfo::getIgnore();
1419
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001420 // Small structures which are register sized are generally returned
1421 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001422 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001423 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001424
1425 // As a special-case, if the struct is a "single-element" struct, and
1426 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001427 // floating-point register. (MSVC does not apply this special case.)
1428 // We apply a similar transformation for pointer types to improve the
1429 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001430 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001431 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001432 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001433 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1434
1435 // FIXME: We should be able to narrow this integer in cases with dead
1436 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001437 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001438 }
1439
John McCall7f416cc2015-09-08 08:05:57 +00001440 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001441 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001442
Chris Lattner458b2aa2010-07-29 02:16:43 +00001443 // Treat an enum type as its underlying type.
1444 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1445 RetTy = EnumTy->getDecl()->getIntegerType();
1446
Alex Bradburye41a5e22018-01-12 20:08:16 +00001447 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1448 : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001449}
1450
Eli Friedman7919bea2012-06-05 19:40:46 +00001451static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1452 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1453}
1454
Daniel Dunbared23de32010-09-16 20:42:00 +00001455static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1456 const RecordType *RT = Ty->getAs<RecordType>();
1457 if (!RT)
1458 return 0;
1459 const RecordDecl *RD = RT->getDecl();
1460
1461 // If this is a C++ record, check the bases first.
1462 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001463 for (const auto &I : CXXRD->bases())
1464 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001465 return false;
1466
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001467 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001468 QualType FT = i->getType();
1469
Eli Friedman7919bea2012-06-05 19:40:46 +00001470 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001471 return true;
1472
1473 if (isRecordWithSSEVectorType(Context, FT))
1474 return true;
1475 }
1476
1477 return false;
1478}
1479
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001480unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1481 unsigned Align) const {
1482 // Otherwise, if the alignment is less than or equal to the minimum ABI
1483 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001484 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001485 return 0; // Use default alignment.
1486
1487 // On non-Darwin, the stack type alignment is always 4.
1488 if (!IsDarwinVectorABI) {
1489 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001490 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001491 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001492
Daniel Dunbared23de32010-09-16 20:42:00 +00001493 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001494 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1495 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001496 return 16;
1497
1498 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001499}
1500
Rafael Espindola703c47f2012-10-19 05:04:37 +00001501ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001502 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001503 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001504 if (State.FreeRegs) {
1505 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001506 if (!IsMCUABI)
1507 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001508 }
John McCall7f416cc2015-09-08 08:05:57 +00001509 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001510 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001511
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001512 // Compute the byval alignment.
1513 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1514 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1515 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001516 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001517
1518 // If the stack alignment is less than the type alignment, realign the
1519 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001520 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001521 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1522 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001523}
1524
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001525X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1526 const Type *T = isSingleElementStruct(Ty, getContext());
1527 if (!T)
1528 T = Ty.getTypePtr();
1529
1530 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1531 BuiltinType::Kind K = BT->getKind();
1532 if (K == BuiltinType::Float || K == BuiltinType::Double)
1533 return Float;
1534 }
1535 return Integer;
1536}
1537
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001538bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001539 if (!IsSoftFloatABI) {
1540 Class C = classify(Ty);
1541 if (C == Float)
1542 return false;
1543 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001544
Rafael Espindola077dd592012-10-24 01:58:58 +00001545 unsigned Size = getContext().getTypeSize(Ty);
1546 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001547
1548 if (SizeInRegs == 0)
1549 return false;
1550
Michael Kuperstein68901882015-10-25 08:18:20 +00001551 if (!IsMCUABI) {
1552 if (SizeInRegs > State.FreeRegs) {
1553 State.FreeRegs = 0;
1554 return false;
1555 }
1556 } else {
1557 // The MCU psABI allows passing parameters in-reg even if there are
1558 // earlier parameters that are passed on the stack. Also,
1559 // it does not allow passing >8-byte structs in-register,
1560 // even if there are 3 free registers available.
1561 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1562 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001563 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001564
Reid Kleckner661f35b2014-01-18 01:12:41 +00001565 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001566 return true;
1567}
1568
Fangrui Song6907ce22018-07-30 19:24:48 +00001569bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001570 bool &InReg,
1571 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001572 // On Windows, aggregates other than HFAs are never passed in registers, and
1573 // they do not consume register slots. Homogenous floating-point aggregates
1574 // (HFAs) have already been dealt with at this point.
1575 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1576 return false;
1577
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001578 NeedsPadding = false;
1579 InReg = !IsMCUABI;
1580
1581 if (!updateFreeRegs(Ty, State))
1582 return false;
1583
1584 if (IsMCUABI)
1585 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001586
Reid Kleckner80944df2014-10-31 22:00:51 +00001587 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001588 State.CC == llvm::CallingConv::X86_VectorCall ||
1589 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001590 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001591 NeedsPadding = true;
1592
Rafael Espindola077dd592012-10-24 01:58:58 +00001593 return false;
1594 }
1595
Rafael Espindola703c47f2012-10-19 05:04:37 +00001596 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001597}
1598
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001599bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1600 if (!updateFreeRegs(Ty, State))
1601 return false;
1602
1603 if (IsMCUABI)
1604 return false;
1605
1606 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001607 State.CC == llvm::CallingConv::X86_VectorCall ||
1608 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001609 if (getContext().getTypeSize(Ty) > 32)
1610 return false;
1611
Fangrui Song6907ce22018-07-30 19:24:48 +00001612 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001613 Ty->isReferenceType());
1614 }
1615
1616 return true;
1617}
1618
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001619ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1620 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001621 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001622
Reid Klecknerb1be6832014-11-15 01:41:41 +00001623 Ty = useFirstFieldIfTransparentUnion(Ty);
1624
Reid Kleckner80944df2014-10-31 22:00:51 +00001625 // Check with the C++ ABI first.
1626 const RecordType *RT = Ty->getAs<RecordType>();
1627 if (RT) {
1628 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1629 if (RAA == CGCXXABI::RAA_Indirect) {
1630 return getIndirectResult(Ty, false, State);
1631 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1632 // The field index doesn't matter, we'll fix it up later.
1633 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1634 }
1635 }
1636
Erich Keane4bd39302017-06-21 16:37:22 +00001637 // Regcall uses the concept of a homogenous vector aggregate, similar
1638 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001639 const Type *Base = nullptr;
1640 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001641 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001642 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001643
Erich Keane4bd39302017-06-21 16:37:22 +00001644 if (State.FreeSSERegs >= NumElts) {
1645 State.FreeSSERegs -= NumElts;
1646 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001647 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001648 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001649 }
Erich Keane4bd39302017-06-21 16:37:22 +00001650 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001651 }
1652
1653 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001654 // Structures with flexible arrays are always indirect.
1655 // FIXME: This should not be byval!
1656 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1657 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001658
Reid Kleckner04046052016-05-02 17:41:07 +00001659 // Ignore empty structs/unions on non-Windows.
1660 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001661 return ABIArgInfo::getIgnore();
1662
Rafael Espindolafad28de2012-10-24 01:59:00 +00001663 llvm::LLVMContext &LLVMContext = getVMContext();
1664 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001665 bool NeedsPadding = false;
1666 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001667 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001668 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001669 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001670 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001671 if (InReg)
1672 return ABIArgInfo::getDirectInReg(Result);
1673 else
1674 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001675 }
Craig Topper8a13c412014-05-21 05:09:00 +00001676 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001677
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001678 // Expand small (<= 128-bit) record types when we know that the stack layout
1679 // of those arguments will match the struct. This is important because the
1680 // LLVM backend isn't smart enough to remove byval, which inhibits many
1681 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001682 // Don't do this for the MCU if there are still free integer registers
1683 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001684 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1685 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001686 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001687 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001688 State.CC == llvm::CallingConv::X86_VectorCall ||
1689 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001690 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001691
Reid Kleckner661f35b2014-01-18 01:12:41 +00001692 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001693 }
1694
Chris Lattnerd774ae92010-08-26 20:05:13 +00001695 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001696 // On Darwin, some vectors are passed in memory, we handle this by passing
1697 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001698 if (IsDarwinVectorABI) {
1699 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001700 if ((Size == 8 || Size == 16 || Size == 32) ||
1701 (Size == 64 && VT->getNumElements() == 1))
1702 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1703 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001704 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001705
Chad Rosier651c1832013-03-25 21:00:27 +00001706 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1707 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001708
Chris Lattnerd774ae92010-08-26 20:05:13 +00001709 return ABIArgInfo::getDirect();
1710 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001711
1712
Chris Lattner458b2aa2010-07-29 02:16:43 +00001713 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1714 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001715
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001716 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001717
1718 if (Ty->isPromotableIntegerType()) {
1719 if (InReg)
Alex Bradburye41a5e22018-01-12 20:08:16 +00001720 return ABIArgInfo::getExtendInReg(Ty);
1721 return ABIArgInfo::getExtend(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001722 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001723
Rafael Espindola703c47f2012-10-19 05:04:37 +00001724 if (InReg)
1725 return ABIArgInfo::getDirectInReg();
1726 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001727}
1728
Erich Keane521ed962017-01-05 00:20:51 +00001729void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1730 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001731 // Vectorcall x86 works subtly different than in x64, so the format is
1732 // a bit different than the x64 version. First, all vector types (not HVAs)
1733 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1734 // This differs from the x64 implementation, where the first 6 by INDEX get
1735 // registers.
1736 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1737 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1738 // first take up the remaining YMM/XMM registers. If insufficient registers
1739 // remain but an integer register (ECX/EDX) is available, it will be passed
1740 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001741 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001742 // First pass do all the vector types.
1743 const Type *Base = nullptr;
1744 uint64_t NumElts = 0;
1745 const QualType& Ty = I.type;
1746 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1747 isHomogeneousAggregate(Ty, Base, NumElts)) {
1748 if (State.FreeSSERegs >= NumElts) {
1749 State.FreeSSERegs -= NumElts;
1750 I.info = ABIArgInfo::getDirect();
1751 } else {
1752 I.info = classifyArgumentType(Ty, State);
1753 }
1754 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1755 }
Erich Keane521ed962017-01-05 00:20:51 +00001756 }
Erich Keane4bd39302017-06-21 16:37:22 +00001757
Erich Keane521ed962017-01-05 00:20:51 +00001758 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001759 // Second pass, do the rest!
1760 const Type *Base = nullptr;
1761 uint64_t NumElts = 0;
1762 const QualType& Ty = I.type;
1763 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1764
1765 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1766 // Assign true HVAs (non vector/native FP types).
1767 if (State.FreeSSERegs >= NumElts) {
1768 State.FreeSSERegs -= NumElts;
1769 I.info = getDirectX86Hva();
1770 } else {
1771 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1772 }
1773 } else if (!IsHva) {
1774 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1775 I.info = classifyArgumentType(Ty, State);
1776 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1777 }
Erich Keane521ed962017-01-05 00:20:51 +00001778 }
1779}
1780
Rafael Espindolaa6472962012-07-24 00:01:07 +00001781void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001782 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001783 if (IsMCUABI)
1784 State.FreeRegs = 3;
1785 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001786 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001787 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1788 State.FreeRegs = 2;
1789 State.FreeSSERegs = 6;
1790 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001791 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001792 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1793 State.FreeRegs = 5;
1794 State.FreeSSERegs = 8;
1795 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001796 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001797
Akira Hatanakad791e922018-03-19 17:38:40 +00001798 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001799 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001800 } else if (FI.getReturnInfo().isIndirect()) {
1801 // The C++ ABI is not aware of register usage, so we have to check if the
1802 // return value was sret and put it in a register ourselves if appropriate.
1803 if (State.FreeRegs) {
1804 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001805 if (!IsMCUABI)
1806 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001807 }
1808 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001809
Peter Collingbournef7706832014-12-12 23:41:25 +00001810 // The chain argument effectively gives us another free register.
1811 if (FI.isChainCall())
1812 ++State.FreeRegs;
1813
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001814 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001815 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1816 computeVectorCallArgs(FI, State, UsedInAlloca);
1817 } else {
1818 // If not vectorcall, revert to normal behavior.
1819 for (auto &I : FI.arguments()) {
1820 I.info = classifyArgumentType(I.type, State);
1821 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1822 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001823 }
1824
1825 // If we needed to use inalloca for any argument, do a second pass and rewrite
1826 // all the memory arguments to use inalloca.
1827 if (UsedInAlloca)
1828 rewriteWithInAlloca(FI);
1829}
1830
1831void
1832X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001833 CharUnits &StackOffset, ABIArgInfo &Info,
1834 QualType Type) const {
1835 // Arguments are always 4-byte-aligned.
1836 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1837
1838 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001839 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1840 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001841 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001842
John McCall7f416cc2015-09-08 08:05:57 +00001843 // Insert padding bytes to respect alignment.
1844 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001845 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001846 if (StackOffset != FieldEnd) {
1847 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001848 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001849 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001850 FrameFields.push_back(Ty);
1851 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001852}
1853
Reid Kleckner852361d2014-07-26 00:12:26 +00001854static bool isArgInAlloca(const ABIArgInfo &Info) {
1855 // Leave ignored and inreg arguments alone.
1856 switch (Info.getKind()) {
1857 case ABIArgInfo::InAlloca:
1858 return true;
1859 case ABIArgInfo::Indirect:
1860 assert(Info.getIndirectByVal());
1861 return true;
1862 case ABIArgInfo::Ignore:
1863 return false;
1864 case ABIArgInfo::Direct:
1865 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001866 if (Info.getInReg())
1867 return false;
1868 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001869 case ABIArgInfo::Expand:
1870 case ABIArgInfo::CoerceAndExpand:
1871 // These are aggregate types which are never passed in registers when
1872 // inalloca is involved.
1873 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001874 }
1875 llvm_unreachable("invalid enum");
1876}
1877
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001878void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1879 assert(IsWin32StructABI && "inalloca only supported on win32");
1880
1881 // Build a packed struct type for all of the arguments in memory.
1882 SmallVector<llvm::Type *, 6> FrameFields;
1883
John McCall7f416cc2015-09-08 08:05:57 +00001884 // The stack alignment is always 4.
1885 CharUnits StackAlign = CharUnits::fromQuantity(4);
1886
1887 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001888 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1889
1890 // Put 'this' into the struct before 'sret', if necessary.
1891 bool IsThisCall =
1892 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1893 ABIArgInfo &Ret = FI.getReturnInfo();
1894 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1895 isArgInAlloca(I->info)) {
1896 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1897 ++I;
1898 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001899
1900 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001901 if (Ret.isIndirect() && !Ret.getInReg()) {
1902 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1903 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001904 // On Windows, the hidden sret parameter is always returned in eax.
1905 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001906 }
1907
1908 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001909 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001910 ++I;
1911
1912 // Put arguments passed in memory into the struct.
1913 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001914 if (isArgInAlloca(I->info))
1915 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001916 }
1917
1918 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001919 /*isPacked=*/true),
1920 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001921}
1922
John McCall7f416cc2015-09-08 08:05:57 +00001923Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1924 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001925
John McCall7f416cc2015-09-08 08:05:57 +00001926 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001927
John McCall7f416cc2015-09-08 08:05:57 +00001928 // x86-32 changes the alignment of certain arguments on the stack.
1929 //
1930 // Just messing with TypeInfo like this works because we never pass
1931 // anything indirectly.
1932 TypeInfo.second = CharUnits::fromQuantity(
1933 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001934
John McCall7f416cc2015-09-08 08:05:57 +00001935 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1936 TypeInfo, CharUnits::fromQuantity(4),
1937 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001938}
1939
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001940bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1941 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1942 assert(Triple.getArch() == llvm::Triple::x86);
1943
1944 switch (Opts.getStructReturnConvention()) {
1945 case CodeGenOptions::SRCK_Default:
1946 break;
1947 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1948 return false;
1949 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1950 return true;
1951 }
1952
Michael Kupersteind749f232015-10-27 07:46:22 +00001953 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001954 return true;
1955
1956 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001957 case llvm::Triple::DragonFly:
1958 case llvm::Triple::FreeBSD:
1959 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001960 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001961 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001962 default:
1963 return false;
1964 }
1965}
1966
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001967void X86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001968 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1969 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001970 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001971 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001972 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001973 llvm::Function *Fn = cast<llvm::Function>(GV);
Erich Keaneb127a3942018-04-19 14:27:05 +00001974 Fn->addFnAttr("stackrealign");
Charles Davis4ea31ab2010-02-13 15:54:06 +00001975 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001976 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1977 llvm::Function *Fn = cast<llvm::Function>(GV);
1978 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1979 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001980 }
1981}
1982
John McCallbeec5a02010-03-06 00:35:14 +00001983bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1984 CodeGen::CodeGenFunction &CGF,
1985 llvm::Value *Address) const {
1986 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001987
Chris Lattnerece04092012-02-07 00:39:47 +00001988 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001989
John McCallbeec5a02010-03-06 00:35:14 +00001990 // 0-7 are the eight integer registers; the order is different
1991 // on Darwin (for EH), but the range is the same.
1992 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001993 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001994
John McCallc8e01702013-04-16 22:48:15 +00001995 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001996 // 12-16 are st(0..4). Not sure why we stop at 4.
1997 // These have size 16, which is sizeof(long double) on
1998 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001999 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00002000 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002001
John McCallbeec5a02010-03-06 00:35:14 +00002002 } else {
2003 // 9 is %eflags, which doesn't get a size on Darwin for some
2004 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00002005 Builder.CreateAlignedStore(
2006 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2007 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00002008
2009 // 11-16 are st(0..5). Not sure why we stop at 5.
2010 // These have size 12, which is sizeof(long double) on
2011 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00002012 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00002013 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2014 }
John McCallbeec5a02010-03-06 00:35:14 +00002015
2016 return false;
2017}
2018
Chris Lattner0cf24192010-06-28 20:05:43 +00002019//===----------------------------------------------------------------------===//
2020// X86-64 ABI Implementation
2021//===----------------------------------------------------------------------===//
2022
2023
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002024namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002025/// The AVX ABI level for X86 targets.
2026enum class X86AVXABILevel {
2027 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002028 AVX,
2029 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002030};
2031
2032/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2033static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2034 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002035 case X86AVXABILevel::AVX512:
2036 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002037 case X86AVXABILevel::AVX:
2038 return 256;
2039 case X86AVXABILevel::None:
2040 return 128;
2041 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002042 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002043}
2044
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002045/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002046class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002047 enum Class {
2048 Integer = 0,
2049 SSE,
2050 SSEUp,
2051 X87,
2052 X87Up,
2053 ComplexX87,
2054 NoClass,
2055 Memory
2056 };
2057
2058 /// merge - Implement the X86_64 ABI merging algorithm.
2059 ///
2060 /// Merge an accumulating classification \arg Accum with a field
2061 /// classification \arg Field.
2062 ///
2063 /// \param Accum - The accumulating classification. This should
2064 /// always be either NoClass or the result of a previous merge
2065 /// call. In addition, this should never be Memory (the caller
2066 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002067 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002068
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002069 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2070 ///
2071 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2072 /// final MEMORY or SSE classes when necessary.
2073 ///
2074 /// \param AggregateSize - The size of the current aggregate in
2075 /// the classification process.
2076 ///
2077 /// \param Lo - The classification for the parts of the type
2078 /// residing in the low word of the containing object.
2079 ///
2080 /// \param Hi - The classification for the parts of the type
2081 /// residing in the higher words of the containing object.
2082 ///
2083 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2084
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002085 /// classify - Determine the x86_64 register classes in which the
2086 /// given type T should be passed.
2087 ///
2088 /// \param Lo - The classification for the parts of the type
2089 /// residing in the low word of the containing object.
2090 ///
2091 /// \param Hi - The classification for the parts of the type
2092 /// residing in the high word of the containing object.
2093 ///
2094 /// \param OffsetBase - The bit offset of this type in the
2095 /// containing object. Some parameters are classified different
2096 /// depending on whether they straddle an eightbyte boundary.
2097 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002098 /// \param isNamedArg - Whether the argument in question is a "named"
2099 /// argument, as used in AMD64-ABI 3.5.7.
2100 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101 /// If a word is unused its result will be NoClass; if a type should
2102 /// be passed in Memory then at least the classification of \arg Lo
2103 /// will be Memory.
2104 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002105 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002106 ///
2107 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2108 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002109 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2110 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002111
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002112 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002113 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2114 unsigned IROffset, QualType SourceTy,
2115 unsigned SourceOffset) const;
2116 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2117 unsigned IROffset, QualType SourceTy,
2118 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002119
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002120 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002121 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002122 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002123
2124 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002125 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002126 ///
2127 /// \param freeIntRegs - The number of free integer registers remaining
2128 /// available.
2129 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002130
Chris Lattner458b2aa2010-07-29 02:16:43 +00002131 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002132
Erich Keane757d3172016-11-02 18:29:35 +00002133 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2134 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002135 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002136
Erich Keane757d3172016-11-02 18:29:35 +00002137 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2138 unsigned &NeededSSE) const;
2139
2140 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2141 unsigned &NeededSSE) const;
2142
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002143 bool IsIllegalVectorType(QualType Ty) const;
2144
John McCalle0fda732011-04-21 01:20:55 +00002145 /// The 0.98 ABI revision clarified a lot of ambiguities,
2146 /// unfortunately in ways that were not always consistent with
2147 /// certain previous compilers. In particular, platforms which
2148 /// required strict binary compatibility with older versions of GCC
2149 /// may need to exempt themselves.
2150 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002151 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002152 }
2153
Richard Smithf667ad52017-08-26 01:04:35 +00002154 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2155 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002156 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002157 // Clang <= 3.8 did not do this.
Akira Hatanakafcbe17c2018-03-28 21:13:14 +00002158 if (getContext().getLangOpts().getClangABICompat() <=
2159 LangOptions::ClangABI::Ver3_8)
Richard Smithf667ad52017-08-26 01:04:35 +00002160 return false;
2161
David Majnemere2ae2282016-03-04 05:26:16 +00002162 const llvm::Triple &Triple = getTarget().getTriple();
2163 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2164 return false;
2165 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2166 return false;
2167 return true;
2168 }
2169
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002170 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002171 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2172 // 64-bit hardware.
2173 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002174
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002175public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002176 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002177 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002178 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002179 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002180
John McCalla729c622012-02-17 03:33:10 +00002181 bool isPassedUsingAVXType(QualType type) const {
2182 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002183 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002184 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2185 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002186 if (info.isDirect()) {
2187 llvm::Type *ty = info.getCoerceToType();
2188 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2189 return (vectorTy->getBitWidth() > 128);
2190 }
2191 return false;
2192 }
2193
Craig Topper4f12f102014-03-12 06:41:41 +00002194 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002195
John McCall7f416cc2015-09-08 08:05:57 +00002196 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2197 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002198 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2199 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002200
2201 bool has64BitPointers() const {
2202 return Has64BitPointers;
2203 }
John McCall12f23522016-04-04 18:33:08 +00002204
John McCall56331e22018-01-07 06:28:49 +00002205 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00002206 bool asReturnValue) const override {
2207 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
Fangrui Song6907ce22018-07-30 19:24:48 +00002208 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002209 bool isSwiftErrorInRegister() const override {
2210 return true;
2211 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002212};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002213
Chris Lattner04dc9572010-08-31 16:44:54 +00002214/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002215class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002216public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002217 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002218 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002219 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002220
Craig Topper4f12f102014-03-12 06:41:41 +00002221 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002222
John McCall7f416cc2015-09-08 08:05:57 +00002223 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2224 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002225
2226 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2227 // FIXME: Assumes vectorcall is in use.
2228 return isX86VectorTypeForVectorCall(getContext(), Ty);
2229 }
2230
2231 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2232 uint64_t NumMembers) const override {
2233 // FIXME: Assumes vectorcall is in use.
2234 return isX86VectorCallAggregateSmallEnough(NumMembers);
2235 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002236
John McCall56331e22018-01-07 06:28:49 +00002237 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002238 bool asReturnValue) const override {
2239 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2240 }
2241
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002242 bool isSwiftErrorInRegister() const override {
2243 return true;
2244 }
2245
Reid Kleckner11a17192015-10-28 22:29:52 +00002246private:
Erich Keane521ed962017-01-05 00:20:51 +00002247 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2248 bool IsVectorCall, bool IsRegCall) const;
2249 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2250 const ABIArgInfo &current) const;
2251 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2252 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002253
Erich Keane521ed962017-01-05 00:20:51 +00002254 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002255};
2256
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002257class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2258public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002259 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002260 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002261
John McCalla729c622012-02-17 03:33:10 +00002262 const X86_64ABIInfo &getABIInfo() const {
2263 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2264 }
2265
Craig Topper4f12f102014-03-12 06:41:41 +00002266 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002267 return 7;
2268 }
2269
2270 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002271 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002272 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002273
John McCall943fae92010-05-27 06:19:26 +00002274 // 0-15 are the 16 integer registers.
2275 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002276 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002277 return false;
2278 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002279
Jay Foad7c57be32011-07-11 09:56:20 +00002280 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002281 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002282 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002283 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2284 }
2285
John McCalla729c622012-02-17 03:33:10 +00002286 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002287 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002288 // The default CC on x86-64 sets %al to the number of SSA
2289 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002290 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002291 // that when AVX types are involved: the ABI explicitly states it is
2292 // undefined, and it doesn't work in practice because of how the ABI
2293 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002294 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002295 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002296 for (CallArgList::const_iterator
2297 it = args.begin(), ie = args.end(); it != ie; ++it) {
2298 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2299 HasAVXType = true;
2300 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002301 }
2302 }
John McCalla729c622012-02-17 03:33:10 +00002303
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002304 if (!HasAVXType)
2305 return true;
2306 }
John McCallcbc038a2011-09-21 08:08:30 +00002307
John McCalla729c622012-02-17 03:33:10 +00002308 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002309 }
2310
Craig Topper4f12f102014-03-12 06:41:41 +00002311 llvm::Constant *
2312 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002313 unsigned Sig = (0xeb << 0) | // jmp rel8
2314 (0x06 << 8) | // .+0x08
2315 ('v' << 16) |
2316 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002317 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2318 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002319
2320 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002321 CodeGen::CodeGenModule &CGM) const override {
2322 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002323 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002324 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002325 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002326 llvm::Function *Fn = cast<llvm::Function>(GV);
2327 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002328 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002329 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2330 llvm::Function *Fn = cast<llvm::Function>(GV);
2331 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2332 }
2333 }
2334 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002335};
2336
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002337class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2338public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002339 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2340 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002341
2342 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002343 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002344 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002345 // If the argument contains a space, enclose it in quotes.
2346 if (Lib.find(" ") != StringRef::npos)
2347 Opt += "\"" + Lib.str() + "\"";
2348 else
2349 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002350 }
2351};
2352
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002353static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002354 // If the argument does not end in .lib, automatically add the suffix.
2355 // If the argument contains a space, enclose it in quotes.
2356 // This matches the behavior of MSVC.
2357 bool Quote = (Lib.find(" ") != StringRef::npos);
2358 std::string ArgStr = Quote ? "\"" : "";
2359 ArgStr += Lib;
Martin Storsjo3cd67c92018-10-10 09:01:00 +00002360 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002361 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002362 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002363 return ArgStr;
2364}
2365
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002366class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2367public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002368 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002369 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2370 unsigned NumRegisterParameters)
2371 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002372 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002373
Eric Christopher162c91c2015-06-05 22:03:00 +00002374 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002375 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002376
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002377 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002378 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002379 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002380 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002381 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002382
2383 void getDetectMismatchOption(llvm::StringRef Name,
2384 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002385 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002386 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002387 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002388};
2389
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002390static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2391 CodeGen::CodeGenModule &CGM) {
2392 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002393
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002394 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
Eric Christopher7565e0d2015-05-29 23:09:49 +00002395 Fn->addFnAttr("stack-probe-size",
2396 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002397 if (CGM.getCodeGenOpts().NoStackArgProbe)
2398 Fn->addFnAttr("no-stack-arg-probe");
Hans Wennborg77dc2362015-01-20 19:45:50 +00002399 }
2400}
2401
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002402void WinX86_32TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002403 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2404 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2405 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002406 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002407 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002408}
2409
Chris Lattner04dc9572010-08-31 16:44:54 +00002410class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2411public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002412 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2413 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002414 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002415
Eric Christopher162c91c2015-06-05 22:03:00 +00002416 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002417 CodeGen::CodeGenModule &CGM) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002418
Craig Topper4f12f102014-03-12 06:41:41 +00002419 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002420 return 7;
2421 }
2422
2423 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002424 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002425 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002426
Chris Lattner04dc9572010-08-31 16:44:54 +00002427 // 0-15 are the 16 integer registers.
2428 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002429 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002430 return false;
2431 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002432
2433 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002434 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002435 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002436 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002437 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002438
2439 void getDetectMismatchOption(llvm::StringRef Name,
2440 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002441 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002442 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002443 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002444};
2445
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002446void WinX86_64TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002447 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2448 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2449 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002450 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002451 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002452 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
Erich Keaneb127a3942018-04-19 14:27:05 +00002453 llvm::Function *Fn = cast<llvm::Function>(GV);
2454 Fn->addFnAttr("stackrealign");
Erich Keanebb9c7042017-08-30 21:17:40 +00002455 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002456 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2457 llvm::Function *Fn = cast<llvm::Function>(GV);
2458 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2459 }
2460 }
2461
Hans Wennborgd43f40d2018-02-23 13:47:36 +00002462 addStackProbeTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002463}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002464}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002465
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002466void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2467 Class &Hi) const {
2468 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2469 //
2470 // (a) If one of the classes is Memory, the whole argument is passed in
2471 // memory.
2472 //
2473 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2474 // memory.
2475 //
2476 // (c) If the size of the aggregate exceeds two eightbytes and the first
2477 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2478 // argument is passed in memory. NOTE: This is necessary to keep the
2479 // ABI working for processors that don't support the __m256 type.
2480 //
2481 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2482 //
2483 // Some of these are enforced by the merging logic. Others can arise
2484 // only with unions; for example:
2485 // union { _Complex double; unsigned; }
2486 //
2487 // Note that clauses (b) and (c) were added in 0.98.
2488 //
2489 if (Hi == Memory)
2490 Lo = Memory;
2491 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2492 Lo = Memory;
2493 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2494 Lo = Memory;
2495 if (Hi == SSEUp && Lo != SSE)
2496 Hi = SSE;
2497}
2498
Chris Lattnerd776fb12010-06-28 21:43:59 +00002499X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002500 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2501 // classified recursively so that always two fields are
2502 // considered. The resulting class is calculated according to
2503 // the classes of the fields in the eightbyte:
2504 //
2505 // (a) If both classes are equal, this is the resulting class.
2506 //
2507 // (b) If one of the classes is NO_CLASS, the resulting class is
2508 // the other class.
2509 //
2510 // (c) If one of the classes is MEMORY, the result is the MEMORY
2511 // class.
2512 //
2513 // (d) If one of the classes is INTEGER, the result is the
2514 // INTEGER.
2515 //
2516 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2517 // MEMORY is used as class.
2518 //
2519 // (f) Otherwise class SSE is used.
2520
2521 // Accum should never be memory (we should have returned) or
2522 // ComplexX87 (because this cannot be passed in a structure).
2523 assert((Accum != Memory && Accum != ComplexX87) &&
2524 "Invalid accumulated classification during merge.");
2525 if (Accum == Field || Field == NoClass)
2526 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002527 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002528 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002529 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002530 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002531 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002533 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2534 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002535 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002536 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537}
2538
Chris Lattner5c740f12010-06-30 19:14:05 +00002539void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002540 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002541 // FIXME: This code can be simplified by introducing a simple value class for
2542 // Class pairs with appropriate constructor methods for the various
2543 // situations.
2544
2545 // FIXME: Some of the split computations are wrong; unaligned vectors
2546 // shouldn't be passed in registers for example, so there is no chance they
2547 // can straddle an eightbyte. Verify & simplify.
2548
2549 Lo = Hi = NoClass;
2550
2551 Class &Current = OffsetBase < 64 ? Lo : Hi;
2552 Current = Memory;
2553
John McCall9dd450b2009-09-21 23:43:11 +00002554 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 BuiltinType::Kind k = BT->getKind();
2556
2557 if (k == BuiltinType::Void) {
2558 Current = NoClass;
2559 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2560 Lo = Integer;
2561 Hi = Integer;
2562 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2563 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002564 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002565 Current = SSE;
2566 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002567 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002568 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002569 Lo = SSE;
2570 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002571 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002572 Lo = X87;
2573 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002574 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002575 Current = SSE;
2576 } else
2577 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002578 }
2579 // FIXME: _Decimal32 and _Decimal64 are SSE.
2580 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002581 return;
2582 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002583
Chris Lattnerd776fb12010-06-28 21:43:59 +00002584 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002585 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002586 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002587 return;
2588 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002589
Chris Lattnerd776fb12010-06-28 21:43:59 +00002590 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002591 Current = Integer;
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->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002596 if (Ty->isMemberFunctionPointerType()) {
2597 if (Has64BitPointers) {
2598 // If Has64BitPointers, this is an {i64, i64}, so classify both
2599 // Lo and Hi now.
2600 Lo = Hi = Integer;
2601 } else {
2602 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2603 // straddles an eightbyte boundary, Hi should be classified as well.
2604 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2605 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2606 if (EB_FuncPtr != EB_ThisAdj) {
2607 Lo = Hi = Integer;
2608 } else {
2609 Current = Integer;
2610 }
2611 }
2612 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002613 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002614 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002615 return;
2616 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002617
Chris Lattnerd776fb12010-06-28 21:43:59 +00002618 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002619 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002620 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2621 // gcc passes the following as integer:
2622 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2623 // 2 bytes - <2 x char>, <1 x short>
2624 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002625 Current = Integer;
2626
2627 // If this type crosses an eightbyte boundary, it should be
2628 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002629 uint64_t EB_Lo = (OffsetBase) / 64;
2630 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2631 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002632 Hi = Lo;
2633 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002634 QualType ElementType = VT->getElementType();
2635
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002636 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002637 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002638 return;
2639
David Majnemere2ae2282016-03-04 05:26:16 +00002640 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2641 // pass them as integer. For platforms where clang is the de facto
2642 // platform compiler, we must continue to use integer.
2643 if (!classifyIntegerMMXAsSSE() &&
2644 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2645 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2646 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2647 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002648 Current = Integer;
2649 else
2650 Current = SSE;
2651
2652 // If this type crosses an eightbyte boundary, it should be
2653 // split.
2654 if (OffsetBase && OffsetBase != 64)
2655 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002656 } else if (Size == 128 ||
2657 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002658 // Arguments of 256-bits are split into four eightbyte chunks. The
2659 // least significant one belongs to class SSE and all the others to class
2660 // SSEUP. The original Lo and Hi design considers that types can't be
2661 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2662 // This design isn't correct for 256-bits, but since there're no cases
2663 // where the upper parts would need to be inspected, avoid adding
2664 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002665 //
2666 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2667 // registers if they are "named", i.e. not part of the "..." of a
2668 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002669 //
2670 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2671 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002672 Lo = SSE;
2673 Hi = SSEUp;
2674 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002675 return;
2676 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002677
Chris Lattnerd776fb12010-06-28 21:43:59 +00002678 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002679 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680
Chris Lattner2b037972010-07-29 02:01:43 +00002681 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002682 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002683 if (Size <= 64)
2684 Current = Integer;
2685 else if (Size <= 128)
2686 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002687 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002689 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002690 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002691 } else if (ET == getContext().LongDoubleTy) {
2692 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002693 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002694 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002695 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002696 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002697 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002698 Lo = Hi = SSE;
2699 else
2700 llvm_unreachable("unexpected long double representation!");
2701 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002702
2703 // If this complex type crosses an eightbyte boundary then it
2704 // should be split.
2705 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002706 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707 if (Hi == NoClass && EB_Real != EB_Imag)
2708 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002709
Chris Lattnerd776fb12010-06-28 21:43:59 +00002710 return;
2711 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002712
Chris Lattner2b037972010-07-29 02:01:43 +00002713 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002714 // Arrays are treated like structures.
2715
Chris Lattner2b037972010-07-29 02:01:43 +00002716 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002717
2718 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002719 // than eight eightbytes, ..., it has class MEMORY.
2720 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002721 return;
2722
2723 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2724 // fields, it has class MEMORY.
2725 //
2726 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002727 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002728 return;
2729
2730 // Otherwise implement simplified merge. We could be smarter about
2731 // this, but it isn't worth it and would be harder to verify.
2732 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002733 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002734 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002735
2736 // The only case a 256-bit wide vector could be used is when the array
2737 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2738 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002739 //
2740 if (Size > 128 &&
2741 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002742 return;
2743
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2745 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002746 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002747 Lo = merge(Lo, FieldLo);
2748 Hi = merge(Hi, FieldHi);
2749 if (Lo == Memory || Hi == Memory)
2750 break;
2751 }
2752
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002753 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002754 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002755 return;
2756 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002757
Chris Lattnerd776fb12010-06-28 21:43:59 +00002758 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002759 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002760
2761 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002762 // than eight eightbytes, ..., it has class MEMORY.
2763 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002764 return;
2765
Anders Carlsson20759ad2009-09-16 15:53:40 +00002766 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2767 // copy constructor or a non-trivial destructor, it is passed by invisible
2768 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002769 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002770 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002771
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002772 const RecordDecl *RD = RT->getDecl();
2773
2774 // Assume variable sized types are passed in memory.
2775 if (RD->hasFlexibleArrayMember())
2776 return;
2777
Chris Lattner2b037972010-07-29 02:01:43 +00002778 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002779
2780 // Reset Lo class, this will be recomputed.
2781 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002782
2783 // If this is a C++ record, classify the bases first.
2784 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002785 for (const auto &I : CXXRD->bases()) {
2786 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002787 "Unexpected base class!");
2788 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002789 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002790
2791 // Classify this field.
2792 //
2793 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2794 // single eightbyte, each is classified separately. Each eightbyte gets
2795 // initialized to class NO_CLASS.
2796 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002797 uint64_t Offset =
2798 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002799 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002800 Lo = merge(Lo, FieldLo);
2801 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002802 if (Lo == Memory || Hi == Memory) {
2803 postMerge(Size, Lo, Hi);
2804 return;
2805 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002806 }
2807 }
2808
2809 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002810 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002811 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002812 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002813 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2814 bool BitField = i->isBitField();
2815
David Majnemerb439dfe2016-08-15 07:20:40 +00002816 // Ignore padding bit-fields.
2817 if (BitField && i->isUnnamedBitfield())
2818 continue;
2819
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002820 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2821 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002822 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002823 // The only case a 256-bit wide vector could be used is when the struct
2824 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2825 // to work for sizes wider than 128, early check and fallback to memory.
2826 //
David Majnemerb229cb02016-08-15 06:39:18 +00002827 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2828 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002829 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002830 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002831 return;
2832 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002833 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002834 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002835 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002836 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002837 return;
2838 }
2839
2840 // Classify this field.
2841 //
2842 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2843 // exceeds a single eightbyte, each is classified
2844 // separately. Each eightbyte gets initialized to class
2845 // NO_CLASS.
2846 Class FieldLo, FieldHi;
2847
2848 // Bit-fields require special handling, they do not force the
2849 // structure to be passed in memory even if unaligned, and
2850 // therefore they can straddle an eightbyte.
2851 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002852 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002853 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002854 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002855
2856 uint64_t EB_Lo = Offset / 64;
2857 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002858
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002859 if (EB_Lo) {
2860 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2861 FieldLo = NoClass;
2862 FieldHi = Integer;
2863 } else {
2864 FieldLo = Integer;
2865 FieldHi = EB_Hi ? Integer : NoClass;
2866 }
2867 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002868 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002869 Lo = merge(Lo, FieldLo);
2870 Hi = merge(Hi, FieldHi);
2871 if (Lo == Memory || Hi == Memory)
2872 break;
2873 }
2874
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002875 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002876 }
2877}
2878
Chris Lattner22a931e2010-06-29 06:01:59 +00002879ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002880 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2881 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002882 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002883 // Treat an enum type as its underlying type.
2884 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2885 Ty = EnumTy->getDecl()->getIntegerType();
2886
Alex Bradburye41a5e22018-01-12 20:08:16 +00002887 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2888 : ABIArgInfo::getDirect());
Daniel Dunbar53fac692010-04-21 19:49:55 +00002889 }
2890
John McCall7f416cc2015-09-08 08:05:57 +00002891 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002892}
2893
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002894bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2895 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2896 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002897 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002898 if (Size <= 64 || Size > LargestVector)
2899 return true;
2900 }
2901
2902 return false;
2903}
2904
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002905ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2906 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2908 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002909 //
2910 // This assumption is optimistic, as there could be free registers available
2911 // when we need to pass this argument in memory, and LLVM could try to pass
2912 // the argument in the free register. This does not seem to happen currently,
2913 // but this code would be much safer if we could mark the argument with
2914 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002915 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002916 // Treat an enum type as its underlying type.
2917 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2918 Ty = EnumTy->getDecl()->getIntegerType();
2919
Alex Bradburye41a5e22018-01-12 20:08:16 +00002920 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2921 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002922 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002923
Mark Lacey3825e832013-10-06 01:33:34 +00002924 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002925 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002926
Chris Lattner44c2b902011-05-22 23:21:23 +00002927 // Compute the byval alignment. We specify the alignment of the byval in all
2928 // cases so that the mid-level optimizer knows the alignment of the byval.
2929 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002930
2931 // Attempt to avoid passing indirect results using byval when possible. This
2932 // is important for good codegen.
2933 //
2934 // We do this by coercing the value into a scalar type which the backend can
2935 // handle naturally (i.e., without using byval).
2936 //
2937 // For simplicity, we currently only do this when we have exhausted all of the
2938 // free integer registers. Doing this when there are free integer registers
2939 // would require more care, as we would have to ensure that the coerced value
2940 // did not claim the unused register. That would require either reording the
2941 // arguments to the function (so that any subsequent inreg values came first),
2942 // or only doing this optimization when there were no following arguments that
2943 // might be inreg.
2944 //
2945 // We currently expect it to be rare (particularly in well written code) for
2946 // arguments to be passed on the stack when there are still free integer
2947 // registers available (this would typically imply large structs being passed
2948 // by value), so this seems like a fair tradeoff for now.
2949 //
2950 // We can revisit this if the backend grows support for 'onstack' parameter
2951 // attributes. See PR12193.
2952 if (freeIntRegs == 0) {
2953 uint64_t Size = getContext().getTypeSize(Ty);
2954
2955 // If this type fits in an eightbyte, coerce it into the matching integral
2956 // type, which will end up on the stack (with alignment 8).
2957 if (Align == 8 && Size <= 64)
2958 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2959 Size));
2960 }
2961
John McCall7f416cc2015-09-08 08:05:57 +00002962 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002963}
2964
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002965/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2966/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002967llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002968 // Wrapper structs/arrays that only contain vectors are passed just like
2969 // vectors; strip them off if present.
2970 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2971 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002972
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002973 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002974 if (isa<llvm::VectorType>(IRType) ||
2975 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002976 return IRType;
2977
2978 // We couldn't find the preferred IR vector type for 'Ty'.
2979 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002980 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002981
2982 // Return a LLVM IR vector type based on the size of 'Ty'.
2983 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2984 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002985}
2986
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002987/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2988/// is known to either be off the end of the specified type or being in
2989/// alignment padding. The user type specified is known to be at most 128 bits
2990/// in size, and have passed through X86_64ABIInfo::classify with a successful
2991/// classification that put one of the two halves in the INTEGER class.
2992///
2993/// It is conservatively correct to return false.
2994static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2995 unsigned EndBit, ASTContext &Context) {
2996 // If the bytes being queried are off the end of the type, there is no user
2997 // data hiding here. This handles analysis of builtins, vectors and other
2998 // types that don't contain interesting padding.
2999 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3000 if (TySize <= StartBit)
3001 return true;
3002
Chris Lattner98076a22010-07-29 07:43:55 +00003003 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3004 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3005 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3006
3007 // Check each element to see if the element overlaps with the queried range.
3008 for (unsigned i = 0; i != NumElts; ++i) {
3009 // If the element is after the span we care about, then we're done..
3010 unsigned EltOffset = i*EltSize;
3011 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003012
Chris Lattner98076a22010-07-29 07:43:55 +00003013 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3014 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3015 EndBit-EltOffset, Context))
3016 return false;
3017 }
3018 // If it overlaps no elements, then it is safe to process as padding.
3019 return true;
3020 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003021
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003022 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3023 const RecordDecl *RD = RT->getDecl();
3024 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003025
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003026 // If this is a C++ record, check the bases first.
3027 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003028 for (const auto &I : CXXRD->bases()) {
3029 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003030 "Unexpected base class!");
3031 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003032 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003033
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003034 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003035 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003036 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003037
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003038 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003039 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003040 EndBit-BaseOffset, Context))
3041 return false;
3042 }
3043 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003044
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003045 // Verify that no field has data that overlaps the region of interest. Yes
3046 // this could be sped up a lot by being smarter about queried fields,
3047 // however we're only looking at structs up to 16 bytes, so we don't care
3048 // much.
3049 unsigned idx = 0;
3050 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3051 i != e; ++i, ++idx) {
3052 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003053
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003054 // If we found a field after the region we care about, then we're done.
3055 if (FieldOffset >= EndBit) break;
3056
3057 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3058 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3059 Context))
3060 return false;
3061 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003062
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003063 // If nothing in this record overlapped the area of interest, then we're
3064 // clean.
3065 return true;
3066 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003067
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003068 return false;
3069}
3070
Chris Lattnere556a712010-07-29 18:39:32 +00003071/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3072/// float member at the specified offset. For example, {int,{float}} has a
3073/// float at offset 4. It is conservatively correct for this routine to return
3074/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003075static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003076 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003077 // Base case if we find a float.
3078 if (IROffset == 0 && IRType->isFloatTy())
3079 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003080
Chris Lattnere556a712010-07-29 18:39:32 +00003081 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003082 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003083 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3084 unsigned Elt = SL->getElementContainingOffset(IROffset);
3085 IROffset -= SL->getElementOffset(Elt);
3086 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3087 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003088
Chris Lattnere556a712010-07-29 18:39:32 +00003089 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003090 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3091 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003092 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3093 IROffset -= IROffset/EltSize*EltSize;
3094 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3095 }
3096
3097 return false;
3098}
3099
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003100
3101/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3102/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003103llvm::Type *X86_64ABIInfo::
3104GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003105 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003106 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003107 // pass as float if the last 4 bytes is just padding. This happens for
3108 // structs that contain 3 floats.
3109 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3110 SourceOffset*8+64, getContext()))
3111 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003112
Chris Lattnere556a712010-07-29 18:39:32 +00003113 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3114 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3115 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003116 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3117 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003118 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003119
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003120 return llvm::Type::getDoubleTy(getVMContext());
3121}
3122
3123
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003124/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3125/// an 8-byte GPR. This means that we either have a scalar or we are talking
3126/// about the high or low part of an up-to-16-byte struct. This routine picks
3127/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003128/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3129/// etc).
3130///
3131/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3132/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3133/// the 8-byte value references. PrefType may be null.
3134///
Alp Toker9907f082014-07-09 14:06:35 +00003135/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003136/// an offset into this that we're processing (which is always either 0 or 8).
3137///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003138llvm::Type *X86_64ABIInfo::
3139GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003140 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003141 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3142 // returning an 8-byte unit starting with it. See if we can safely use it.
3143 if (IROffset == 0) {
3144 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003145 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3146 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003147 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003148
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003149 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3150 // goodness in the source type is just tail padding. This is allowed to
3151 // kick in for struct {double,int} on the int, but not on
3152 // struct{double,int,int} because we wouldn't return the second int. We
3153 // have to do this analysis on the source type because we can't depend on
3154 // unions being lowered a specific way etc.
3155 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003156 IRType->isIntegerTy(32) ||
3157 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3158 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3159 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003160
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003161 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3162 SourceOffset*8+64, getContext()))
3163 return IRType;
3164 }
3165 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003166
Chris Lattner2192fe52011-07-18 04:24:23 +00003167 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003168 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003169 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003170 if (IROffset < SL->getSizeInBytes()) {
3171 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3172 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003173
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003174 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3175 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003176 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003177 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003178
Chris Lattner2192fe52011-07-18 04:24:23 +00003179 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003180 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003181 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003182 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003183 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3184 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003185 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003186
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003187 // Okay, we don't have any better idea of what to pass, so we pass this in an
3188 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003189 unsigned TySizeInBytes =
3190 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003191
Chris Lattner3f763422010-07-29 17:34:39 +00003192 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003193
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003194 // It is always safe to classify this as an integer type up to i64 that
3195 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003196 return llvm::IntegerType::get(getVMContext(),
3197 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003198}
3199
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003200
3201/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3202/// be used as elements of a two register pair to pass or return, return a
3203/// first class aggregate to represent them. For example, if the low part of
3204/// a by-value argument should be passed as i32* and the high part as float,
3205/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003206static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003207GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003208 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003209 // In order to correctly satisfy the ABI, we need to the high part to start
3210 // at offset 8. If the high and low parts we inferred are both 4-byte types
3211 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3212 // the second element at offset 8. Check for this:
3213 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3214 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003215 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003216 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003217
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003218 // To handle this, we have to increase the size of the low part so that the
3219 // second element will start at an 8 byte offset. We can't increase the size
3220 // of the second element because it might make us access off the end of the
3221 // struct.
3222 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003223 // There are usually two sorts of types the ABI generation code can produce
3224 // for the low part of a pair that aren't 8 bytes in size: float or
3225 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3226 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003227 // Promote these to a larger type.
3228 if (Lo->isFloatTy())
3229 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3230 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003231 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3232 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003233 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3234 }
3235 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003236
Serge Guelton1d993272017-05-09 19:31:30 +00003237 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003238
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003239 // Verify that the second element is at an 8-byte offset.
3240 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3241 "Invalid x86-64 argument pair!");
3242 return Result;
3243}
3244
Chris Lattner31faff52010-07-28 23:06:14 +00003245ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003246classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003247 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3248 // classification algorithm.
3249 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003250 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003251
3252 // Check some invariants.
3253 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003254 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3255
Craig Topper8a13c412014-05-21 05:09:00 +00003256 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003257 switch (Lo) {
3258 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003259 if (Hi == NoClass)
3260 return ABIArgInfo::getIgnore();
3261 // If the low part is just padding, it takes no register, leave ResType
3262 // null.
3263 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3264 "Unknown missing lo part");
3265 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003266
3267 case SSEUp:
3268 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003269 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003270
3271 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3272 // hidden argument.
3273 case Memory:
3274 return getIndirectReturnResult(RetTy);
3275
3276 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3277 // available register of the sequence %rax, %rdx is used.
3278 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003279 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003280
Chris Lattner1f3a0632010-07-29 21:42:50 +00003281 // If we have a sign or zero extended integer, make sure to return Extend
3282 // so that the parameter gets the right LLVM IR attributes.
3283 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3284 // Treat an enum type as its underlying type.
3285 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3286 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003287
Chris Lattner1f3a0632010-07-29 21:42:50 +00003288 if (RetTy->isIntegralOrEnumerationType() &&
3289 RetTy->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003290 return ABIArgInfo::getExtend(RetTy);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003291 }
Chris Lattner31faff52010-07-28 23:06:14 +00003292 break;
3293
3294 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3295 // available SSE register of the sequence %xmm0, %xmm1 is used.
3296 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003297 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003298 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003299
3300 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3301 // returned on the X87 stack in %st0 as 80-bit x87 number.
3302 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003303 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003304 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003305
3306 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3307 // part of the value is returned in %st0 and the imaginary part in
3308 // %st1.
3309 case ComplexX87:
3310 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003311 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003312 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003313 break;
3314 }
3315
Craig Topper8a13c412014-05-21 05:09:00 +00003316 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003317 switch (Hi) {
3318 // Memory was handled previously and X87 should
3319 // never occur as a hi class.
3320 case Memory:
3321 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003322 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003323
3324 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003325 case NoClass:
3326 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003327
Chris Lattner52b3c132010-09-01 00:20:33 +00003328 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003329 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003330 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3331 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003332 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003333 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003334 HighPart = GetSSETypeAtOffset(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;
3338
3339 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003340 // is passed in the next available eightbyte chunk if the last used
3341 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003342 //
Chris Lattner57540c52011-04-15 05:22:18 +00003343 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003344 case SSEUp:
3345 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003346 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003347 break;
3348
3349 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3350 // returned together with the previous X87 value in %st0.
3351 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003352 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003353 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003354 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003355 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003356 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003357 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003358 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3359 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003360 }
Chris Lattner31faff52010-07-28 23:06:14 +00003361 break;
3362 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003363
Chris Lattner52b3c132010-09-01 00:20:33 +00003364 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003365 // known to pass in the high eightbyte of the result. We do this by forming a
3366 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003367 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003368 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003369
Chris Lattner1f3a0632010-07-29 21:42:50 +00003370 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003371}
3372
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003373ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003374 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3375 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003376 const
3377{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003378 Ty = useFirstFieldIfTransparentUnion(Ty);
3379
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003380 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003381 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003382
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003383 // Check some invariants.
3384 // FIXME: Enforce these by construction.
3385 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003386 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3387
3388 neededInt = 0;
3389 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003390 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003391 switch (Lo) {
3392 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003393 if (Hi == NoClass)
3394 return ABIArgInfo::getIgnore();
3395 // If the low part is just padding, it takes no register, leave ResType
3396 // null.
3397 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3398 "Unknown missing lo part");
3399 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003400
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003401 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3402 // on the stack.
3403 case Memory:
3404
3405 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3406 // COMPLEX_X87, it is passed in memory.
3407 case X87:
3408 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003409 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003410 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003411 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003412
3413 case SSEUp:
3414 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003415 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003416
3417 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3418 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3419 // and %r9 is used.
3420 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003421 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003422
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003423 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003424 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003425
3426 // If we have a sign or zero extended integer, make sure to return Extend
3427 // so that the parameter gets the right LLVM IR attributes.
3428 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3429 // Treat an enum type as its underlying type.
3430 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3431 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003432
Chris Lattner1f3a0632010-07-29 21:42:50 +00003433 if (Ty->isIntegralOrEnumerationType() &&
3434 Ty->isPromotableIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00003435 return ABIArgInfo::getExtend(Ty);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003436 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003437
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003438 break;
3439
3440 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3441 // available SSE register is used, the registers are taken in the
3442 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003443 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003444 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003445 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003446 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003447 break;
3448 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003449 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003450
Craig Topper8a13c412014-05-21 05:09:00 +00003451 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003452 switch (Hi) {
3453 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003454 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003455 // which is passed in memory.
3456 case Memory:
3457 case X87:
3458 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003459 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003460
3461 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003462
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003463 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003464 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003465 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003466 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003467
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003468 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3469 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003470 break;
3471
3472 // X87Up generally doesn't occur here (long double is passed in
3473 // memory), except in situations involving unions.
3474 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003475 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003476 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003477
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003478 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3479 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003480
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003481 ++neededSSE;
3482 break;
3483
3484 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3485 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003486 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003487 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003488 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003489 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003490 break;
3491 }
3492
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003493 // If a high part was specified, merge it together with the low part. It is
3494 // known to pass in the high eightbyte of the result. We do this by forming a
3495 // first class struct aggregate with the high and low part: {low, high}
3496 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003497 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003498
Chris Lattner1f3a0632010-07-29 21:42:50 +00003499 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003500}
3501
Erich Keane757d3172016-11-02 18:29:35 +00003502ABIArgInfo
3503X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3504 unsigned &NeededSSE) const {
3505 auto RT = Ty->getAs<RecordType>();
3506 assert(RT && "classifyRegCallStructType only valid with struct types");
3507
3508 if (RT->getDecl()->hasFlexibleArrayMember())
3509 return getIndirectReturnResult(Ty);
3510
3511 // Sum up bases
3512 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3513 if (CXXRD->isDynamicClass()) {
3514 NeededInt = NeededSSE = 0;
3515 return getIndirectReturnResult(Ty);
3516 }
3517
3518 for (const auto &I : CXXRD->bases())
3519 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3520 .isIndirect()) {
3521 NeededInt = NeededSSE = 0;
3522 return getIndirectReturnResult(Ty);
3523 }
3524 }
3525
3526 // Sum up members
3527 for (const auto *FD : RT->getDecl()->fields()) {
3528 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3529 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3530 .isIndirect()) {
3531 NeededInt = NeededSSE = 0;
3532 return getIndirectReturnResult(Ty);
3533 }
3534 } else {
3535 unsigned LocalNeededInt, LocalNeededSSE;
3536 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3537 LocalNeededSSE, true)
3538 .isIndirect()) {
3539 NeededInt = NeededSSE = 0;
3540 return getIndirectReturnResult(Ty);
3541 }
3542 NeededInt += LocalNeededInt;
3543 NeededSSE += LocalNeededSSE;
3544 }
3545 }
3546
3547 return ABIArgInfo::getDirect();
3548}
3549
3550ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3551 unsigned &NeededInt,
3552 unsigned &NeededSSE) const {
3553
3554 NeededInt = 0;
3555 NeededSSE = 0;
3556
3557 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3558}
3559
Chris Lattner22326a12010-07-29 02:31:05 +00003560void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003561
Alexander Ivchenko4b20b3c2018-02-08 11:15:21 +00003562 const unsigned CallingConv = FI.getCallingConvention();
3563 // It is possible to force Win64 calling convention on any x86_64 target by
3564 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3565 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3566 if (CallingConv == llvm::CallingConv::Win64) {
3567 WinX86_64ABIInfo Win64ABIInfo(CGT);
3568 Win64ABIInfo.computeInfo(FI);
3569 return;
3570 }
3571
3572 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003573
3574 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003575 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3576 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3577 unsigned NeededInt, NeededSSE;
3578
Akira Hatanakad791e922018-03-19 17:38:40 +00003579 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
Erich Keanede1b2a92017-07-21 18:50:36 +00003580 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3581 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3582 FI.getReturnInfo() =
3583 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3584 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3585 FreeIntRegs -= NeededInt;
3586 FreeSSERegs -= NeededSSE;
3587 } else {
3588 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3589 }
3590 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3591 // Complex Long Double Type is passed in Memory when Regcall
3592 // calling convention is used.
3593 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3594 if (getContext().getCanonicalType(CT->getElementType()) ==
3595 getContext().LongDoubleTy)
3596 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3597 } else
3598 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3599 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003600
3601 // If the return value is indirect, then the hidden argument is consuming one
3602 // integer register.
3603 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003604 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003605
Peter Collingbournef7706832014-12-12 23:41:25 +00003606 // The chain argument effectively gives us another free register.
3607 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003608 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003609
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003610 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003611 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3612 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003613 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003614 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003615 it != ie; ++it, ++ArgNo) {
3616 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003617
Erich Keane757d3172016-11-02 18:29:35 +00003618 if (IsRegCall && it->type->isStructureOrClassType())
3619 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3620 else
3621 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3622 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003623
3624 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3625 // eightbyte of an argument, the whole argument is passed on the
3626 // stack. If registers have already been assigned for some
3627 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003628 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3629 FreeIntRegs -= NeededInt;
3630 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003631 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003632 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003633 }
3634 }
3635}
3636
John McCall7f416cc2015-09-08 08:05:57 +00003637static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3638 Address VAListAddr, QualType Ty) {
3639 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3640 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003641 llvm::Value *overflow_arg_area =
3642 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3643
3644 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3645 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003646 // It isn't stated explicitly in the standard, but in practice we use
3647 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003648 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3649 if (Align > CharUnits::fromQuantity(8)) {
3650 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3651 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003652 }
3653
3654 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003655 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003656 llvm::Value *Res =
3657 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003658 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003659
3660 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3661 // l->overflow_arg_area + sizeof(type).
3662 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3663 // an 8 byte boundary.
3664
3665 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003666 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003667 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003668 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3669 "overflow_arg_area.next");
3670 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3671
3672 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003673 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003674}
3675
John McCall7f416cc2015-09-08 08:05:57 +00003676Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3677 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003678 // Assume that va_list type is correct; should be pointer to LLVM type:
3679 // struct {
3680 // i32 gp_offset;
3681 // i32 fp_offset;
3682 // i8* overflow_arg_area;
3683 // i8* reg_save_area;
3684 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003685 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003686
John McCall7f416cc2015-09-08 08:05:57 +00003687 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003688 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003689 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003690
3691 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3692 // in the registers. If not go to step 7.
3693 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003694 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003695
3696 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3697 // general purpose registers needed to pass type and num_fp to hold
3698 // the number of floating point registers needed.
3699
3700 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3701 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3702 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3703 //
3704 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3705 // register save space).
3706
Craig Topper8a13c412014-05-21 05:09:00 +00003707 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003708 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3709 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003710 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003711 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003712 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3713 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003714 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003715 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3716 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003717 }
3718
3719 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003720 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003721 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3722 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003723 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3724 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003725 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3726 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003727 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3728 }
3729
3730 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3731 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3732 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3733 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3734
3735 // Emit code to load the value if it was passed in registers.
3736
3737 CGF.EmitBlock(InRegBlock);
3738
3739 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3740 // an offset of l->gp_offset and/or l->fp_offset. This may require
3741 // copying to a temporary location in case the parameter is passed
3742 // in different register classes or requires an alignment greater
3743 // than 8 for general purpose registers and 16 for XMM registers.
3744 //
3745 // FIXME: This really results in shameful code when we end up needing to
3746 // collect arguments from different places; often what should result in a
3747 // simple assembling of a structure from scattered addresses has many more
3748 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003749 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003750 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3751 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3752 "reg_save_area");
3753
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)));
John McCall7f416cc2015-09-08 08:05:57 +00003778 CGF.Builder.CreateStore(V,
3779 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3780
3781 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003782 V = CGF.Builder.CreateAlignedLoad(
3783 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3784 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003785 CharUnits Offset = CharUnits::fromQuantity(
3786 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3787 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3788
3789 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003790 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003791 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3792 CharUnits::fromQuantity(8));
3793 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003794
3795 // Copy to a temporary if necessary to ensure the appropriate alignment.
3796 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003797 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003798 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003799 CharUnits TyAlign = SizeAlign.second;
3800
3801 // Copy into a temporary if the type is more aligned than the
3802 // register save area.
3803 if (TyAlign.getQuantity() > 8) {
3804 Address Tmp = CGF.CreateMemTemp(Ty);
3805 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003806 RegAddr = Tmp;
3807 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003808
Chris Lattner0cf24192010-06-28 20:05:43 +00003809 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003810 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3811 CharUnits::fromQuantity(16));
3812 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003813 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003814 assert(neededSSE == 2 && "Invalid number of needed registers!");
3815 // SSE registers are spaced 16 bytes apart in the register save
3816 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003817 // The ABI isn't explicit about this, but it seems reasonable
3818 // to assume that the slots are 16-byte aligned, since the stack is
3819 // naturally 16-byte aligned and the prologue is expected to store
3820 // all the SSE registers to the RSA.
3821 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3822 CharUnits::fromQuantity(16));
3823 Address RegAddrHi =
3824 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3825 CharUnits::fromQuantity(16));
Erich Keane24e68402018-02-02 15:53:35 +00003826 llvm::Type *ST = AI.canHaveCoerceToType()
3827 ? AI.getCoerceToType()
3828 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003829 llvm::Value *V;
3830 Address Tmp = CGF.CreateMemTemp(Ty);
3831 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Erich Keane24e68402018-02-02 15:53:35 +00003832 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3833 RegAddrLo, ST->getStructElementType(0)));
John McCall7f416cc2015-09-08 08:05:57 +00003834 CGF.Builder.CreateStore(V,
3835 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
Erich Keane24e68402018-02-02 15:53:35 +00003836 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3837 RegAddrHi, ST->getStructElementType(1)));
John McCall7f416cc2015-09-08 08:05:57 +00003838 CGF.Builder.CreateStore(V,
3839 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3840
3841 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003842 }
3843
3844 // AMD64-ABI 3.5.7p5: Step 5. Set:
3845 // l->gp_offset = l->gp_offset + num_gp * 8
3846 // l->fp_offset = l->fp_offset + num_fp * 16.
3847 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003848 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003849 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3850 gp_offset_p);
3851 }
3852 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003853 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003854 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3855 fp_offset_p);
3856 }
3857 CGF.EmitBranch(ContBlock);
3858
3859 // Emit code to load the value if it was passed in memory.
3860
3861 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003862 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003863
3864 // Return the appropriate result.
3865
3866 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003867 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3868 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003869 return ResAddr;
3870}
3871
Charles Davisc7d5c942015-09-17 20:55:33 +00003872Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3873 QualType Ty) const {
3874 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3875 CGF.getContext().getTypeInfoInChars(Ty),
3876 CharUnits::fromQuantity(8),
3877 /*allowHigherAlign*/ false);
3878}
3879
Erich Keane521ed962017-01-05 00:20:51 +00003880ABIArgInfo
3881WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3882 const ABIArgInfo &current) const {
3883 // Assumes vectorCall calling convention.
3884 const Type *Base = nullptr;
3885 uint64_t NumElts = 0;
3886
3887 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3888 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3889 FreeSSERegs -= NumElts;
3890 return getDirectX86Hva();
3891 }
3892 return current;
3893}
3894
Reid Kleckner80944df2014-10-31 22:00:51 +00003895ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003896 bool IsReturnType, bool IsVectorCall,
3897 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003898
3899 if (Ty->isVoidType())
3900 return ABIArgInfo::getIgnore();
3901
3902 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3903 Ty = EnumTy->getDecl()->getIntegerType();
3904
Reid Kleckner80944df2014-10-31 22:00:51 +00003905 TypeInfo Info = getContext().getTypeInfo(Ty);
3906 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003907 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003908
Reid Kleckner9005f412014-05-02 00:51:20 +00003909 const RecordType *RT = Ty->getAs<RecordType>();
3910 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003911 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003912 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003913 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003914 }
3915
3916 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003917 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003918
Reid Kleckner9005f412014-05-02 00:51:20 +00003919 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003920
Reid Kleckner80944df2014-10-31 22:00:51 +00003921 const Type *Base = nullptr;
3922 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003923 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3924 // other targets.
3925 if ((IsVectorCall || IsRegCall) &&
3926 isHomogeneousAggregate(Ty, Base, NumElts)) {
3927 if (IsRegCall) {
3928 if (FreeSSERegs >= NumElts) {
3929 FreeSSERegs -= NumElts;
3930 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3931 return ABIArgInfo::getDirect();
3932 return ABIArgInfo::getExpand();
3933 }
3934 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3935 } else if (IsVectorCall) {
3936 if (FreeSSERegs >= NumElts &&
3937 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3938 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003939 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003940 } else if (IsReturnType) {
3941 return ABIArgInfo::getExpand();
3942 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3943 // HVAs are delayed and reclassified in the 2nd step.
3944 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3945 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003946 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003947 }
3948
Reid Klecknerec87fec2014-05-02 01:17:12 +00003949 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003950 // If the member pointer is represented by an LLVM int or ptr, pass it
3951 // directly.
3952 llvm::Type *LLTy = CGT.ConvertType(Ty);
3953 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3954 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003955 }
3956
Michael Kuperstein4f818702015-02-24 09:35:58 +00003957 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003958 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3959 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003960 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003961 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003962
Reid Kleckner9005f412014-05-02 00:51:20 +00003963 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003964 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003965 }
3966
Reid Kleckner08f64e92018-10-31 17:43:55 +00003967 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3968 switch (BT->getKind()) {
3969 case BuiltinType::Bool:
3970 // Bool type is always extended to the ABI, other builtin types are not
3971 // extended.
3972 return ABIArgInfo::getExtend(Ty);
3973
3974 case BuiltinType::LongDouble:
3975 // Mingw64 GCC uses the old 80 bit extended precision floating point
3976 // unit. It passes them indirectly through memory.
3977 if (IsMingw64) {
3978 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3979 if (LDF == &llvm::APFloat::x87DoubleExtended())
3980 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3981 }
3982 break;
3983
3984 case BuiltinType::Int128:
3985 case BuiltinType::UInt128:
3986 // If it's a parameter type, the normal ABI rule is that arguments larger
3987 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
3988 // even though it isn't particularly efficient.
3989 if (!IsReturnType)
3990 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3991
3992 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
3993 // Clang matches them for compatibility.
3994 return ABIArgInfo::getDirect(
3995 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
3996
3997 default:
3998 break;
3999 }
Reid Kleckner11a17192015-10-28 22:29:52 +00004000 }
4001
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004002 return ABIArgInfo::getDirect();
4003}
4004
Erich Keane521ed962017-01-05 00:20:51 +00004005void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4006 unsigned FreeSSERegs,
4007 bool IsVectorCall,
4008 bool IsRegCall) const {
4009 unsigned Count = 0;
4010 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004011 // Vectorcall in x64 only permits the first 6 arguments to be passed
4012 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00004013 if (Count < VectorcallMaxParamNumAsReg)
4014 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4015 else {
4016 // Since these cannot be passed in registers, pretend no registers
4017 // are left.
4018 unsigned ZeroSSERegsAvail = 0;
4019 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4020 IsVectorCall, IsRegCall);
4021 }
4022 ++Count;
4023 }
4024
Erich Keane521ed962017-01-05 00:20:51 +00004025 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00004026 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00004027 }
4028}
4029
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004030void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00004031 bool IsVectorCall =
4032 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00004033 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00004034
Erich Keane757d3172016-11-02 18:29:35 +00004035 unsigned FreeSSERegs = 0;
4036 if (IsVectorCall) {
4037 // We can use up to 4 SSE return registers with vectorcall.
4038 FreeSSERegs = 4;
4039 } else if (IsRegCall) {
4040 // RegCall gives us 16 SSE registers.
4041 FreeSSERegs = 16;
4042 }
4043
Reid Kleckner80944df2014-10-31 22:00:51 +00004044 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004045 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4046 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004047
Erich Keane757d3172016-11-02 18:29:35 +00004048 if (IsVectorCall) {
4049 // We can use up to 6 SSE register parameters with vectorcall.
4050 FreeSSERegs = 6;
4051 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004052 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004053 FreeSSERegs = 16;
4054 }
4055
Erich Keane521ed962017-01-05 00:20:51 +00004056 if (IsVectorCall) {
4057 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4058 } else {
4059 for (auto &I : FI.arguments())
4060 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4061 }
4062
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004063}
4064
John McCall7f416cc2015-09-08 08:05:57 +00004065Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4066 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004067
4068 bool IsIndirect = false;
4069
4070 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4071 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4072 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4073 uint64_t Width = getContext().getTypeSize(Ty);
4074 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4075 }
4076
4077 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004078 CGF.getContext().getTypeInfoInChars(Ty),
4079 CharUnits::fromQuantity(8),
4080 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004081}
Chris Lattner0cf24192010-06-28 20:05:43 +00004082
John McCallea8d8bb2010-03-11 00:10:12 +00004083// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004084namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004085/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4086class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004087 bool IsSoftFloatABI;
4088
4089 CharUnits getParamTypeAlignment(QualType Ty) const;
4090
John McCallea8d8bb2010-03-11 00:10:12 +00004091public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004092 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4093 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004094
John McCall7f416cc2015-09-08 08:05:57 +00004095 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4096 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004097};
4098
4099class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4100public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004101 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4102 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004103
Craig Topper4f12f102014-03-12 06:41:41 +00004104 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004105 // This is recovered from gcc output.
4106 return 1; // r1 is the dedicated stack pointer
4107 }
4108
4109 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004110 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004111};
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004112}
John McCallea8d8bb2010-03-11 00:10:12 +00004113
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004114CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4115 // Complex types are passed just like their elements
4116 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4117 Ty = CTy->getElementType();
4118
4119 if (Ty->isVectorType())
4120 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4121 : 4);
4122
4123 // For single-element float/vector structs, we consider the whole type
4124 // to have the same alignment requirements as its single element.
4125 const Type *AlignTy = nullptr;
4126 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4127 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4128 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4129 (BT && BT->isFloatingPoint()))
4130 AlignTy = EltType;
4131 }
4132
4133 if (AlignTy)
4134 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4135 return CharUnits::fromQuantity(4);
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004136}
John McCallea8d8bb2010-03-11 00:10:12 +00004137
James Y Knight29b5f082016-02-24 02:59:33 +00004138// TODO: this implementation is now likely redundant with
4139// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004140Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4141 QualType Ty) const {
Saleem Abdulrasool2a5015b2017-10-25 17:56:50 +00004142 if (getTarget().getTriple().isOSDarwin()) {
4143 auto TI = getContext().getTypeInfoInChars(Ty);
4144 TI.second = getParamTypeAlignment(Ty);
4145
4146 CharUnits SlotSize = CharUnits::fromQuantity(4);
4147 return emitVoidPtrVAArg(CGF, VAList, Ty,
4148 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4149 /*AllowHigherAlign=*/true);
4150 }
4151
Roman Divacky039b9702016-02-20 08:31:24 +00004152 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004153 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4154 // TODO: Implement this. For now ignore.
4155 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004156 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004157 }
4158
John McCall7f416cc2015-09-08 08:05:57 +00004159 // struct __va_list_tag {
4160 // unsigned char gpr;
4161 // unsigned char fpr;
4162 // unsigned short reserved;
4163 // void *overflow_arg_area;
4164 // void *reg_save_area;
4165 // };
4166
Roman Divacky8a12d842014-11-03 18:32:54 +00004167 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004168 bool isInt =
4169 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004170 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004171
4172 // All aggregates are passed indirectly? That doesn't seem consistent
4173 // with the argument-lowering code.
4174 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004175
4176 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004177
4178 // The calling convention either uses 1-2 GPRs or 1 FPR.
4179 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004180 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004181 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4182 } else {
4183 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004184 }
John McCall7f416cc2015-09-08 08:05:57 +00004185
4186 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4187
4188 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004189 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004190 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4191 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4192 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004193
Eric Christopher7565e0d2015-05-29 23:09:49 +00004194 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004195 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004196
4197 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4198 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4199 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4200
4201 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4202
John McCall7f416cc2015-09-08 08:05:57 +00004203 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4204 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004205
John McCall7f416cc2015-09-08 08:05:57 +00004206 // Case 1: consume registers.
4207 Address RegAddr = Address::invalid();
4208 {
4209 CGF.EmitBlock(UsingRegs);
4210
4211 Address RegSaveAreaPtr =
4212 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4213 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4214 CharUnits::fromQuantity(8));
4215 assert(RegAddr.getElementType() == CGF.Int8Ty);
4216
4217 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004218 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004219 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4220 CharUnits::fromQuantity(32));
4221 }
4222
4223 // Get the address of the saved value by scaling the number of
Fangrui Song6907ce22018-07-30 19:24:48 +00004224 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004225 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004226 llvm::Value *RegOffset =
4227 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4228 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4229 RegAddr.getPointer(), RegOffset),
4230 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4231 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4232
4233 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004234 NumRegs =
Fangrui Song6907ce22018-07-30 19:24:48 +00004235 Builder.CreateAdd(NumRegs,
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004236 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004237 Builder.CreateStore(NumRegs, NumRegsAddr);
4238
4239 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004240 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004241
John McCall7f416cc2015-09-08 08:05:57 +00004242 // Case 2: consume space in the overflow area.
4243 Address MemAddr = Address::invalid();
4244 {
4245 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004246
Roman Divacky039b9702016-02-20 08:31:24 +00004247 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4248
John McCall7f416cc2015-09-08 08:05:57 +00004249 // Everything in the overflow area is rounded up to a size of at least 4.
4250 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4251
4252 CharUnits Size;
4253 if (!isIndirect) {
4254 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004255 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004256 } else {
4257 Size = CGF.getPointerSize();
4258 }
4259
4260 Address OverflowAreaAddr =
4261 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004262 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004263 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004264 // Round up address of argument to alignment
4265 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4266 if (Align > OverflowAreaAlign) {
4267 llvm::Value *Ptr = OverflowArea.getPointer();
4268 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4269 Align);
4270 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004271
John McCall7f416cc2015-09-08 08:05:57 +00004272 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4273
4274 // Increase the overflow area.
4275 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4276 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4277 CGF.EmitBranch(Cont);
4278 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004279
4280 CGF.EmitBlock(Cont);
4281
John McCall7f416cc2015-09-08 08:05:57 +00004282 // Merge the cases with a phi.
4283 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4284 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004285
John McCall7f416cc2015-09-08 08:05:57 +00004286 // Load the pointer if the argument was passed indirectly.
4287 if (isIndirect) {
4288 Result = Address(Builder.CreateLoad(Result, "aggr"),
4289 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004290 }
4291
4292 return Result;
4293}
4294
John McCallea8d8bb2010-03-11 00:10:12 +00004295bool
4296PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4297 llvm::Value *Address) const {
4298 // This is calculated from the LLVM and GCC tables and verified
4299 // against gcc output. AFAIK all ABIs use the same encoding.
4300
4301 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004302
Chris Lattnerece04092012-02-07 00:39:47 +00004303 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004304 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4305 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4306 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4307
4308 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004309 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004310
4311 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004312 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004313
4314 // 64-76 are various 4-byte special-purpose registers:
4315 // 64: mq
4316 // 65: lr
4317 // 66: ctr
4318 // 67: ap
4319 // 68-75 cr0-7
4320 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004321 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004322
4323 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004324 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004325
4326 // 109: vrsave
4327 // 110: vscr
4328 // 111: spe_acc
4329 // 112: spefscr
4330 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004331 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004332
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004333 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004334}
4335
Roman Divackyd966e722012-05-09 18:22:46 +00004336// PowerPC-64
4337
4338namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004339/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004340class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004341public:
4342 enum ABIKind {
4343 ELFv1 = 0,
4344 ELFv2
4345 };
4346
4347private:
4348 static const unsigned GPRBits = 64;
4349 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004350 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004351 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004352
4353 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4354 // will be passed in a QPX register.
4355 bool IsQPXVectorTy(const Type *Ty) const {
4356 if (!HasQPX)
4357 return false;
4358
4359 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4360 unsigned NumElements = VT->getNumElements();
4361 if (NumElements == 1)
4362 return false;
4363
4364 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4365 if (getContext().getTypeSize(Ty) <= 256)
4366 return true;
4367 } else if (VT->getElementType()->
4368 isSpecificBuiltinType(BuiltinType::Float)) {
4369 if (getContext().getTypeSize(Ty) <= 128)
4370 return true;
4371 }
4372 }
4373
4374 return false;
4375 }
4376
4377 bool IsQPXVectorTy(QualType Ty) const {
4378 return IsQPXVectorTy(Ty.getTypePtr());
4379 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004380
4381public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004382 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4383 bool SoftFloatABI)
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004384 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
Hal Finkel415c2a32016-10-02 02:10:45 +00004385 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004386
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004387 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004388 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004389
4390 ABIArgInfo classifyReturnType(QualType RetTy) const;
4391 ABIArgInfo classifyArgumentType(QualType Ty) const;
4392
Reid Klecknere9f6a712014-10-31 17:10:41 +00004393 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4394 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4395 uint64_t Members) const override;
4396
Bill Schmidt84d37792012-10-12 19:26:17 +00004397 // TODO: We can add more logic to computeInfo to improve performance.
4398 // Example: For aggregate arguments that fit in a register, we could
4399 // use getDirectInReg (as is done below for structs containing a single
4400 // floating-point value) to avoid pushing them to memory on function
4401 // entry. This would require changing the logic in PPCISelLowering
4402 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004403 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004404 if (!getCXXABI().classifyReturnType(FI))
4405 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004406 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004407 // We rely on the default argument classification for the most part.
4408 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004409 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004410 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004411 if (T) {
4412 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004413 if (IsQPXVectorTy(T) ||
4414 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004415 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004416 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004417 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004418 continue;
4419 }
4420 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004421 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004422 }
4423 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004424
John McCall7f416cc2015-09-08 08:05:57 +00004425 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4426 QualType Ty) const override;
Bob Wilsonfa84fc92018-05-25 21:26:03 +00004427
4428 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4429 bool asReturnValue) const override {
4430 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4431 }
4432
4433 bool isSwiftErrorInRegister() const override {
4434 return false;
4435 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004436};
4437
4438class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004439
Bill Schmidt25cb3492012-10-03 19:18:57 +00004440public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004441 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004442 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4443 bool SoftFloatABI)
4444 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4445 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004446
Craig Topper4f12f102014-03-12 06:41:41 +00004447 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004448 // This is recovered from gcc output.
4449 return 1; // r1 is the dedicated stack pointer
4450 }
4451
4452 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004453 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004454};
4455
Roman Divackyd966e722012-05-09 18:22:46 +00004456class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4457public:
4458 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4459
Craig Topper4f12f102014-03-12 06:41:41 +00004460 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004461 // This is recovered from gcc output.
4462 return 1; // r1 is the dedicated stack pointer
4463 }
4464
4465 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004466 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004467};
4468
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004469}
Roman Divackyd966e722012-05-09 18:22:46 +00004470
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004471// Return true if the ABI requires Ty to be passed sign- or zero-
4472// extended to 64 bits.
4473bool
4474PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4475 // Treat an enum type as its underlying type.
4476 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4477 Ty = EnumTy->getDecl()->getIntegerType();
4478
4479 // Promotable integer types are required to be promoted by the ABI.
4480 if (Ty->isPromotableIntegerType())
4481 return true;
4482
4483 // In addition to the usual promotable integer types, we also need to
4484 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4485 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4486 switch (BT->getKind()) {
4487 case BuiltinType::Int:
4488 case BuiltinType::UInt:
4489 return true;
4490 default:
4491 break;
4492 }
4493
4494 return false;
4495}
4496
John McCall7f416cc2015-09-08 08:05:57 +00004497/// isAlignedParamType - Determine whether a type requires 16-byte or
4498/// higher alignment in the parameter area. Always returns at least 8.
4499CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004500 // Complex types are passed just like their elements.
4501 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4502 Ty = CTy->getElementType();
4503
4504 // Only vector types of size 16 bytes need alignment (larger types are
4505 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004506 if (IsQPXVectorTy(Ty)) {
4507 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004508 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004509
John McCall7f416cc2015-09-08 08:05:57 +00004510 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004511 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004512 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004513 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004514
4515 // For single-element float/vector structs, we consider the whole type
4516 // to have the same alignment requirements as its single element.
4517 const Type *AlignAsType = nullptr;
4518 const Type *EltType = isSingleElementStruct(Ty, getContext());
4519 if (EltType) {
4520 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004521 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004522 getContext().getTypeSize(EltType) == 128) ||
4523 (BT && BT->isFloatingPoint()))
4524 AlignAsType = EltType;
4525 }
4526
Ulrich Weigandb7122372014-07-21 00:48:09 +00004527 // Likewise for ELFv2 homogeneous aggregates.
4528 const Type *Base = nullptr;
4529 uint64_t Members = 0;
4530 if (!AlignAsType && Kind == ELFv2 &&
4531 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4532 AlignAsType = Base;
4533
Ulrich Weigand581badc2014-07-10 17:20:07 +00004534 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004535 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4536 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004537 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004538
John McCall7f416cc2015-09-08 08:05:57 +00004539 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004540 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004541 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004542 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004543
4544 // Otherwise, we only need alignment for any aggregate type that
4545 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004546 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4547 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004548 return CharUnits::fromQuantity(32);
4549 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004550 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004551
John McCall7f416cc2015-09-08 08:05:57 +00004552 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004553}
4554
Ulrich Weigandb7122372014-07-21 00:48:09 +00004555/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4556/// aggregate. Base is set to the base element type, and Members is set
4557/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004558bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4559 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004560 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4561 uint64_t NElements = AT->getSize().getZExtValue();
4562 if (NElements == 0)
4563 return false;
4564 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4565 return false;
4566 Members *= NElements;
4567 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4568 const RecordDecl *RD = RT->getDecl();
4569 if (RD->hasFlexibleArrayMember())
4570 return false;
4571
4572 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004573
4574 // If this is a C++ record, check the bases first.
4575 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4576 for (const auto &I : CXXRD->bases()) {
4577 // Ignore empty records.
4578 if (isEmptyRecord(getContext(), I.getType(), true))
4579 continue;
4580
4581 uint64_t FldMembers;
4582 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4583 return false;
4584
4585 Members += FldMembers;
4586 }
4587 }
4588
Ulrich Weigandb7122372014-07-21 00:48:09 +00004589 for (const auto *FD : RD->fields()) {
4590 // Ignore (non-zero arrays of) empty records.
4591 QualType FT = FD->getType();
4592 while (const ConstantArrayType *AT =
4593 getContext().getAsConstantArrayType(FT)) {
4594 if (AT->getSize().getZExtValue() == 0)
4595 return false;
4596 FT = AT->getElementType();
4597 }
4598 if (isEmptyRecord(getContext(), FT, true))
4599 continue;
4600
4601 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4602 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00004603 FD->isZeroLengthBitField(getContext()))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004604 continue;
4605
4606 uint64_t FldMembers;
4607 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4608 return false;
4609
4610 Members = (RD->isUnion() ?
4611 std::max(Members, FldMembers) : Members + FldMembers);
4612 }
4613
4614 if (!Base)
4615 return false;
4616
4617 // Ensure there is no padding.
4618 if (getContext().getTypeSize(Base) * Members !=
4619 getContext().getTypeSize(Ty))
4620 return false;
4621 } else {
4622 Members = 1;
4623 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4624 Members = 2;
4625 Ty = CT->getElementType();
4626 }
4627
Reid Klecknere9f6a712014-10-31 17:10:41 +00004628 // Most ABIs only support float, double, and some vector type widths.
4629 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004630 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004631
4632 // The base type must be the same for all members. Types that
4633 // agree in both total size and mode (float vs. vector) are
4634 // treated as being equivalent here.
4635 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004636 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004637 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004638 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4639 // so make sure to widen it explicitly.
4640 if (const VectorType *VT = Base->getAs<VectorType>()) {
4641 QualType EltTy = VT->getElementType();
4642 unsigned NumElements =
4643 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4644 Base = getContext()
4645 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4646 .getTypePtr();
4647 }
4648 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004649
4650 if (Base->isVectorType() != TyPtr->isVectorType() ||
4651 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4652 return false;
4653 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004654 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4655}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004656
Reid Klecknere9f6a712014-10-31 17:10:41 +00004657bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4658 // Homogeneous aggregates for ELFv2 must have base types of float,
4659 // double, long double, or 128-bit vectors.
4660 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4661 if (BT->getKind() == BuiltinType::Float ||
4662 BT->getKind() == BuiltinType::Double ||
Lei Huang449252d2018-07-05 04:32:01 +00004663 BT->getKind() == BuiltinType::LongDouble ||
4664 (getContext().getTargetInfo().hasFloat128Type() &&
4665 (BT->getKind() == BuiltinType::Float128))) {
Hal Finkel415c2a32016-10-02 02:10:45 +00004666 if (IsSoftFloatABI)
4667 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004668 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004669 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004670 }
4671 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004672 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004673 return true;
4674 }
4675 return false;
4676}
4677
4678bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4679 const Type *Base, uint64_t Members) const {
Lei Huang449252d2018-07-05 04:32:01 +00004680 // Vector and fp128 types require one register, other floating point types
4681 // require one or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004682 uint32_t NumRegs =
Lei Huang449252d2018-07-05 04:32:01 +00004683 ((getContext().getTargetInfo().hasFloat128Type() &&
4684 Base->isFloat128Type()) ||
4685 Base->isVectorType()) ? 1
4686 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004687
4688 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004689 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004690}
4691
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004692ABIArgInfo
4693PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004694 Ty = useFirstFieldIfTransparentUnion(Ty);
4695
Bill Schmidt90b22c92012-11-27 02:46:43 +00004696 if (Ty->isAnyComplexType())
4697 return ABIArgInfo::getDirect();
4698
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004699 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4700 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004701 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004702 uint64_t Size = getContext().getTypeSize(Ty);
4703 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004704 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004705 else if (Size < 128) {
4706 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4707 return ABIArgInfo::getDirect(CoerceTy);
4708 }
4709 }
4710
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004711 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004712 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004713 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004714
John McCall7f416cc2015-09-08 08:05:57 +00004715 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4716 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004717
4718 // ELFv2 homogeneous aggregates are passed as array types.
4719 const Type *Base = nullptr;
4720 uint64_t Members = 0;
4721 if (Kind == ELFv2 &&
4722 isHomogeneousAggregate(Ty, Base, Members)) {
4723 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4724 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4725 return ABIArgInfo::getDirect(CoerceTy);
4726 }
4727
Ulrich Weigand601957f2014-07-21 00:56:36 +00004728 // If an aggregate may end up fully in registers, we do not
4729 // use the ByVal method, but pass the aggregate as array.
4730 // This is usually beneficial since we avoid forcing the
4731 // back-end to store the argument to memory.
4732 uint64_t Bits = getContext().getTypeSize(Ty);
4733 if (Bits > 0 && Bits <= 8 * GPRBits) {
4734 llvm::Type *CoerceTy;
4735
4736 // Types up to 8 bytes are passed as integer type (which will be
4737 // properly aligned in the argument save area doubleword).
4738 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004739 CoerceTy =
4740 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004741 // Larger types are passed as arrays, with the base type selected
4742 // according to the required alignment in the save area.
4743 else {
4744 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004745 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004746 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4747 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4748 }
4749
4750 return ABIArgInfo::getDirect(CoerceTy);
4751 }
4752
Ulrich Weigandb7122372014-07-21 00:48:09 +00004753 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004754 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4755 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004756 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004757 }
4758
Alex Bradburye41a5e22018-01-12 20:08:16 +00004759 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4760 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004761}
4762
4763ABIArgInfo
4764PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4765 if (RetTy->isVoidType())
4766 return ABIArgInfo::getIgnore();
4767
Bill Schmidta3d121c2012-12-17 04:20:17 +00004768 if (RetTy->isAnyComplexType())
4769 return ABIArgInfo::getDirect();
4770
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004771 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4772 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004773 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004774 uint64_t Size = getContext().getTypeSize(RetTy);
4775 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004776 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004777 else if (Size < 128) {
4778 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4779 return ABIArgInfo::getDirect(CoerceTy);
4780 }
4781 }
4782
Ulrich Weigandb7122372014-07-21 00:48:09 +00004783 if (isAggregateTypeForABI(RetTy)) {
4784 // ELFv2 homogeneous aggregates are returned as array types.
4785 const Type *Base = nullptr;
4786 uint64_t Members = 0;
4787 if (Kind == ELFv2 &&
4788 isHomogeneousAggregate(RetTy, Base, Members)) {
4789 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4790 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4791 return ABIArgInfo::getDirect(CoerceTy);
4792 }
4793
4794 // ELFv2 small aggregates are returned in up to two registers.
4795 uint64_t Bits = getContext().getTypeSize(RetTy);
4796 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4797 if (Bits == 0)
4798 return ABIArgInfo::getIgnore();
4799
4800 llvm::Type *CoerceTy;
4801 if (Bits > GPRBits) {
4802 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004803 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004804 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004805 CoerceTy =
4806 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004807 return ABIArgInfo::getDirect(CoerceTy);
4808 }
4809
4810 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004811 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004812 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004813
Alex Bradburye41a5e22018-01-12 20:08:16 +00004814 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4815 : ABIArgInfo::getDirect());
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004816}
4817
Bill Schmidt25cb3492012-10-03 19:18:57 +00004818// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004819Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4820 QualType Ty) const {
4821 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4822 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004823
John McCall7f416cc2015-09-08 08:05:57 +00004824 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004825
Bill Schmidt924c4782013-01-14 17:45:36 +00004826 // If we have a complex type and the base type is smaller than 8 bytes,
4827 // the ABI calls for the real and imaginary parts to be right-adjusted
4828 // in separate doublewords. However, Clang expects us to produce a
4829 // pointer to a structure with the two parts packed tightly. So generate
4830 // loads of the real and imaginary parts relative to the va_list pointer,
4831 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004832 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4833 CharUnits EltSize = TypeInfo.first / 2;
4834 if (EltSize < SlotSize) {
4835 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4836 SlotSize * 2, SlotSize,
4837 SlotSize, /*AllowHigher*/ true);
4838
4839 Address RealAddr = Addr;
4840 Address ImagAddr = RealAddr;
4841 if (CGF.CGM.getDataLayout().isBigEndian()) {
4842 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4843 SlotSize - EltSize);
4844 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4845 2 * SlotSize - EltSize);
4846 } else {
4847 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4848 }
4849
4850 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4851 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4852 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4853 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4854 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4855
4856 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4857 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4858 /*init*/ true);
4859 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004860 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004861 }
4862
John McCall7f416cc2015-09-08 08:05:57 +00004863 // Otherwise, just use the general rule.
4864 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4865 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004866}
4867
4868static bool
4869PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4870 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004871 // This is calculated from the LLVM and GCC tables and verified
4872 // against gcc output. AFAIK all ABIs use the same encoding.
4873
4874 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4875
4876 llvm::IntegerType *i8 = CGF.Int8Ty;
4877 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4878 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4879 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4880
4881 // 0-31: r0-31, the 8-byte general-purpose registers
4882 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4883
4884 // 32-63: fp0-31, the 8-byte floating-point registers
4885 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4886
Hal Finkel84832a72016-08-30 02:38:34 +00004887 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004888 // 64: mq
4889 // 65: lr
4890 // 66: ctr
4891 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004892 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4893
4894 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004895 // 68-75 cr0-7
4896 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004897 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004898
4899 // 77-108: v0-31, the 16-byte vector registers
4900 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4901
4902 // 109: vrsave
4903 // 110: vscr
4904 // 111: spe_acc
4905 // 112: spefscr
4906 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004907 // 114: tfhar
4908 // 115: tfiar
4909 // 116: texasr
4910 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004911
4912 return false;
4913}
John McCallea8d8bb2010-03-11 00:10:12 +00004914
Bill Schmidt25cb3492012-10-03 19:18:57 +00004915bool
4916PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4917 CodeGen::CodeGenFunction &CGF,
4918 llvm::Value *Address) const {
4919
4920 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4921}
4922
4923bool
4924PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4925 llvm::Value *Address) const {
4926
4927 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4928}
4929
Chris Lattner0cf24192010-06-28 20:05:43 +00004930//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004931// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004932//===----------------------------------------------------------------------===//
4933
4934namespace {
4935
John McCall12f23522016-04-04 18:33:08 +00004936class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004937public:
4938 enum ABIKind {
4939 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004940 DarwinPCS,
4941 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004942 };
4943
4944private:
4945 ABIKind Kind;
4946
4947public:
John McCall12f23522016-04-04 18:33:08 +00004948 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4949 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004950
4951private:
4952 ABIKind getABIKind() const { return Kind; }
4953 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4954
4955 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004956 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004957 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4958 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4959 uint64_t Members) const override;
4960
Tim Northovera2ee4332014-03-29 15:09:45 +00004961 bool isIllegalVectorType(QualType Ty) const;
4962
David Blaikie1cbb9712014-11-14 19:09:44 +00004963 void computeInfo(CGFunctionInfo &FI) const override {
Akira Hatanakad791e922018-03-19 17:38:40 +00004964 if (!::classifyReturnType(getCXXABI(), FI, *this))
Reid Kleckner40ca9132014-05-13 22:05:45 +00004965 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004966
Tim Northoverb047bfa2014-11-27 21:02:49 +00004967 for (auto &it : FI.arguments())
4968 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004969 }
4970
John McCall7f416cc2015-09-08 08:05:57 +00004971 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4972 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004973
John McCall7f416cc2015-09-08 08:05:57 +00004974 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4975 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004976
John McCall7f416cc2015-09-08 08:05:57 +00004977 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4978 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004979 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4980 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4981 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004982 }
John McCall12f23522016-04-04 18:33:08 +00004983
Martin Storsjo502de222017-07-13 17:59:14 +00004984 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4985 QualType Ty) const override;
4986
John McCall56331e22018-01-07 06:28:49 +00004987 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00004988 bool asReturnValue) const override {
4989 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4990 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004991 bool isSwiftErrorInRegister() const override {
4992 return true;
4993 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004994
4995 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4996 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004997};
4998
Tim Northover573cbee2014-05-24 12:52:07 +00004999class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00005000public:
Tim Northover573cbee2014-05-24 12:52:07 +00005001 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5002 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00005003
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005004 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005005 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00005006 }
5007
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005008 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5009 return 31;
5010 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005011
Alexander Kornienko34eb2072015-04-11 02:00:23 +00005012 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005013
5014 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5015 CodeGen::CodeGenModule &CGM) const override {
5016 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5017 if (!FD)
5018 return;
5019 llvm::Function *Fn = cast<llvm::Function>(GV);
5020
5021 auto Kind = CGM.getCodeGenOpts().getSignReturnAddress();
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005022 if (Kind != CodeGenOptions::SignReturnAddressScope::None) {
5023 Fn->addFnAttr("sign-return-address",
5024 Kind == CodeGenOptions::SignReturnAddressScope::All
5025 ? "all"
5026 : "non-leaf");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005027
Luke Cheesemana8a24aa2018-10-25 15:23:49 +00005028 auto Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5029 Fn->addFnAttr("sign-return-address-key",
5030 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5031 ? "a_key"
5032 : "b_key");
5033 }
5034
5035 if (CGM.getCodeGenOpts().BranchTargetEnforcement)
5036 Fn->addFnAttr("branch-target-enforcement");
Luke Cheeseman0ac44c12018-08-17 12:55:05 +00005037 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005038};
Martin Storsjo1c8af272017-07-20 05:47:06 +00005039
5040class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5041public:
5042 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5043 : AArch64TargetCodeGenInfo(CGT, K) {}
5044
Eli Friedman540be6d2018-10-26 01:31:57 +00005045 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5046 CodeGen::CodeGenModule &CGM) const override;
5047
Martin Storsjo1c8af272017-07-20 05:47:06 +00005048 void getDependentLibraryOption(llvm::StringRef Lib,
5049 llvm::SmallString<24> &Opt) const override {
5050 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5051 }
5052
5053 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5054 llvm::SmallString<32> &Opt) const override {
5055 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5056 }
5057};
Eli Friedman540be6d2018-10-26 01:31:57 +00005058
5059void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5060 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5061 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5062 if (GV->isDeclaration())
5063 return;
5064 addStackProbeTargetAttributes(D, GV, CGM);
5065}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005066}
Tim Northovera2ee4332014-03-29 15:09:45 +00005067
Tim Northoverb047bfa2014-11-27 21:02:49 +00005068ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00005069 Ty = useFirstFieldIfTransparentUnion(Ty);
5070
Tim Northovera2ee4332014-03-29 15:09:45 +00005071 // Handle illegal vector types here.
5072 if (isIllegalVectorType(Ty)) {
5073 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005074 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00005075 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00005076 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5077 return ABIArgInfo::getDirect(ResType);
5078 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005079 if (Size <= 32) {
5080 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00005081 return ABIArgInfo::getDirect(ResType);
5082 }
5083 if (Size == 64) {
5084 llvm::Type *ResType =
5085 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00005086 return ABIArgInfo::getDirect(ResType);
5087 }
5088 if (Size == 128) {
5089 llvm::Type *ResType =
5090 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00005091 return ABIArgInfo::getDirect(ResType);
5092 }
John McCall7f416cc2015-09-08 08:05:57 +00005093 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005094 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005095
5096 if (!isAggregateTypeForABI(Ty)) {
5097 // Treat an enum type as its underlying type.
5098 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5099 Ty = EnumTy->getDecl()->getIntegerType();
5100
Tim Northovera2ee4332014-03-29 15:09:45 +00005101 return (Ty->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005102 ? ABIArgInfo::getExtend(Ty)
Tim Northovera2ee4332014-03-29 15:09:45 +00005103 : ABIArgInfo::getDirect());
5104 }
5105
5106 // Structures with either a non-trivial destructor or a non-trivial
5107 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00005108 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005109 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5110 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00005111 }
5112
5113 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5114 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00005115 uint64_t Size = getContext().getTypeSize(Ty);
5116 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5117 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005118 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5119 return ABIArgInfo::getIgnore();
5120
Tim Northover23bcad22017-05-05 22:36:06 +00005121 // GNU C mode. The only argument that gets ignored is an empty one with size
5122 // 0.
5123 if (IsEmpty && Size == 0)
5124 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00005125 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5126 }
5127
5128 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005129 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005130 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005131 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005132 return ABIArgInfo::getDirect(
5133 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005134 }
5135
5136 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005137 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005138 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5139 // same size and alignment.
5140 if (getTarget().isRenderScriptTarget()) {
5141 return coerceToIntArray(Ty, getContext(), getVMContext());
5142 }
Momchil Velikov20208cc2018-07-30 17:48:23 +00005143 unsigned Alignment;
5144 if (Kind == AArch64ABIInfo::AAPCS) {
5145 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5146 Alignment = Alignment < 128 ? 64 : 128;
5147 } else {
5148 Alignment = getContext().getTypeAlign(Ty);
5149 }
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005150 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005151
Tim Northovera2ee4332014-03-29 15:09:45 +00005152 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5153 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005154 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005155 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5156 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5157 }
5158 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5159 }
5160
John McCall7f416cc2015-09-08 08:05:57 +00005161 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005162}
5163
Tim Northover573cbee2014-05-24 12:52:07 +00005164ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005165 if (RetTy->isVoidType())
5166 return ABIArgInfo::getIgnore();
5167
5168 // Large vector types should be returned via memory.
5169 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005170 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005171
5172 if (!isAggregateTypeForABI(RetTy)) {
5173 // Treat an enum type as its underlying type.
5174 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5175 RetTy = EnumTy->getDecl()->getIntegerType();
5176
Tim Northover4dab6982014-04-18 13:46:08 +00005177 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
Alex Bradburye41a5e22018-01-12 20:08:16 +00005178 ? ABIArgInfo::getExtend(RetTy)
Tim Northover4dab6982014-04-18 13:46:08 +00005179 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005180 }
5181
Tim Northover23bcad22017-05-05 22:36:06 +00005182 uint64_t Size = getContext().getTypeSize(RetTy);
5183 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005184 return ABIArgInfo::getIgnore();
5185
Craig Topper8a13c412014-05-21 05:09:00 +00005186 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005187 uint64_t Members = 0;
5188 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005189 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5190 return ABIArgInfo::getDirect();
5191
5192 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005193 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005194 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5195 // same size and alignment.
5196 if (getTarget().isRenderScriptTarget()) {
5197 return coerceToIntArray(RetTy, getContext(), getVMContext());
5198 }
Pete Cooper635b5092015-04-17 22:16:24 +00005199 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005200 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005201
5202 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5203 // For aggregates with 16-byte alignment, we use i128.
5204 if (Alignment < 128 && Size == 128) {
5205 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5206 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5207 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005208 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5209 }
5210
John McCall7f416cc2015-09-08 08:05:57 +00005211 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005212}
5213
Tim Northover573cbee2014-05-24 12:52:07 +00005214/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5215bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005216 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5217 // Check whether VT is legal.
5218 unsigned NumElements = VT->getNumElements();
5219 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005220 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005221 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005222 return true;
5223 return Size != 64 && (Size != 128 || NumElements == 1);
5224 }
5225 return false;
5226}
5227
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005228bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5229 llvm::Type *eltTy,
5230 unsigned elts) const {
5231 if (!llvm::isPowerOf2_32(elts))
5232 return false;
5233 if (totalSize.getQuantity() != 8 &&
5234 (totalSize.getQuantity() != 16 || elts == 1))
5235 return false;
5236 return true;
5237}
5238
Reid Klecknere9f6a712014-10-31 17:10:41 +00005239bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5240 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5241 // point type or a short-vector type. This is the same as the 32-bit ABI,
5242 // but with the difference that any floating-point type is allowed,
5243 // including __fp16.
5244 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5245 if (BT->isFloatingPoint())
5246 return true;
5247 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5248 unsigned VecSize = getContext().getTypeSize(VT);
5249 if (VecSize == 64 || VecSize == 128)
5250 return true;
5251 }
5252 return false;
5253}
5254
5255bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5256 uint64_t Members) const {
5257 return Members <= 4;
5258}
5259
John McCall7f416cc2015-09-08 08:05:57 +00005260Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005261 QualType Ty,
5262 CodeGenFunction &CGF) const {
5263 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005264 bool IsIndirect = AI.isIndirect();
5265
Tim Northoverb047bfa2014-11-27 21:02:49 +00005266 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5267 if (IsIndirect)
5268 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5269 else if (AI.getCoerceToType())
5270 BaseTy = AI.getCoerceToType();
5271
5272 unsigned NumRegs = 1;
5273 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5274 BaseTy = ArrTy->getElementType();
5275 NumRegs = ArrTy->getNumElements();
5276 }
5277 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5278
Tim Northovera2ee4332014-03-29 15:09:45 +00005279 // The AArch64 va_list type and handling is specified in the Procedure Call
5280 // Standard, section B.4:
5281 //
5282 // struct {
5283 // void *__stack;
5284 // void *__gr_top;
5285 // void *__vr_top;
5286 // int __gr_offs;
5287 // int __vr_offs;
5288 // };
5289
5290 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5291 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5292 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5293 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005294
John McCall7f416cc2015-09-08 08:05:57 +00005295 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5296 CharUnits TyAlign = TyInfo.second;
5297
5298 Address reg_offs_p = Address::invalid();
5299 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005300 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005301 CharUnits reg_top_offset;
5302 int RegSize = IsIndirect ? 8 : TyInfo.first.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
David Blaikie2e804282015-04-05 22:47:07 +00005305 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005306 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5307 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005308 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5309 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005310 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005311 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005312 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005313 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005314 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005315 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5316 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005317 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5318 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005319 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005320 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005321 }
5322
5323 //=======================================
5324 // Find out where argument was passed
5325 //=======================================
5326
5327 // If reg_offs >= 0 we're already using the stack for this type of
5328 // argument. We don't want to keep updating reg_offs (in case it overflows,
5329 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5330 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005331 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005332 UsingStack = CGF.Builder.CreateICmpSGE(
5333 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5334
5335 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5336
5337 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005338 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005339 CGF.EmitBlock(MaybeRegBlock);
5340
5341 // Integer arguments may need to correct register alignment (for example a
5342 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5343 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005344 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5345 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005346
5347 reg_offs = CGF.Builder.CreateAdd(
5348 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5349 "align_regoffs");
5350 reg_offs = CGF.Builder.CreateAnd(
5351 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5352 "aligned_regoffs");
5353 }
5354
5355 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005356 // The fact that this is done unconditionally reflects the fact that
5357 // allocating an argument to the stack also uses up all the remaining
5358 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005359 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005360 NewOffset = CGF.Builder.CreateAdd(
5361 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5362 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5363
5364 // Now we're in a position to decide whether this argument really was in
5365 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005366 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005367 InRegs = CGF.Builder.CreateICmpSLE(
5368 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5369
5370 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5371
5372 //=======================================
5373 // Argument was in registers
5374 //=======================================
5375
5376 // Now we emit the code for if the argument was originally passed in
5377 // registers. First start the appropriate block:
5378 CGF.EmitBlock(InRegBlock);
5379
John McCall7f416cc2015-09-08 08:05:57 +00005380 llvm::Value *reg_top = nullptr;
5381 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5382 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005383 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005384 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5385 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5386 Address RegAddr = Address::invalid();
5387 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005388
5389 if (IsIndirect) {
5390 // If it's been passed indirectly (actually a struct), whatever we find from
5391 // stored registers or on the stack will actually be a struct **.
5392 MemTy = llvm::PointerType::getUnqual(MemTy);
5393 }
5394
Craig Topper8a13c412014-05-21 05:09:00 +00005395 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005396 uint64_t NumMembers = 0;
5397 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005398 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005399 // Homogeneous aggregates passed in registers will have their elements split
5400 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5401 // qN+1, ...). We reload and store into a temporary local variable
5402 // contiguously.
5403 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005404 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005405 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5406 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005407 Address Tmp = CGF.CreateTempAlloca(HFATy,
5408 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005409
John McCall7f416cc2015-09-08 08:05:57 +00005410 // On big-endian platforms, the value will be right-aligned in its slot.
5411 int Offset = 0;
5412 if (CGF.CGM.getDataLayout().isBigEndian() &&
5413 BaseTyInfo.first.getQuantity() < 16)
5414 Offset = 16 - BaseTyInfo.first.getQuantity();
5415
Tim Northovera2ee4332014-03-29 15:09:45 +00005416 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005417 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5418 Address LoadAddr =
5419 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5420 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5421
5422 Address StoreAddr =
5423 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005424
5425 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5426 CGF.Builder.CreateStore(Elem, StoreAddr);
5427 }
5428
John McCall7f416cc2015-09-08 08:05:57 +00005429 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005430 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005431 // Otherwise the object is contiguous in memory.
5432
5433 // It might be right-aligned in its slot.
5434 CharUnits SlotSize = BaseAddr.getAlignment();
5435 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005436 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005437 TyInfo.first < SlotSize) {
5438 CharUnits Offset = SlotSize - TyInfo.first;
5439 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005440 }
5441
John McCall7f416cc2015-09-08 08:05:57 +00005442 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005443 }
5444
5445 CGF.EmitBranch(ContBlock);
5446
5447 //=======================================
5448 // Argument was on the stack
5449 //=======================================
5450 CGF.EmitBlock(OnStackBlock);
5451
John McCall7f416cc2015-09-08 08:05:57 +00005452 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5453 CharUnits::Zero(), "stack_p");
5454 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005455
John McCall7f416cc2015-09-08 08:05:57 +00005456 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005457 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005458 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5459 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005460
John McCall7f416cc2015-09-08 08:05:57 +00005461 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005462
John McCall7f416cc2015-09-08 08:05:57 +00005463 OnStackPtr = CGF.Builder.CreateAdd(
5464 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005465 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005466 OnStackPtr = CGF.Builder.CreateAnd(
5467 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005468 "align_stack");
5469
John McCall7f416cc2015-09-08 08:05:57 +00005470 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005471 }
John McCall7f416cc2015-09-08 08:05:57 +00005472 Address OnStackAddr(OnStackPtr,
5473 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005474
John McCall7f416cc2015-09-08 08:05:57 +00005475 // All stack slots are multiples of 8 bytes.
5476 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5477 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005478 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005479 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005480 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005481 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005482
John McCall7f416cc2015-09-08 08:05:57 +00005483 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005484 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005485 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005486
5487 // Write the new value of __stack for the next call to va_arg
5488 CGF.Builder.CreateStore(NewStack, stack_p);
5489
5490 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005491 TyInfo.first < StackSlotSize) {
5492 CharUnits Offset = StackSlotSize - TyInfo.first;
5493 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005494 }
5495
John McCall7f416cc2015-09-08 08:05:57 +00005496 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005497
5498 CGF.EmitBranch(ContBlock);
5499
5500 //=======================================
5501 // Tidy up
5502 //=======================================
5503 CGF.EmitBlock(ContBlock);
5504
John McCall7f416cc2015-09-08 08:05:57 +00005505 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5506 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005507
5508 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005509 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5510 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005511
5512 return ResAddr;
5513}
5514
John McCall7f416cc2015-09-08 08:05:57 +00005515Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5516 CodeGenFunction &CGF) const {
5517 // The backend's lowering doesn't support va_arg for aggregates or
5518 // illegal vector types. Lower VAArg here for these cases and use
5519 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005520 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005521 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005522
John McCall7f416cc2015-09-08 08:05:57 +00005523 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005524
John McCall7f416cc2015-09-08 08:05:57 +00005525 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005526 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005527 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5528 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5529 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005530 }
5531
John McCall7f416cc2015-09-08 08:05:57 +00005532 // The size of the actual thing passed, which might end up just
5533 // being a pointer for indirect types.
5534 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5535
5536 // Arguments bigger than 16 bytes which aren't homogeneous
5537 // aggregates should be passed indirectly.
5538 bool IsIndirect = false;
5539 if (TyInfo.first.getQuantity() > 16) {
5540 const Type *Base = nullptr;
5541 uint64_t Members = 0;
5542 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005543 }
5544
John McCall7f416cc2015-09-08 08:05:57 +00005545 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5546 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005547}
5548
Martin Storsjo502de222017-07-13 17:59:14 +00005549Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5550 QualType Ty) const {
5551 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5552 CGF.getContext().getTypeInfoInChars(Ty),
5553 CharUnits::fromQuantity(8),
5554 /*allowHigherAlign*/ false);
5555}
5556
Tim Northovera2ee4332014-03-29 15:09:45 +00005557//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005558// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005559//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005560
5561namespace {
5562
John McCall12f23522016-04-04 18:33:08 +00005563class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005564public:
5565 enum ABIKind {
5566 APCS = 0,
5567 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005568 AAPCS_VFP = 2,
5569 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005570 };
5571
5572private:
5573 ABIKind Kind;
5574
5575public:
John McCall12f23522016-04-04 18:33:08 +00005576 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5577 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005578 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005579 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005580
John McCall3480ef22011-08-30 01:42:09 +00005581 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005582 switch (getTarget().getTriple().getEnvironment()) {
5583 case llvm::Triple::Android:
5584 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005585 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005586 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005587 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005588 case llvm::Triple::MuslEABI:
5589 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005590 return true;
5591 default:
5592 return false;
5593 }
John McCall3480ef22011-08-30 01:42:09 +00005594 }
5595
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005596 bool isEABIHF() const {
5597 switch (getTarget().getTriple().getEnvironment()) {
5598 case llvm::Triple::EABIHF:
5599 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005600 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005601 return true;
5602 default:
5603 return false;
5604 }
5605 }
5606
Daniel Dunbar020daa92009-09-12 01:00:39 +00005607 ABIKind getABIKind() const { return Kind; }
5608
Tim Northovera484bc02013-10-01 14:34:25 +00005609private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005610 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005611 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005612 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5613 uint64_t Members) const;
5614 ABIArgInfo coerceIllegalVector(QualType Ty) const;
Manman Renfef9e312012-10-16 19:18:39 +00005615 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005616
Reid Klecknere9f6a712014-10-31 17:10:41 +00005617 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5618 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5619 uint64_t Members) const override;
5620
Craig Topper4f12f102014-03-12 06:41:41 +00005621 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005622
John McCall7f416cc2015-09-08 08:05:57 +00005623 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5624 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005625
5626 llvm::CallingConv::ID getLLVMDefaultCC() const;
5627 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005628 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005629
John McCall56331e22018-01-07 06:28:49 +00005630 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
John McCall12f23522016-04-04 18:33:08 +00005631 bool asReturnValue) const override {
5632 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5633 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005634 bool isSwiftErrorInRegister() const override {
5635 return true;
5636 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005637 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5638 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005639};
5640
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005641class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5642public:
Chris Lattner2b037972010-07-29 02:01:43 +00005643 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5644 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005645
John McCall3480ef22011-08-30 01:42:09 +00005646 const ARMABIInfo &getABIInfo() const {
5647 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5648 }
5649
Craig Topper4f12f102014-03-12 06:41:41 +00005650 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005651 return 13;
5652 }
Roman Divackyc1617352011-05-18 19:36:54 +00005653
Craig Topper4f12f102014-03-12 06:41:41 +00005654 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005655 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005656 }
5657
Roman Divackyc1617352011-05-18 19:36:54 +00005658 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005659 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005660 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005661
5662 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005663 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005664 return false;
5665 }
John McCall3480ef22011-08-30 01:42:09 +00005666
Craig Topper4f12f102014-03-12 06:41:41 +00005667 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005668 if (getABIInfo().isEABI()) return 88;
5669 return TargetCodeGenInfo::getSizeOfUnwindException();
5670 }
Tim Northovera484bc02013-10-01 14:34:25 +00005671
Eric Christopher162c91c2015-06-05 22:03:00 +00005672 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005673 CodeGen::CodeGenModule &CGM) const override {
5674 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005675 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005676 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005677 if (!FD)
5678 return;
5679
5680 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5681 if (!Attr)
5682 return;
5683
5684 const char *Kind;
5685 switch (Attr->getInterrupt()) {
5686 case ARMInterruptAttr::Generic: Kind = ""; break;
5687 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5688 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5689 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5690 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5691 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5692 }
5693
5694 llvm::Function *Fn = cast<llvm::Function>(GV);
5695
5696 Fn->addFnAttr("interrupt", Kind);
5697
Tim Northover5627d392015-10-30 16:30:45 +00005698 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5699 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005700 return;
5701
5702 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5703 // however this is not necessarily true on taking any interrupt. Instruct
5704 // the backend to perform a realignment as part of the function prologue.
5705 llvm::AttrBuilder B;
5706 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005707 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005708 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005709};
5710
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005711class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005712public:
5713 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5714 : ARMTargetCodeGenInfo(CGT, K) {}
5715
Eric Christopher162c91c2015-06-05 22:03:00 +00005716 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005717 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005718
5719 void getDependentLibraryOption(llvm::StringRef Lib,
5720 llvm::SmallString<24> &Opt) const override {
5721 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5722 }
5723
5724 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5725 llvm::SmallString<32> &Opt) const override {
5726 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5727 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005728};
5729
Eric Christopher162c91c2015-06-05 22:03:00 +00005730void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00005731 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5732 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5733 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005734 return;
Hans Wennborgd43f40d2018-02-23 13:47:36 +00005735 addStackProbeTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005736}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005737}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005738
Chris Lattner22326a12010-07-29 02:31:05 +00005739void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanakad791e922018-03-19 17:38:40 +00005740 if (!::classifyReturnType(getCXXABI(), FI, *this))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005741 FI.getReturnInfo() =
5742 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005743
Tim Northoverbc784d12015-02-24 17:22:40 +00005744 for (auto &I : FI.arguments())
5745 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005746
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005747 // Always honor user-specified calling convention.
5748 if (FI.getCallingConvention() != llvm::CallingConv::C)
5749 return;
5750
John McCall882987f2013-02-28 19:01:20 +00005751 llvm::CallingConv::ID cc = getRuntimeCC();
5752 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005753 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005754}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005755
John McCall882987f2013-02-28 19:01:20 +00005756/// Return the default calling convention that LLVM will use.
5757llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5758 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005759 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005760 return llvm::CallingConv::ARM_AAPCS_VFP;
5761 else if (isEABI())
5762 return llvm::CallingConv::ARM_AAPCS;
5763 else
5764 return llvm::CallingConv::ARM_APCS;
5765}
5766
5767/// Return the calling convention that our ABI would like us to use
5768/// as the C calling convention.
5769llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005770 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005771 case APCS: return llvm::CallingConv::ARM_APCS;
5772 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5773 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005774 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005775 }
John McCall882987f2013-02-28 19:01:20 +00005776 llvm_unreachable("bad ABI kind");
5777}
5778
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005779void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005780 assert(getRuntimeCC() == llvm::CallingConv::C);
5781
5782 // Don't muddy up the IR with a ton of explicit annotations if
5783 // they'd just match what LLVM will infer from the triple.
5784 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5785 if (abiCC != getLLVMDefaultCC())
5786 RuntimeCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005787}
5788
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005789ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5790 uint64_t Size = getContext().getTypeSize(Ty);
5791 if (Size <= 32) {
5792 llvm::Type *ResType =
5793 llvm::Type::getInt32Ty(getVMContext());
5794 return ABIArgInfo::getDirect(ResType);
5795 }
5796 if (Size == 64 || Size == 128) {
5797 llvm::Type *ResType = llvm::VectorType::get(
5798 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5799 return ABIArgInfo::getDirect(ResType);
5800 }
5801 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5802}
5803
5804ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5805 const Type *Base,
5806 uint64_t Members) const {
5807 assert(Base && "Base class should be set for homogeneous aggregate");
5808 // Base can be a floating-point or a vector.
5809 if (const VectorType *VT = Base->getAs<VectorType>()) {
5810 // FP16 vectors should be converted to integer vectors
5811 if (!getTarget().hasLegalHalfType() &&
5812 (VT->getElementType()->isFloat16Type() ||
5813 VT->getElementType()->isHalfType())) {
5814 uint64_t Size = getContext().getTypeSize(VT);
5815 llvm::Type *NewVecTy = llvm::VectorType::get(
5816 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5817 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5818 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5819 }
5820 }
5821 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5822}
5823
Tim Northoverbc784d12015-02-24 17:22:40 +00005824ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5825 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005826 // 6.1.2.1 The following argument types are VFP CPRCs:
5827 // A single-precision floating-point type (including promoted
5828 // half-precision types); A double-precision floating-point type;
5829 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5830 // with a Base Type of a single- or double-precision floating-point type,
5831 // 64-bit containerized vectors or 128-bit containerized vectors with one
5832 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005833 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005834
Reid Klecknerb1be6832014-11-15 01:41:41 +00005835 Ty = useFirstFieldIfTransparentUnion(Ty);
5836
Manman Renfef9e312012-10-16 19:18:39 +00005837 // Handle illegal vector types here.
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005838 if (isIllegalVectorType(Ty))
5839 return coerceIllegalVector(Ty);
Manman Renfef9e312012-10-16 19:18:39 +00005840
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00005841 // _Float16 and __fp16 get passed as if it were an int or float, but with
5842 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5843 // half type natively, and does not need to interwork with AAPCS code.
5844 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5845 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005846 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5847 llvm::Type::getFloatTy(getVMContext()) :
5848 llvm::Type::getInt32Ty(getVMContext());
5849 return ABIArgInfo::getDirect(ResType);
5850 }
5851
John McCalla1dee5302010-08-22 10:59:02 +00005852 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005853 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005854 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005855 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005856 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005857
Alex Bradburye41a5e22018-01-12 20:08:16 +00005858 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
Tim Northover5a1558e2014-11-07 22:30:50 +00005859 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005860 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005861
Oliver Stannard405bded2014-02-11 09:25:50 +00005862 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005863 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005864 }
Tim Northover1060eae2013-06-21 22:49:34 +00005865
Daniel Dunbar09d33622009-09-14 21:54:03 +00005866 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005867 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005868 return ABIArgInfo::getIgnore();
5869
Tim Northover5a1558e2014-11-07 22:30:50 +00005870 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005871 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5872 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005873 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005874 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00005875 if (isHomogeneousAggregate(Ty, Base, Members))
5876 return classifyHomogeneousAggregate(Ty, Base, Members);
Tim Northover5627d392015-10-30 16:30:45 +00005877 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5878 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5879 // this convention even for a variadic function: the backend will use GPRs
5880 // if needed.
5881 const Type *Base = nullptr;
5882 uint64_t Members = 0;
5883 if (isHomogeneousAggregate(Ty, Base, Members)) {
5884 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5885 llvm::Type *Ty =
5886 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5887 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5888 }
5889 }
5890
5891 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5892 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5893 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5894 // bigger than 128-bits, they get placed in space allocated by the caller,
5895 // and a pointer is passed.
5896 return ABIArgInfo::getIndirect(
5897 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005898 }
5899
Manman Ren6c30e132012-08-13 21:23:55 +00005900 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005901 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5902 // most 8-byte. We realign the indirect argument if type alignment is bigger
5903 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005904 uint64_t ABIAlign = 4;
Momchil Velikov20208cc2018-07-30 17:48:23 +00005905 uint64_t TyAlign;
Manman Ren505d68f2012-11-05 22:42:46 +00005906 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Momchil Velikov20208cc2018-07-30 17:48:23 +00005907 getABIKind() == ARMABIInfo::AAPCS) {
5908 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
Manman Ren505d68f2012-11-05 22:42:46 +00005909 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Momchil Velikov20208cc2018-07-30 17:48:23 +00005910 } else {
5911 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
5912 }
Manman Ren8cd99812012-11-06 04:58:01 +00005913 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005914 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005915 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5916 /*ByVal=*/true,
5917 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005918 }
5919
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005920 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5921 // same size and alignment.
5922 if (getTarget().isRenderScriptTarget()) {
5923 return coerceToIntArray(Ty, getContext(), getVMContext());
5924 }
5925
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005926 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005927 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005928 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005929 // FIXME: Try to match the types of the arguments more accurately where
5930 // we can.
Momchil Velikov20208cc2018-07-30 17:48:23 +00005931 if (TyAlign <= 4) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005932 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5933 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005934 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005935 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5936 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005937 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005938
Tim Northover5a1558e2014-11-07 22:30:50 +00005939 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005940}
5941
Chris Lattner458b2aa2010-07-29 02:16:43 +00005942static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005943 llvm::LLVMContext &VMContext) {
5944 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5945 // is called integer-like if its size is less than or equal to one word, and
5946 // the offset of each of its addressable sub-fields is zero.
5947
5948 uint64_t Size = Context.getTypeSize(Ty);
5949
5950 // Check that the type fits in a word.
5951 if (Size > 32)
5952 return false;
5953
5954 // FIXME: Handle vector types!
5955 if (Ty->isVectorType())
5956 return false;
5957
Daniel Dunbard53bac72009-09-14 02:20:34 +00005958 // Float types are never treated as "integer like".
5959 if (Ty->isRealFloatingType())
5960 return false;
5961
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005962 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005963 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005964 return true;
5965
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005966 // Small complex integer types are "integer like".
5967 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5968 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005969
5970 // Single element and zero sized arrays should be allowed, by the definition
5971 // above, but they are not.
5972
5973 // Otherwise, it must be a record type.
5974 const RecordType *RT = Ty->getAs<RecordType>();
5975 if (!RT) return false;
5976
5977 // Ignore records with flexible arrays.
5978 const RecordDecl *RD = RT->getDecl();
5979 if (RD->hasFlexibleArrayMember())
5980 return false;
5981
5982 // Check that all sub-fields are at offset 0, and are themselves "integer
5983 // like".
5984 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5985
5986 bool HadField = false;
5987 unsigned idx = 0;
5988 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5989 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005990 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005991
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005992 // Bit-fields are not addressable, we only need to verify they are "integer
5993 // like". We still have to disallow a subsequent non-bitfield, for example:
5994 // struct { int : 0; int x }
5995 // is non-integer like according to gcc.
5996 if (FD->isBitField()) {
5997 if (!RD->isUnion())
5998 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005999
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006000 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6001 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006002
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006003 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006004 }
6005
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006006 // Check if this field is at offset 0.
6007 if (Layout.getFieldOffset(idx) != 0)
6008 return false;
6009
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006010 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6011 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00006012
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00006013 // Only allow at most one field in a structure. This doesn't match the
6014 // wording above, but follows gcc in situations with a field following an
6015 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006016 if (!RD->isUnion()) {
6017 if (HadField)
6018 return false;
6019
6020 HadField = true;
6021 }
6022 }
6023
6024 return true;
6025}
6026
Oliver Stannard405bded2014-02-11 09:25:50 +00006027ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
6028 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00006029 bool IsEffectivelyAAPCS_VFP =
6030 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006031
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006032 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006033 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006034
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006035 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6036 // Large vector types should be returned via memory.
6037 if (getContext().getTypeSize(RetTy) > 128)
6038 return getNaturalAlignIndirect(RetTy);
6039 // FP16 vectors should be converted to integer vectors
6040 if (!getTarget().hasLegalHalfType() &&
6041 (VT->getElementType()->isFloat16Type() ||
6042 VT->getElementType()->isHalfType()))
6043 return coerceIllegalVector(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00006044 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00006045
Sjoerd Meijerca8f4e72018-01-23 10:13:49 +00006046 // _Float16 and __fp16 get returned as if it were an int or float, but with
6047 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6048 // half type natively, and does not need to interwork with AAPCS code.
6049 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6050 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00006051 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
6052 llvm::Type::getFloatTy(getVMContext()) :
6053 llvm::Type::getInt32Ty(getVMContext());
6054 return ABIArgInfo::getDirect(ResType);
6055 }
6056
John McCalla1dee5302010-08-22 10:59:02 +00006057 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00006058 // Treat an enum type as its underlying type.
6059 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6060 RetTy = EnumTy->getDecl()->getIntegerType();
6061
Alex Bradburye41a5e22018-01-12 20:08:16 +00006062 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
Tim Northover5a1558e2014-11-07 22:30:50 +00006063 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00006064 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006065
6066 // Are we following APCS?
6067 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00006068 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006069 return ABIArgInfo::getIgnore();
6070
Daniel Dunbareedf1512010-02-01 23:31:19 +00006071 // Complex types are all returned as packed integers.
6072 //
6073 // FIXME: Consider using 2 x vector types if the back end handles them
6074 // correctly.
6075 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00006076 return ABIArgInfo::getDirect(llvm::IntegerType::get(
6077 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00006078
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006079 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006080 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006081 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006082 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006083 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006084 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006085 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00006086 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6087 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006088 }
6089
6090 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00006091 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006092 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006093
6094 // Otherwise this is an AAPCS variant.
6095
Chris Lattner458b2aa2010-07-29 02:16:43 +00006096 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006097 return ABIArgInfo::getIgnore();
6098
Bob Wilson1d9269a2011-11-02 04:51:36 +00006099 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00006100 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00006101 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00006102 uint64_t Members = 0;
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006103 if (isHomogeneousAggregate(RetTy, Base, Members))
6104 return classifyHomogeneousAggregate(RetTy, Base, Members);
Bob Wilson1d9269a2011-11-02 04:51:36 +00006105 }
6106
Daniel Dunbar626f1d82009-09-13 08:03:58 +00006107 // Aggregates <= 4 bytes are returned in r0; other aggregates
6108 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00006109 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006110 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00006111 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6112 // same size and alignment.
6113 if (getTarget().isRenderScriptTarget()) {
6114 return coerceToIntArray(RetTy, getContext(), getVMContext());
6115 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00006116 if (getDataLayout().isBigEndian())
6117 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00006118 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00006119
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006120 // Return in the smallest viable integer type.
6121 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00006122 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006123 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00006124 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6125 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00006126 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6127 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6128 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00006129 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00006130 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00006131 }
6132
John McCall7f416cc2015-09-08 08:05:57 +00006133 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006134}
6135
Manman Renfef9e312012-10-16 19:18:39 +00006136/// isIllegalVector - check whether Ty is an illegal vector type.
6137bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00006138 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
Mikhail Maltseve04ab4f2018-09-12 09:19:19 +00006139 // On targets that don't support FP16, FP16 is expanded into float, and we
6140 // don't want the ABI to depend on whether or not FP16 is supported in
6141 // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6142 if (!getTarget().hasLegalHalfType() &&
6143 (VT->getElementType()->isFloat16Type() ||
6144 VT->getElementType()->isHalfType()))
6145 return true;
Stephen Hines8267e7d2015-12-04 01:39:30 +00006146 if (isAndroid()) {
6147 // Android shipped using Clang 3.1, which supported a slightly different
6148 // vector ABI. The primary differences were that 3-element vector types
6149 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6150 // accepts that legacy behavior for Android only.
6151 // Check whether VT is legal.
6152 unsigned NumElements = VT->getNumElements();
6153 // NumElements should be power of 2 or equal to 3.
6154 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6155 return true;
6156 } else {
6157 // Check whether VT is legal.
6158 unsigned NumElements = VT->getNumElements();
6159 uint64_t Size = getContext().getTypeSize(VT);
6160 // NumElements should be power of 2.
6161 if (!llvm::isPowerOf2_32(NumElements))
6162 return true;
6163 // Size should be greater than 32 bits.
6164 return Size <= 32;
6165 }
Manman Renfef9e312012-10-16 19:18:39 +00006166 }
6167 return false;
6168}
6169
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006170bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6171 llvm::Type *eltTy,
6172 unsigned numElts) const {
6173 if (!llvm::isPowerOf2_32(numElts))
6174 return false;
6175 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6176 if (size > 64)
6177 return false;
6178 if (vectorSize.getQuantity() != 8 &&
6179 (vectorSize.getQuantity() != 16 || numElts == 1))
6180 return false;
6181 return true;
6182}
6183
Reid Klecknere9f6a712014-10-31 17:10:41 +00006184bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6185 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6186 // double, or 64-bit or 128-bit vectors.
6187 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6188 if (BT->getKind() == BuiltinType::Float ||
6189 BT->getKind() == BuiltinType::Double ||
6190 BT->getKind() == BuiltinType::LongDouble)
6191 return true;
6192 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6193 unsigned VecSize = getContext().getTypeSize(VT);
6194 if (VecSize == 64 || VecSize == 128)
6195 return true;
6196 }
6197 return false;
6198}
6199
6200bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6201 uint64_t Members) const {
6202 return Members <= 4;
6203}
6204
John McCall7f416cc2015-09-08 08:05:57 +00006205Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6206 QualType Ty) const {
6207 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006208
John McCall7f416cc2015-09-08 08:05:57 +00006209 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006210 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006211 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6212 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6213 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006214 }
6215
John McCall7f416cc2015-09-08 08:05:57 +00006216 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6217 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006218
John McCall7f416cc2015-09-08 08:05:57 +00006219 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6220 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006221 const Type *Base = nullptr;
6222 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006223 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6224 IsIndirect = true;
6225
Tim Northover5627d392015-10-30 16:30:45 +00006226 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6227 // allocated by the caller.
6228 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6229 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6230 !isHomogeneousAggregate(Ty, Base, Members)) {
6231 IsIndirect = true;
6232
John McCall7f416cc2015-09-08 08:05:57 +00006233 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006234 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6235 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006236 // Our callers should be prepared to handle an under-aligned address.
6237 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6238 getABIKind() == ARMABIInfo::AAPCS) {
6239 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6240 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006241 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6242 // ARMv7k allows type alignment up to 16 bytes.
6243 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6244 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006245 } else {
6246 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006247 }
John McCall7f416cc2015-09-08 08:05:57 +00006248 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006249
John McCall7f416cc2015-09-08 08:05:57 +00006250 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6251 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006252}
6253
Chris Lattner0cf24192010-06-28 20:05:43 +00006254//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006255// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006256//===----------------------------------------------------------------------===//
6257
6258namespace {
6259
Justin Holewinski83e96682012-05-24 17:43:12 +00006260class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006261public:
Justin Holewinski36837432013-03-30 14:38:24 +00006262 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006263
6264 ABIArgInfo classifyReturnType(QualType RetTy) const;
6265 ABIArgInfo classifyArgumentType(QualType Ty) const;
6266
Craig Topper4f12f102014-03-12 06:41:41 +00006267 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006268 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6269 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006270};
6271
Justin Holewinski83e96682012-05-24 17:43:12 +00006272class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006273public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006274 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6275 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006276
Eric Christopher162c91c2015-06-05 22:03:00 +00006277 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006278 CodeGen::CodeGenModule &M) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00006279 bool shouldEmitStaticExternCAliases() const override;
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006280
Justin Holewinski36837432013-03-30 14:38:24 +00006281private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006282 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6283 // resulting MDNode to the nvvm.annotations MDNode.
6284 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006285};
6286
Justin Holewinski83e96682012-05-24 17:43:12 +00006287ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006288 if (RetTy->isVoidType())
6289 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006290
6291 // note: this is different from default ABI
6292 if (!RetTy->isScalarType())
6293 return ABIArgInfo::getDirect();
6294
6295 // Treat an enum type as its underlying type.
6296 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6297 RetTy = EnumTy->getDecl()->getIntegerType();
6298
Alex Bradburye41a5e22018-01-12 20:08:16 +00006299 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6300 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006301}
6302
Justin Holewinski83e96682012-05-24 17:43:12 +00006303ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006304 // Treat an enum type as its underlying type.
6305 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6306 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006307
Eli Bendersky95338a02014-10-29 13:43:21 +00006308 // Return aggregates type as indirect by value
6309 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006310 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006311
Alex Bradburye41a5e22018-01-12 20:08:16 +00006312 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6313 : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006314}
6315
Justin Holewinski83e96682012-05-24 17:43:12 +00006316void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006317 if (!getCXXABI().classifyReturnType(FI))
6318 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006319 for (auto &I : FI.arguments())
6320 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006321
6322 // Always honor user-specified calling convention.
6323 if (FI.getCallingConvention() != llvm::CallingConv::C)
6324 return;
6325
John McCall882987f2013-02-28 19:01:20 +00006326 FI.setEffectiveCallingConvention(getRuntimeCC());
6327}
6328
John McCall7f416cc2015-09-08 08:05:57 +00006329Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6330 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006331 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006332}
6333
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006334void NVPTXTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006335 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6336 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006337 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006338 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006339 if (!FD) return;
6340
6341 llvm::Function *F = cast<llvm::Function>(GV);
6342
6343 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006344 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006345 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006346 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006347 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006348 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006349 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6350 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006351 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006352 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006353 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006354 }
Justin Holewinski38031972011-10-05 17:58:44 +00006355
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006356 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006357 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006358 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006359 // __global__ functions cannot be called from the device, we do not
6360 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006361 if (FD->hasAttr<CUDAGlobalAttr>()) {
6362 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6363 addNVVMMetadata(F, "kernel", 1);
6364 }
Artem Belevich7093e402015-04-21 22:55:54 +00006365 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006366 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006367 llvm::APSInt MaxThreads(32);
6368 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6369 if (MaxThreads > 0)
6370 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6371
6372 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6373 // not specified in __launch_bounds__ or if the user specified a 0 value,
6374 // we don't have to add a PTX directive.
6375 if (Attr->getMinBlocks()) {
6376 llvm::APSInt MinBlocks(32);
6377 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6378 if (MinBlocks > 0)
6379 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6380 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006381 }
6382 }
Justin Holewinski38031972011-10-05 17:58:44 +00006383 }
6384}
6385
Eli Benderskye06a2c42014-04-15 16:57:05 +00006386void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6387 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006388 llvm::Module *M = F->getParent();
6389 llvm::LLVMContext &Ctx = M->getContext();
6390
6391 // Get "nvvm.annotations" metadata node
6392 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6393
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006394 llvm::Metadata *MDVals[] = {
6395 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6396 llvm::ConstantAsMetadata::get(
6397 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006398 // Append metadata to nvvm.annotations
6399 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6400}
Yaxun Liub0eee292018-03-29 14:50:00 +00006401
6402bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6403 return false;
6404}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006405}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006406
6407//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006408// SystemZ ABI Implementation
6409//===----------------------------------------------------------------------===//
6410
6411namespace {
6412
Bryan Chane3f1ed52016-04-28 13:56:43 +00006413class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006414 bool HasVector;
6415
Ulrich Weigand47445072013-05-06 16:26:41 +00006416public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006417 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006418 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006419
6420 bool isPromotableIntegerType(QualType Ty) const;
6421 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006422 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006423 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006424 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006425
6426 ABIArgInfo classifyReturnType(QualType RetTy) const;
6427 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6428
Craig Topper4f12f102014-03-12 06:41:41 +00006429 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006430 if (!getCXXABI().classifyReturnType(FI))
6431 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006432 for (auto &I : FI.arguments())
6433 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006434 }
6435
John McCall7f416cc2015-09-08 08:05:57 +00006436 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6437 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006438
John McCall56331e22018-01-07 06:28:49 +00006439 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
Bryan Chane3f1ed52016-04-28 13:56:43 +00006440 bool asReturnValue) const override {
6441 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6442 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006443 bool isSwiftErrorInRegister() const override {
Arnold Schwaighofer612d6932017-11-07 16:40:51 +00006444 return false;
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006445 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006446};
6447
6448class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6449public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006450 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6451 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006452};
6453
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006454}
Ulrich Weigand47445072013-05-06 16:26:41 +00006455
6456bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6457 // Treat an enum type as its underlying type.
6458 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6459 Ty = EnumTy->getDecl()->getIntegerType();
6460
6461 // Promotable integer types are required to be promoted by the ABI.
6462 if (Ty->isPromotableIntegerType())
6463 return true;
6464
6465 // 32-bit values must also be promoted.
6466 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6467 switch (BT->getKind()) {
6468 case BuiltinType::Int:
6469 case BuiltinType::UInt:
6470 return true;
6471 default:
6472 return false;
6473 }
6474 return false;
6475}
6476
6477bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006478 return (Ty->isAnyComplexType() ||
6479 Ty->isVectorType() ||
6480 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006481}
6482
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006483bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6484 return (HasVector &&
6485 Ty->isVectorType() &&
6486 getContext().getTypeSize(Ty) <= 128);
6487}
6488
Ulrich Weigand47445072013-05-06 16:26:41 +00006489bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6490 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6491 switch (BT->getKind()) {
6492 case BuiltinType::Float:
6493 case BuiltinType::Double:
6494 return true;
6495 default:
6496 return false;
6497 }
6498
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006499 return false;
6500}
6501
6502QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006503 if (const RecordType *RT = Ty->getAsStructureType()) {
6504 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006505 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006506
6507 // If this is a C++ record, check the bases first.
6508 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006509 for (const auto &I : CXXRD->bases()) {
6510 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006511
6512 // Empty bases don't affect things either way.
6513 if (isEmptyRecord(getContext(), Base, true))
6514 continue;
6515
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006516 if (!Found.isNull())
6517 return Ty;
6518 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006519 }
6520
6521 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006522 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006523 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006524 // Unlike isSingleElementStruct(), empty structure and array fields
6525 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006526 if (getContext().getLangOpts().CPlusPlus &&
Richard Smith866dee42018-04-02 18:29:43 +00006527 FD->isZeroLengthBitField(getContext()))
Ulrich Weigand759449c2015-03-30 13:49:01 +00006528 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006529
6530 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006531 // Nested structures still do though.
6532 if (!Found.isNull())
6533 return Ty;
6534 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006535 }
6536
6537 // Unlike isSingleElementStruct(), trailing padding is allowed.
6538 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006539 if (!Found.isNull())
6540 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006541 }
6542
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006543 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006544}
6545
John McCall7f416cc2015-09-08 08:05:57 +00006546Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6547 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006548 // Assume that va_list type is correct; should be pointer to LLVM type:
6549 // struct {
6550 // i64 __gpr;
6551 // i64 __fpr;
6552 // i8 *__overflow_arg_area;
6553 // i8 *__reg_save_area;
6554 // };
6555
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006556 // Every non-vector argument occupies 8 bytes and is passed by preference
6557 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6558 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006559 Ty = getContext().getCanonicalType(Ty);
6560 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006561 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006562 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006563 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006564 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006565 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006566 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006567 CharUnits UnpaddedSize;
6568 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006569 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006570 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6571 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006572 } else {
6573 if (AI.getCoerceToType())
6574 ArgTy = AI.getCoerceToType();
6575 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006576 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006577 UnpaddedSize = TyInfo.first;
6578 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006579 }
John McCall7f416cc2015-09-08 08:05:57 +00006580 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6581 if (IsVector && UnpaddedSize > PaddedSize)
6582 PaddedSize = CharUnits::fromQuantity(16);
6583 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006584
John McCall7f416cc2015-09-08 08:05:57 +00006585 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006586
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006587 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006588 llvm::Value *PaddedSizeV =
6589 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006590
6591 if (IsVector) {
6592 // Work out the address of a vector argument on the stack.
6593 // Vector arguments are always passed in the high bits of a
6594 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006595 Address OverflowArgAreaPtr =
6596 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006597 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006598 Address OverflowArgArea =
6599 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6600 TyInfo.second);
6601 Address MemAddr =
6602 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006603
6604 // Update overflow_arg_area_ptr pointer
6605 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006606 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6607 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006608 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6609
6610 return MemAddr;
6611 }
6612
John McCall7f416cc2015-09-08 08:05:57 +00006613 assert(PaddedSize.getQuantity() == 8);
6614
6615 unsigned MaxRegs, RegCountField, RegSaveIndex;
6616 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006617 if (InFPRs) {
6618 MaxRegs = 4; // Maximum of 4 FPR arguments
6619 RegCountField = 1; // __fpr
6620 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006621 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006622 } else {
6623 MaxRegs = 5; // Maximum of 5 GPR arguments
6624 RegCountField = 0; // __gpr
6625 RegSaveIndex = 2; // save offset for r2
6626 RegPadding = Padding; // values are passed in the low bits of a GPR
6627 }
6628
John McCall7f416cc2015-09-08 08:05:57 +00006629 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6630 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6631 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006632 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006633 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6634 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006635 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006636
6637 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6638 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6639 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6640 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6641
6642 // Emit code to load the value if it was passed in registers.
6643 CGF.EmitBlock(InRegBlock);
6644
6645 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006646 llvm::Value *ScaledRegCount =
6647 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6648 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006649 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6650 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006651 llvm::Value *RegOffset =
6652 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006653 Address RegSaveAreaPtr =
6654 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6655 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006656 llvm::Value *RegSaveArea =
6657 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006658 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6659 "raw_reg_addr"),
6660 PaddedSize);
6661 Address RegAddr =
6662 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006663
6664 // Update the register count
6665 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6666 llvm::Value *NewRegCount =
6667 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6668 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6669 CGF.EmitBranch(ContBlock);
6670
6671 // Emit code to load the value if it was passed in memory.
6672 CGF.EmitBlock(InMemBlock);
6673
6674 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006675 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6676 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6677 Address OverflowArgArea =
6678 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6679 PaddedSize);
6680 Address RawMemAddr =
6681 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6682 Address MemAddr =
6683 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006684
6685 // Update overflow_arg_area_ptr pointer
6686 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006687 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6688 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006689 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6690 CGF.EmitBranch(ContBlock);
6691
6692 // Return the appropriate result.
6693 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006694 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6695 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006696
6697 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006698 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6699 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006700
6701 return ResAddr;
6702}
6703
Ulrich Weigand47445072013-05-06 16:26:41 +00006704ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6705 if (RetTy->isVoidType())
6706 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006707 if (isVectorArgumentType(RetTy))
6708 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006709 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006710 return getNaturalAlignIndirect(RetTy);
Alex Bradburye41a5e22018-01-12 20:08:16 +00006711 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6712 : ABIArgInfo::getDirect());
Ulrich Weigand47445072013-05-06 16:26:41 +00006713}
6714
6715ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6716 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006717 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006718 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006719
6720 // Integers and enums are extended to full register width.
6721 if (isPromotableIntegerType(Ty))
Alex Bradburye41a5e22018-01-12 20:08:16 +00006722 return ABIArgInfo::getExtend(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006723
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006724 // Handle vector types and vector-like structure types. Note that
6725 // as opposed to float-like structure types, we do not allow any
6726 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006727 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006728 QualType SingleElementTy = GetSingleElementType(Ty);
6729 if (isVectorArgumentType(SingleElementTy) &&
6730 getContext().getTypeSize(SingleElementTy) == Size)
6731 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6732
6733 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006734 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006735 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006736
6737 // Handle small structures.
6738 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6739 // Structures with flexible arrays have variable length, so really
6740 // fail the size test above.
6741 const RecordDecl *RD = RT->getDecl();
6742 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006743 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006744
6745 // The structure is passed as an unextended integer, a float, or a double.
6746 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006747 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006748 assert(Size == 32 || Size == 64);
6749 if (Size == 32)
6750 PassTy = llvm::Type::getFloatTy(getVMContext());
6751 else
6752 PassTy = llvm::Type::getDoubleTy(getVMContext());
6753 } else
6754 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6755 return ABIArgInfo::getDirect(PassTy);
6756 }
6757
6758 // Non-structure compounds are passed indirectly.
6759 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006760 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006761
Craig Topper8a13c412014-05-21 05:09:00 +00006762 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006763}
6764
6765//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006766// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006767//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006768
6769namespace {
6770
6771class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6772public:
Chris Lattner2b037972010-07-29 02:01:43 +00006773 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6774 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006775 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006776 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006777};
6778
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006779}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006780
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006781void MSP430TargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006782 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6783 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006784 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006785 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006786 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
6787 if (!InterruptAttr)
6788 return;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006789
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006790 // Handle 'interrupt' attribute:
6791 llvm::Function *F = cast<llvm::Function>(GV);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006792
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006793 // Step 1: Set ISR calling convention.
6794 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006795
Anton Korobeynikov383e8272019-01-16 13:44:01 +00006796 // Step 2: Add attributes goodness.
6797 F->addFnAttr(llvm::Attribute::NoInline);
6798 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006799 }
6800}
6801
Chris Lattner0cf24192010-06-28 20:05:43 +00006802//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006803// MIPS ABI Implementation. This works for both little-endian and
6804// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006805//===----------------------------------------------------------------------===//
6806
John McCall943fae92010-05-27 06:19:26 +00006807namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006808class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006809 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006810 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6811 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006812 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006813 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006814 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006815 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006816public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006817 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006818 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006819 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006820
6821 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006822 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006823 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006824 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6825 QualType Ty) const override;
Alex Bradburye41a5e22018-01-12 20:08:16 +00006826 ABIArgInfo extendType(QualType Ty) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006827};
6828
John McCall943fae92010-05-27 06:19:26 +00006829class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006830 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006831public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006832 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6833 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006834 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006835
Craig Topper4f12f102014-03-12 06:41:41 +00006836 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006837 return 29;
6838 }
6839
Eric Christopher162c91c2015-06-05 22:03:00 +00006840 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006841 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006842 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006843 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006844 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006845
6846 if (FD->hasAttr<MipsLongCallAttr>())
6847 Fn->addFnAttr("long-call");
6848 else if (FD->hasAttr<MipsShortCallAttr>())
6849 Fn->addFnAttr("short-call");
6850
6851 // Other attributes do not have a meaning for declarations.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00006852 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006853 return;
6854
Reed Kotler3d5966f2013-03-13 20:40:30 +00006855 if (FD->hasAttr<Mips16Attr>()) {
6856 Fn->addFnAttr("mips16");
6857 }
6858 else if (FD->hasAttr<NoMips16Attr>()) {
6859 Fn->addFnAttr("nomips16");
6860 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006861
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006862 if (FD->hasAttr<MicroMipsAttr>())
6863 Fn->addFnAttr("micromips");
6864 else if (FD->hasAttr<NoMicroMipsAttr>())
6865 Fn->addFnAttr("nomicromips");
6866
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006867 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6868 if (!Attr)
6869 return;
6870
6871 const char *Kind;
6872 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006873 case MipsInterruptAttr::eic: Kind = "eic"; break;
6874 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6875 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6876 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6877 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6878 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6879 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6880 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6881 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6882 }
6883
6884 Fn->addFnAttr("interrupt", Kind);
6885
Reed Kotler373feca2013-01-16 17:10:28 +00006886 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006887
John McCall943fae92010-05-27 06:19:26 +00006888 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006889 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006890
Craig Topper4f12f102014-03-12 06:41:41 +00006891 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006892 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006893 }
John McCall943fae92010-05-27 06:19:26 +00006894};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006895}
John McCall943fae92010-05-27 06:19:26 +00006896
Eric Christopher7565e0d2015-05-29 23:09:49 +00006897void MipsABIInfo::CoerceToIntArgs(
6898 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006899 llvm::IntegerType *IntTy =
6900 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006901
6902 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6903 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6904 ArgList.push_back(IntTy);
6905
6906 // If necessary, add one more integer type to ArgList.
6907 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6908
6909 if (R)
6910 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006911}
6912
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006913// In N32/64, an aligned double precision floating point field is passed in
6914// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006915llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006916 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6917
6918 if (IsO32) {
6919 CoerceToIntArgs(TySize, ArgList);
6920 return llvm::StructType::get(getVMContext(), ArgList);
6921 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006922
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006923 if (Ty->isComplexType())
6924 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006925
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006926 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006927
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006928 // Unions/vectors are passed in integer registers.
6929 if (!RT || !RT->isStructureOrClassType()) {
6930 CoerceToIntArgs(TySize, ArgList);
6931 return llvm::StructType::get(getVMContext(), ArgList);
6932 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006933
6934 const RecordDecl *RD = RT->getDecl();
6935 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006936 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006937
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006938 uint64_t LastOffset = 0;
6939 unsigned idx = 0;
6940 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6941
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006942 // Iterate over fields in the struct/class and check if there are any aligned
6943 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006944 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6945 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006946 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006947 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6948
6949 if (!BT || BT->getKind() != BuiltinType::Double)
6950 continue;
6951
6952 uint64_t Offset = Layout.getFieldOffset(idx);
6953 if (Offset % 64) // Ignore doubles that are not aligned.
6954 continue;
6955
6956 // Add ((Offset - LastOffset) / 64) args of type i64.
6957 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6958 ArgList.push_back(I64);
6959
6960 // Add double type.
6961 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6962 LastOffset = Offset + 64;
6963 }
6964
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006965 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6966 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006967
6968 return llvm::StructType::get(getVMContext(), ArgList);
6969}
6970
Akira Hatanakaddd66342013-10-29 18:41:15 +00006971llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6972 uint64_t Offset) const {
6973 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006974 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006975
Akira Hatanakaddd66342013-10-29 18:41:15 +00006976 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006977}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006978
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006979ABIArgInfo
6980MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006981 Ty = useFirstFieldIfTransparentUnion(Ty);
6982
Akira Hatanaka1632af62012-01-09 19:31:25 +00006983 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006984 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006985 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006986
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006987 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6988 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006989 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6990 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006991
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006992 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006993 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006994 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006995 return ABIArgInfo::getIgnore();
6996
Mark Lacey3825e832013-10-06 01:33:34 +00006997 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006998 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006999 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00007000 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00007001
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007002 // If we have reached here, aggregates are passed directly by coercing to
7003 // another structure type. Padding is inserted if the offset of the
7004 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00007005 ABIArgInfo ArgInfo =
7006 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7007 getPaddingType(OrigOffset, CurrOffset));
7008 ArgInfo.setInReg(true);
7009 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007010 }
7011
7012 // Treat an enum type as its underlying type.
7013 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7014 Ty = EnumTy->getDecl()->getIntegerType();
7015
Daniel Sanders5b445b32014-10-24 14:42:42 +00007016 // All integral types are promoted to the GPR width.
7017 if (Ty->isIntegralOrEnumerationType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00007018 return extendType(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00007019
Akira Hatanakaddd66342013-10-29 18:41:15 +00007020 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00007021 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00007022}
7023
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007024llvm::Type*
7025MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00007026 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007027 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007028
Akira Hatanakab6f74432012-02-09 18:49:26 +00007029 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007030 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00007031 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7032 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007033
Akira Hatanakab6f74432012-02-09 18:49:26 +00007034 // N32/64 returns struct/classes in floating point registers if the
7035 // following conditions are met:
7036 // 1. The size of the struct/class is no larger than 128-bit.
7037 // 2. The struct/class has one or two fields all of which are floating
7038 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007039 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00007040 //
7041 // Any other composite results are returned in integer registers.
7042 //
7043 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7044 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7045 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007046 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007047
Akira Hatanakab6f74432012-02-09 18:49:26 +00007048 if (!BT || !BT->isFloatingPoint())
7049 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007050
David Blaikie2d7c57e2012-04-30 02:36:29 +00007051 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00007052 }
7053
7054 if (b == e)
7055 return llvm::StructType::get(getVMContext(), RTList,
7056 RD->hasAttr<PackedAttr>());
7057
7058 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007059 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007060 }
7061
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00007062 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007063 return llvm::StructType::get(getVMContext(), RTList);
7064}
7065
Akira Hatanakab579fe52011-06-02 00:09:17 +00007066ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00007067 uint64_t Size = getContext().getTypeSize(RetTy);
7068
Daniel Sandersed39f582014-09-04 13:28:14 +00007069 if (RetTy->isVoidType())
7070 return ABIArgInfo::getIgnore();
7071
7072 // O32 doesn't treat zero-sized structs differently from other structs.
7073 // However, N32/N64 ignores zero sized return values.
7074 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00007075 return ABIArgInfo::getIgnore();
7076
Akira Hatanakac37eddf2012-05-11 21:01:17 +00007077 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007078 if (Size <= 128) {
7079 if (RetTy->isAnyComplexType())
7080 return ABIArgInfo::getDirect();
7081
Daniel Sanderse5018b62014-09-04 15:05:39 +00007082 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00007083 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00007084 if (!IsO32 ||
7085 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7086 ABIArgInfo ArgInfo =
7087 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7088 ArgInfo.setInReg(true);
7089 return ArgInfo;
7090 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00007091 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00007092
John McCall7f416cc2015-09-08 08:05:57 +00007093 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007094 }
7095
7096 // Treat an enum type as its underlying type.
7097 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7098 RetTy = EnumTy->getDecl()->getIntegerType();
7099
Stefan Maksimovicb9da8a52018-07-30 10:44:46 +00007100 if (RetTy->isPromotableIntegerType())
7101 return ABIArgInfo::getExtend(RetTy);
7102
7103 if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7104 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7105 return ABIArgInfo::getSignExtend(RetTy);
7106
7107 return ABIArgInfo::getDirect();
Akira Hatanakab579fe52011-06-02 00:09:17 +00007108}
7109
7110void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00007111 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00007112 if (!getCXXABI().classifyReturnType(FI))
7113 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00007114
Eric Christopher7565e0d2015-05-29 23:09:49 +00007115 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00007116 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00007117
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007118 for (auto &I : FI.arguments())
7119 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00007120}
7121
John McCall7f416cc2015-09-08 08:05:57 +00007122Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7123 QualType OrigTy) const {
7124 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00007125
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007126 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7127 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00007128 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007129 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00007130 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007131 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00007132 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00007133 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00007134 DidPromote = true;
7135 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7136 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00007137 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00007138
John McCall7f416cc2015-09-08 08:05:57 +00007139 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007140
John McCall7f416cc2015-09-08 08:05:57 +00007141 // The alignment of things in the argument area is never larger than
7142 // StackAlignInBytes.
7143 TyInfo.second =
7144 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7145
7146 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7147 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7148
7149 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7150 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7151
7152
7153 // If there was a promotion, "unpromote" into a temporary.
7154 // TODO: can we just use a pointer into a subset of the original slot?
7155 if (DidPromote) {
7156 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7157 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7158
7159 // Truncate down to the right width.
7160 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7161 : CGF.IntPtrTy);
7162 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7163 if (OrigTy->isPointerType())
7164 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7165
7166 CGF.Builder.CreateStore(V, Temp);
7167 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007168 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007169
John McCall7f416cc2015-09-08 08:05:57 +00007170 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007171}
7172
Alex Bradburye41a5e22018-01-12 20:08:16 +00007173ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007174 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007175
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007176 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7177 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
Alex Bradburye41a5e22018-01-12 20:08:16 +00007178 return ABIArgInfo::getSignExtend(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007179
Alex Bradburye41a5e22018-01-12 20:08:16 +00007180 return ABIArgInfo::getExtend(Ty);
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007181}
7182
John McCall943fae92010-05-27 06:19:26 +00007183bool
7184MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7185 llvm::Value *Address) const {
7186 // This information comes from gcc's implementation, which seems to
7187 // as canonical as it gets.
7188
John McCall943fae92010-05-27 06:19:26 +00007189 // Everything on MIPS is 4 bytes. Double-precision FP registers
7190 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007191 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007192
7193 // 0-31 are the general purpose registers, $0 - $31.
7194 // 32-63 are the floating-point registers, $f0 - $f31.
7195 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7196 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007197 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007198
7199 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7200 // They are one bit wide and ignored here.
7201
7202 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7203 // (coprocessor 1 is the FP unit)
7204 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7205 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7206 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007207 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007208 return false;
7209}
7210
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007211//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007212// AVR ABI Implementation.
7213//===----------------------------------------------------------------------===//
7214
7215namespace {
7216class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7217public:
7218 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7219 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7220
7221 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007222 CodeGen::CodeGenModule &CGM) const override {
7223 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007224 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007225 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7226 if (!FD) return;
7227 auto *Fn = cast<llvm::Function>(GV);
7228
7229 if (FD->getAttr<AVRInterruptAttr>())
7230 Fn->addFnAttr("interrupt");
7231
7232 if (FD->getAttr<AVRSignalAttr>())
7233 Fn->addFnAttr("signal");
7234 }
7235};
7236}
7237
7238//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007239// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007240// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007241// handling.
7242//===----------------------------------------------------------------------===//
7243
7244namespace {
7245
7246class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7247public:
7248 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7249 : DefaultTargetCodeGenInfo(CGT) {}
7250
Eric Christopher162c91c2015-06-05 22:03:00 +00007251 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007252 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007253};
7254
Eric Christopher162c91c2015-06-05 22:03:00 +00007255void TCETargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007256 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7257 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007258 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007259 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007260 if (!FD) return;
7261
7262 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007263
David Blaikiebbafb8a2012-03-11 07:00:24 +00007264 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007265 if (FD->hasAttr<OpenCLKernelAttr>()) {
7266 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007267 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007268 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7269 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007270 // Convert the reqd_work_group_size() attributes to metadata.
7271 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007272 llvm::NamedMDNode *OpenCLMetadata =
7273 M.getModule().getOrInsertNamedMetadata(
7274 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007275
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007276 SmallVector<llvm::Metadata *, 5> Operands;
7277 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007278
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007279 Operands.push_back(
7280 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7281 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7282 Operands.push_back(
7283 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7284 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7285 Operands.push_back(
7286 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7287 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007288
Eric Christopher7565e0d2015-05-29 23:09:49 +00007289 // Add a boolean constant operand for "required" (true) or "hint"
7290 // (false) for implementing the work_group_size_hint attr later.
7291 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007292 Operands.push_back(
7293 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007294 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7295 }
7296 }
7297 }
7298}
7299
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007300}
John McCall943fae92010-05-27 06:19:26 +00007301
Tony Linthicum76329bf2011-12-12 21:14:55 +00007302//===----------------------------------------------------------------------===//
7303// Hexagon ABI Implementation
7304//===----------------------------------------------------------------------===//
7305
7306namespace {
7307
7308class HexagonABIInfo : public ABIInfo {
7309
7310
7311public:
7312 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7313
7314private:
7315
7316 ABIArgInfo classifyReturnType(QualType RetTy) const;
7317 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7318
Craig Topper4f12f102014-03-12 06:41:41 +00007319 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007320
John McCall7f416cc2015-09-08 08:05:57 +00007321 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7322 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007323};
7324
7325class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7326public:
7327 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7328 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7329
Craig Topper4f12f102014-03-12 06:41:41 +00007330 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007331 return 29;
7332 }
7333};
7334
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007335}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007336
7337void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007338 if (!getCXXABI().classifyReturnType(FI))
7339 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007340 for (auto &I : FI.arguments())
7341 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007342}
7343
7344ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7345 if (!isAggregateTypeForABI(Ty)) {
7346 // Treat an enum type as its underlying type.
7347 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7348 Ty = EnumTy->getDecl()->getIntegerType();
7349
Alex Bradburye41a5e22018-01-12 20:08:16 +00007350 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7351 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007352 }
7353
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007354 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7355 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7356
Tony Linthicum76329bf2011-12-12 21:14:55 +00007357 // Ignore empty records.
7358 if (isEmptyRecord(getContext(), Ty, true))
7359 return ABIArgInfo::getIgnore();
7360
Tony Linthicum76329bf2011-12-12 21:14:55 +00007361 uint64_t Size = getContext().getTypeSize(Ty);
7362 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007363 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007364 // Pass in the smallest viable integer type.
7365 else if (Size > 32)
7366 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7367 else if (Size > 16)
7368 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7369 else if (Size > 8)
7370 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7371 else
7372 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7373}
7374
7375ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7376 if (RetTy->isVoidType())
7377 return ABIArgInfo::getIgnore();
7378
7379 // Large vector types should be returned via memory.
7380 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007381 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007382
7383 if (!isAggregateTypeForABI(RetTy)) {
7384 // Treat an enum type as its underlying type.
7385 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7386 RetTy = EnumTy->getDecl()->getIntegerType();
7387
Alex Bradburye41a5e22018-01-12 20:08:16 +00007388 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7389 : ABIArgInfo::getDirect());
Tony Linthicum76329bf2011-12-12 21:14:55 +00007390 }
7391
Tony Linthicum76329bf2011-12-12 21:14:55 +00007392 if (isEmptyRecord(getContext(), RetTy, true))
7393 return ABIArgInfo::getIgnore();
7394
7395 // Aggregates <= 8 bytes are returned in r0; other aggregates
7396 // are returned indirectly.
7397 uint64_t Size = getContext().getTypeSize(RetTy);
7398 if (Size <= 64) {
7399 // Return in the smallest viable integer type.
7400 if (Size <= 8)
7401 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7402 if (Size <= 16)
7403 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7404 if (Size <= 32)
7405 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7406 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7407 }
7408
John McCall7f416cc2015-09-08 08:05:57 +00007409 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007410}
7411
John McCall7f416cc2015-09-08 08:05:57 +00007412Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7413 QualType Ty) const {
7414 // FIXME: Someone needs to audit that this handle alignment correctly.
7415 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7416 getContext().getTypeInfoInChars(Ty),
7417 CharUnits::fromQuantity(4),
7418 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007419}
7420
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007421//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007422// Lanai ABI Implementation
7423//===----------------------------------------------------------------------===//
7424
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007425namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007426class LanaiABIInfo : public DefaultABIInfo {
7427public:
7428 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7429
7430 bool shouldUseInReg(QualType Ty, CCState &State) const;
7431
7432 void computeInfo(CGFunctionInfo &FI) const override {
7433 CCState State(FI.getCallingConvention());
7434 // Lanai uses 4 registers to pass arguments unless the function has the
7435 // regparm attribute set.
7436 if (FI.getHasRegParm()) {
7437 State.FreeRegs = FI.getRegParm();
7438 } else {
7439 State.FreeRegs = 4;
7440 }
7441
7442 if (!getCXXABI().classifyReturnType(FI))
7443 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7444 for (auto &I : FI.arguments())
7445 I.info = classifyArgumentType(I.type, State);
7446 }
7447
Jacques Pienaare74d9132016-04-26 00:09:29 +00007448 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007449 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7450};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007451} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007452
7453bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7454 unsigned Size = getContext().getTypeSize(Ty);
7455 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7456
7457 if (SizeInRegs == 0)
7458 return false;
7459
7460 if (SizeInRegs > State.FreeRegs) {
7461 State.FreeRegs = 0;
7462 return false;
7463 }
7464
7465 State.FreeRegs -= SizeInRegs;
7466
7467 return true;
7468}
7469
Jacques Pienaare74d9132016-04-26 00:09:29 +00007470ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7471 CCState &State) const {
7472 if (!ByVal) {
7473 if (State.FreeRegs) {
7474 --State.FreeRegs; // Non-byval indirects just use one pointer.
7475 return getNaturalAlignIndirectInReg(Ty);
7476 }
7477 return getNaturalAlignIndirect(Ty, false);
7478 }
7479
7480 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007481 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007482 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7483 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7484 /*Realign=*/TypeAlign >
7485 MinABIStackAlignInBytes);
7486}
7487
Jacques Pienaard964cc22016-03-28 21:02:54 +00007488ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7489 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007490 // Check with the C++ ABI first.
7491 const RecordType *RT = Ty->getAs<RecordType>();
7492 if (RT) {
7493 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7494 if (RAA == CGCXXABI::RAA_Indirect) {
7495 return getIndirectResult(Ty, /*ByVal=*/false, State);
7496 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7497 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7498 }
7499 }
7500
7501 if (isAggregateTypeForABI(Ty)) {
7502 // Structures with flexible arrays are always indirect.
7503 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7504 return getIndirectResult(Ty, /*ByVal=*/true, State);
7505
7506 // Ignore empty structs/unions.
7507 if (isEmptyRecord(getContext(), Ty, true))
7508 return ABIArgInfo::getIgnore();
7509
7510 llvm::LLVMContext &LLVMContext = getVMContext();
7511 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7512 if (SizeInRegs <= State.FreeRegs) {
7513 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7514 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7515 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7516 State.FreeRegs -= SizeInRegs;
7517 return ABIArgInfo::getDirectInReg(Result);
7518 } else {
7519 State.FreeRegs = 0;
7520 }
7521 return getIndirectResult(Ty, true, State);
7522 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007523
7524 // Treat an enum type as its underlying type.
7525 if (const auto *EnumTy = Ty->getAs<EnumType>())
7526 Ty = EnumTy->getDecl()->getIntegerType();
7527
Jacques Pienaare74d9132016-04-26 00:09:29 +00007528 bool InReg = shouldUseInReg(Ty, State);
7529 if (Ty->isPromotableIntegerType()) {
7530 if (InReg)
7531 return ABIArgInfo::getDirectInReg();
Alex Bradburye41a5e22018-01-12 20:08:16 +00007532 return ABIArgInfo::getExtend(Ty);
Jacques Pienaare74d9132016-04-26 00:09:29 +00007533 }
7534 if (InReg)
7535 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007536 return ABIArgInfo::getDirect();
7537}
7538
7539namespace {
7540class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7541public:
7542 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7543 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7544};
7545}
7546
7547//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007548// AMDGPU ABI Implementation
7549//===----------------------------------------------------------------------===//
7550
7551namespace {
7552
Matt Arsenault88d7da02016-08-22 19:25:59 +00007553class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007554private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007555 static const unsigned MaxNumRegsForArgsRet = 16;
7556
Matt Arsenault3fe73952017-08-09 21:44:58 +00007557 unsigned numRegsForType(QualType Ty) const;
7558
7559 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7560 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7561 uint64_t Members) const override;
7562
7563public:
7564 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7565 DefaultABIInfo(CGT) {}
7566
7567 ABIArgInfo classifyReturnType(QualType RetTy) const;
7568 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7569 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007570
7571 void computeInfo(CGFunctionInfo &FI) const override;
7572};
7573
Matt Arsenault3fe73952017-08-09 21:44:58 +00007574bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7575 return true;
7576}
7577
7578bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7579 const Type *Base, uint64_t Members) const {
7580 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7581
7582 // Homogeneous Aggregates may occupy at most 16 registers.
7583 return Members * NumRegs <= MaxNumRegsForArgsRet;
7584}
7585
Matt Arsenault3fe73952017-08-09 21:44:58 +00007586/// Estimate number of registers the type will use when passed in registers.
7587unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7588 unsigned NumRegs = 0;
7589
7590 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7591 // Compute from the number of elements. The reported size is based on the
7592 // in-memory size, which includes the padding 4th element for 3-vectors.
7593 QualType EltTy = VT->getElementType();
7594 unsigned EltSize = getContext().getTypeSize(EltTy);
7595
7596 // 16-bit element vectors should be passed as packed.
7597 if (EltSize == 16)
7598 return (VT->getNumElements() + 1) / 2;
7599
7600 unsigned EltNumRegs = (EltSize + 31) / 32;
7601 return EltNumRegs * VT->getNumElements();
7602 }
7603
7604 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7605 const RecordDecl *RD = RT->getDecl();
7606 assert(!RD->hasFlexibleArrayMember());
7607
7608 for (const FieldDecl *Field : RD->fields()) {
7609 QualType FieldTy = Field->getType();
7610 NumRegs += numRegsForType(FieldTy);
7611 }
7612
7613 return NumRegs;
7614 }
7615
7616 return (getContext().getTypeSize(Ty) + 31) / 32;
7617}
7618
Matt Arsenault88d7da02016-08-22 19:25:59 +00007619void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007620 llvm::CallingConv::ID CC = FI.getCallingConvention();
7621
Matt Arsenault88d7da02016-08-22 19:25:59 +00007622 if (!getCXXABI().classifyReturnType(FI))
7623 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7624
Matt Arsenault3fe73952017-08-09 21:44:58 +00007625 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7626 for (auto &Arg : FI.arguments()) {
7627 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7628 Arg.info = classifyKernelArgumentType(Arg.type);
7629 } else {
7630 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7631 }
7632 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007633}
7634
Matt Arsenault3fe73952017-08-09 21:44:58 +00007635ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7636 if (isAggregateTypeForABI(RetTy)) {
7637 // Records with non-trivial destructors/copy-constructors should not be
7638 // returned by value.
7639 if (!getRecordArgABI(RetTy, getCXXABI())) {
7640 // Ignore empty structs/unions.
7641 if (isEmptyRecord(getContext(), RetTy, true))
7642 return ABIArgInfo::getIgnore();
7643
7644 // Lower single-element structs to just return a regular value.
7645 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7646 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7647
7648 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7649 const RecordDecl *RD = RT->getDecl();
7650 if (RD->hasFlexibleArrayMember())
7651 return DefaultABIInfo::classifyReturnType(RetTy);
7652 }
7653
7654 // Pack aggregates <= 4 bytes into single VGPR or pair.
7655 uint64_t Size = getContext().getTypeSize(RetTy);
7656 if (Size <= 16)
7657 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7658
7659 if (Size <= 32)
7660 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7661
7662 if (Size <= 64) {
7663 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7664 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7665 }
7666
7667 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7668 return ABIArgInfo::getDirect();
7669 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007670 }
7671
Matt Arsenault3fe73952017-08-09 21:44:58 +00007672 // Otherwise just do the default thing.
7673 return DefaultABIInfo::classifyReturnType(RetTy);
7674}
7675
7676/// For kernels all parameters are really passed in a special buffer. It doesn't
7677/// make sense to pass anything byval, so everything must be direct.
7678ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7679 Ty = useFirstFieldIfTransparentUnion(Ty);
7680
7681 // TODO: Can we omit empty structs?
7682
Matt Arsenault88d7da02016-08-22 19:25:59 +00007683 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007684 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7685 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007686
7687 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7688 // individual elements, which confuses the Clover OpenCL backend; therefore we
7689 // have to set it to false here. Other args of getDirect() are just defaults.
7690 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7691}
7692
Matt Arsenault3fe73952017-08-09 21:44:58 +00007693ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7694 unsigned &NumRegsLeft) const {
7695 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7696
7697 Ty = useFirstFieldIfTransparentUnion(Ty);
7698
7699 if (isAggregateTypeForABI(Ty)) {
7700 // Records with non-trivial destructors/copy-constructors should not be
7701 // passed by value.
7702 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7703 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7704
7705 // Ignore empty structs/unions.
7706 if (isEmptyRecord(getContext(), Ty, true))
7707 return ABIArgInfo::getIgnore();
7708
7709 // Lower single-element structs to just pass a regular value. TODO: We
7710 // could do reasonable-size multiple-element structs too, using getExpand(),
7711 // though watch out for things like bitfields.
7712 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7713 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7714
7715 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7716 const RecordDecl *RD = RT->getDecl();
7717 if (RD->hasFlexibleArrayMember())
7718 return DefaultABIInfo::classifyArgumentType(Ty);
7719 }
7720
7721 // Pack aggregates <= 8 bytes into single VGPR or pair.
7722 uint64_t Size = getContext().getTypeSize(Ty);
7723 if (Size <= 64) {
7724 unsigned NumRegs = (Size + 31) / 32;
7725 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7726
7727 if (Size <= 16)
7728 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7729
7730 if (Size <= 32)
7731 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7732
7733 // XXX: Should this be i64 instead, and should the limit increase?
7734 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7735 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7736 }
7737
7738 if (NumRegsLeft > 0) {
7739 unsigned NumRegs = numRegsForType(Ty);
7740 if (NumRegsLeft >= NumRegs) {
7741 NumRegsLeft -= NumRegs;
7742 return ABIArgInfo::getDirect();
7743 }
7744 }
7745 }
7746
7747 // Otherwise just do the default thing.
7748 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7749 if (!ArgInfo.isIndirect()) {
7750 unsigned NumRegs = numRegsForType(Ty);
7751 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7752 }
7753
7754 return ArgInfo;
7755}
7756
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007757class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7758public:
7759 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007760 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007761 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007762 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007763 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007764
Yaxun Liu402804b2016-12-15 08:09:08 +00007765 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7766 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007767
Alexander Richardson6d989432017-10-15 18:48:14 +00007768 LangAS getASTAllocaAddressSpace() const override {
7769 return getLangASFromTargetAS(
7770 getABIInfo().getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007771 }
Alexander Richardson6d989432017-10-15 18:48:14 +00007772 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7773 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007774 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7775 llvm::LLVMContext &C) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007776 llvm::Function *
7777 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7778 llvm::Function *BlockInvokeFunc,
7779 llvm::Value *BlockLiteral) const override;
Yaxun Liub0eee292018-03-29 14:50:00 +00007780 bool shouldEmitStaticExternCAliases() const override;
Yaxun Liu6c10a662018-06-12 00:16:33 +00007781 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007782};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007783}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007784
Eric Christopher162c91c2015-06-05 22:03:00 +00007785void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Rafael Espindoladeb10be2018-02-07 19:04:41 +00007786 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7787 if (GV->isDeclaration())
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007788 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007789 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007790 if (!FD)
7791 return;
7792
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007793 llvm::Function *F = cast<llvm::Function>(GV);
7794
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007795 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7796 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
Tony Tye1a3f3a22018-03-23 18:43:15 +00007797
7798 if (M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>() &&
7799 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
Tony Tye68e11a62018-03-23 18:51:45 +00007800 F->addFnAttr("amdgpu-implicitarg-num-bytes", "48");
Tony Tye1a3f3a22018-03-23 18:43:15 +00007801
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007802 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7803 if (ReqdWGS || FlatWGS) {
7804 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7805 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7806 if (ReqdWGS && Min == 0 && Max == 0)
7807 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007808
7809 if (Min != 0) {
7810 assert(Min <= Max && "Min must be less than or equal Max");
7811
7812 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7813 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7814 } else
7815 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007816 }
7817
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007818 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7819 unsigned Min = Attr->getMin();
7820 unsigned Max = Attr->getMax();
7821
7822 if (Min != 0) {
7823 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7824
7825 std::string AttrVal = llvm::utostr(Min);
7826 if (Max != 0)
7827 AttrVal = AttrVal + "," + llvm::utostr(Max);
7828 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7829 } else
7830 assert(Max == 0 && "Max must be zero");
7831 }
7832
7833 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007834 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007835
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007836 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007837 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7838 }
7839
7840 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7841 uint32_t NumVGPR = Attr->getNumVGPR();
7842
7843 if (NumVGPR != 0)
7844 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007845 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007846}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007847
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007848unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7849 return llvm::CallingConv::AMDGPU_KERNEL;
7850}
7851
Yaxun Liu402804b2016-12-15 08:09:08 +00007852// Currently LLVM assumes null pointers always have value 0,
7853// which results in incorrectly transformed IR. Therefore, instead of
7854// emitting null pointers in private and local address spaces, a null
7855// pointer in generic address space is emitted which is casted to a
7856// pointer in local or private address space.
7857llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7858 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7859 QualType QT) const {
7860 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7861 return llvm::ConstantPointerNull::get(PT);
7862
7863 auto &Ctx = CGM.getContext();
7864 auto NPT = llvm::PointerType::get(PT->getElementType(),
7865 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7866 return llvm::ConstantExpr::getAddrSpaceCast(
7867 llvm::ConstantPointerNull::get(NPT), PT);
7868}
7869
Alexander Richardson6d989432017-10-15 18:48:14 +00007870LangAS
Yaxun Liucbf647c2017-07-08 13:24:52 +00007871AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7872 const VarDecl *D) const {
7873 assert(!CGM.getLangOpts().OpenCL &&
7874 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7875 "Address space agnostic languages only");
Alexander Richardson6d989432017-10-15 18:48:14 +00007876 LangAS DefaultGlobalAS = getLangASFromTargetAS(
7877 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007878 if (!D)
7879 return DefaultGlobalAS;
7880
Alexander Richardson6d989432017-10-15 18:48:14 +00007881 LangAS AddrSpace = D->getType().getAddressSpace();
7882 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
Yaxun Liucbf647c2017-07-08 13:24:52 +00007883 if (AddrSpace != LangAS::Default)
7884 return AddrSpace;
7885
7886 if (CGM.isTypeConstant(D->getType(), false)) {
7887 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7888 return ConstAS.getValue();
7889 }
7890 return DefaultGlobalAS;
7891}
7892
Yaxun Liu39195062017-08-04 18:16:31 +00007893llvm::SyncScope::ID
7894AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7895 llvm::LLVMContext &C) const {
7896 StringRef Name;
7897 switch (S) {
7898 case SyncScope::OpenCLWorkGroup:
7899 Name = "workgroup";
7900 break;
7901 case SyncScope::OpenCLDevice:
7902 Name = "agent";
7903 break;
7904 case SyncScope::OpenCLAllSVMDevices:
7905 Name = "";
7906 break;
7907 case SyncScope::OpenCLSubGroup:
7908 Name = "subgroup";
7909 }
7910 return C.getOrInsertSyncScopeID(Name);
7911}
7912
Yaxun Liub0eee292018-03-29 14:50:00 +00007913bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7914 return false;
7915}
7916
Yaxun Liu4306f202018-04-20 17:01:03 +00007917void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
Yaxun Liu6c10a662018-06-12 00:16:33 +00007918 const FunctionType *&FT) const {
7919 FT = getABIInfo().getContext().adjustFunctionType(
7920 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
Yaxun Liu4306f202018-04-20 17:01:03 +00007921}
7922
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007923//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007924// SPARC v8 ABI Implementation.
7925// Based on the SPARC Compliance Definition version 2.4.1.
7926//
7927// Ensures that complex values are passed in registers.
7928//
7929namespace {
7930class SparcV8ABIInfo : public DefaultABIInfo {
7931public:
7932 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7933
7934private:
7935 ABIArgInfo classifyReturnType(QualType RetTy) const;
7936 void computeInfo(CGFunctionInfo &FI) const override;
7937};
7938} // end anonymous namespace
7939
7940
7941ABIArgInfo
7942SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7943 if (Ty->isAnyComplexType()) {
7944 return ABIArgInfo::getDirect();
7945 }
7946 else {
7947 return DefaultABIInfo::classifyReturnType(Ty);
7948 }
7949}
7950
7951void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7952
7953 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7954 for (auto &Arg : FI.arguments())
7955 Arg.info = classifyArgumentType(Arg.type);
7956}
7957
7958namespace {
7959class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7960public:
7961 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7962 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7963};
7964} // end anonymous namespace
7965
7966//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007967// SPARC v9 ABI Implementation.
7968// Based on the SPARC Compliance Definition version 2.4.1.
7969//
7970// Function arguments a mapped to a nominal "parameter array" and promoted to
7971// registers depending on their type. Each argument occupies 8 or 16 bytes in
7972// the array, structs larger than 16 bytes are passed indirectly.
7973//
7974// One case requires special care:
7975//
7976// struct mixed {
7977// int i;
7978// float f;
7979// };
7980//
7981// When a struct mixed is passed by value, it only occupies 8 bytes in the
7982// parameter array, but the int is passed in an integer register, and the float
7983// is passed in a floating point register. This is represented as two arguments
7984// with the LLVM IR inreg attribute:
7985//
7986// declare void f(i32 inreg %i, float inreg %f)
7987//
7988// The code generator will only allocate 4 bytes from the parameter array for
7989// the inreg arguments. All other arguments are allocated a multiple of 8
7990// bytes.
7991//
7992namespace {
7993class SparcV9ABIInfo : public ABIInfo {
7994public:
7995 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7996
7997private:
7998 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007999 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00008000 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8001 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008002
8003 // Coercion type builder for structs passed in registers. The coercion type
8004 // serves two purposes:
8005 //
8006 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8007 // in registers.
8008 // 2. Expose aligned floating point elements as first-level elements, so the
8009 // code generator knows to pass them in floating point registers.
8010 //
8011 // We also compute the InReg flag which indicates that the struct contains
8012 // aligned 32-bit floats.
8013 //
8014 struct CoerceBuilder {
8015 llvm::LLVMContext &Context;
8016 const llvm::DataLayout &DL;
8017 SmallVector<llvm::Type*, 8> Elems;
8018 uint64_t Size;
8019 bool InReg;
8020
8021 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8022 : Context(c), DL(dl), Size(0), InReg(false) {}
8023
8024 // Pad Elems with integers until Size is ToSize.
8025 void pad(uint64_t ToSize) {
8026 assert(ToSize >= Size && "Cannot remove elements");
8027 if (ToSize == Size)
8028 return;
8029
8030 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00008031 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008032 if (Aligned > Size && Aligned <= ToSize) {
8033 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8034 Size = Aligned;
8035 }
8036
8037 // Add whole 64-bit words.
8038 while (Size + 64 <= ToSize) {
8039 Elems.push_back(llvm::Type::getInt64Ty(Context));
8040 Size += 64;
8041 }
8042
8043 // Final in-word padding.
8044 if (Size < ToSize) {
8045 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8046 Size = ToSize;
8047 }
8048 }
8049
8050 // Add a floating point element at Offset.
8051 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8052 // Unaligned floats are treated as integers.
8053 if (Offset % Bits)
8054 return;
8055 // The InReg flag is only required if there are any floats < 64 bits.
8056 if (Bits < 64)
8057 InReg = true;
8058 pad(Offset);
8059 Elems.push_back(Ty);
8060 Size = Offset + Bits;
8061 }
8062
8063 // Add a struct type to the coercion type, starting at Offset (in bits).
8064 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8065 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8066 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8067 llvm::Type *ElemTy = StrTy->getElementType(i);
8068 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8069 switch (ElemTy->getTypeID()) {
8070 case llvm::Type::StructTyID:
8071 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8072 break;
8073 case llvm::Type::FloatTyID:
8074 addFloat(ElemOffset, ElemTy, 32);
8075 break;
8076 case llvm::Type::DoubleTyID:
8077 addFloat(ElemOffset, ElemTy, 64);
8078 break;
8079 case llvm::Type::FP128TyID:
8080 addFloat(ElemOffset, ElemTy, 128);
8081 break;
8082 case llvm::Type::PointerTyID:
8083 if (ElemOffset % 64 == 0) {
8084 pad(ElemOffset);
8085 Elems.push_back(ElemTy);
8086 Size += 64;
8087 }
8088 break;
8089 default:
8090 break;
8091 }
8092 }
8093 }
8094
8095 // Check if Ty is a usable substitute for the coercion type.
8096 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00008097 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008098 }
8099
8100 // Get the coercion type as a literal struct type.
8101 llvm::Type *getType() const {
8102 if (Elems.size() == 1)
8103 return Elems.front();
8104 else
8105 return llvm::StructType::get(Context, Elems);
8106 }
8107 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008108};
8109} // end anonymous namespace
8110
8111ABIArgInfo
8112SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8113 if (Ty->isVoidType())
8114 return ABIArgInfo::getIgnore();
8115
8116 uint64_t Size = getContext().getTypeSize(Ty);
8117
8118 // Anything too big to fit in registers is passed with an explicit indirect
8119 // pointer / sret pointer.
8120 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00008121 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008122
8123 // Treat an enum type as its underlying type.
8124 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8125 Ty = EnumTy->getDecl()->getIntegerType();
8126
8127 // Integer types smaller than a register are extended.
8128 if (Size < 64 && Ty->isIntegerType())
Alex Bradburye41a5e22018-01-12 20:08:16 +00008129 return ABIArgInfo::getExtend(Ty);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008130
8131 // Other non-aggregates go in registers.
8132 if (!isAggregateTypeForABI(Ty))
8133 return ABIArgInfo::getDirect();
8134
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008135 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8136 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8137 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00008138 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00008139
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008140 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008141 // Build a coercion type from the LLVM struct type.
8142 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8143 if (!StrTy)
8144 return ABIArgInfo::getDirect();
8145
8146 CoerceBuilder CB(getVMContext(), getDataLayout());
8147 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00008148 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00008149
8150 // Try to use the original type for coercion.
8151 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8152
8153 if (CB.InReg)
8154 return ABIArgInfo::getDirectInReg(CoerceTy);
8155 else
8156 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008157}
8158
John McCall7f416cc2015-09-08 08:05:57 +00008159Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8160 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008161 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8162 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8163 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8164 AI.setCoerceToType(ArgTy);
8165
John McCall7f416cc2015-09-08 08:05:57 +00008166 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008167
John McCall7f416cc2015-09-08 08:05:57 +00008168 CGBuilderTy &Builder = CGF.Builder;
8169 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8170 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8171
8172 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8173
8174 Address ArgAddr = Address::invalid();
8175 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008176 switch (AI.getKind()) {
8177 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008178 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008179 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008180 llvm_unreachable("Unsupported ABI kind for va_arg");
8181
John McCall7f416cc2015-09-08 08:05:57 +00008182 case ABIArgInfo::Extend: {
8183 Stride = SlotSize;
8184 CharUnits Offset = SlotSize - TypeInfo.first;
8185 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008186 break;
John McCall7f416cc2015-09-08 08:05:57 +00008187 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008188
John McCall7f416cc2015-09-08 08:05:57 +00008189 case ABIArgInfo::Direct: {
8190 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008191 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008192 ArgAddr = Addr;
8193 break;
John McCall7f416cc2015-09-08 08:05:57 +00008194 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008195
8196 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008197 Stride = SlotSize;
8198 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8199 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8200 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008201 break;
8202
8203 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008204 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008205 }
8206
8207 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008208 llvm::Value *NextPtr =
8209 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8210 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008211
John McCall7f416cc2015-09-08 08:05:57 +00008212 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008213}
8214
8215void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8216 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008217 for (auto &I : FI.arguments())
8218 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008219}
8220
8221namespace {
8222class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8223public:
8224 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8225 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008226
Craig Topper4f12f102014-03-12 06:41:41 +00008227 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008228 return 14;
8229 }
8230
8231 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008232 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008233};
8234} // end anonymous namespace
8235
Roman Divackyf02c9942014-02-24 18:46:27 +00008236bool
8237SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8238 llvm::Value *Address) const {
8239 // This is calculated from the LLVM and GCC tables and verified
8240 // against gcc output. AFAIK all ABIs use the same encoding.
8241
8242 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8243
8244 llvm::IntegerType *i8 = CGF.Int8Ty;
8245 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8246 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8247
8248 // 0-31: the 8-byte general-purpose registers
8249 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8250
8251 // 32-63: f0-31, the 4-byte floating-point registers
8252 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8253
8254 // Y = 64
8255 // PSR = 65
8256 // WIM = 66
8257 // TBR = 67
8258 // PC = 68
8259 // NPC = 69
8260 // FSR = 70
8261 // CSR = 71
8262 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008263
Roman Divackyf02c9942014-02-24 18:46:27 +00008264 // 72-87: d0-15, the 8-byte floating-point registers
8265 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8266
8267 return false;
8268}
8269
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008270// ARC ABI implementation.
8271namespace {
8272
8273class ARCABIInfo : public DefaultABIInfo {
8274public:
8275 using DefaultABIInfo::DefaultABIInfo;
8276
8277private:
8278 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8279 QualType Ty) const override;
8280
8281 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
8282 if (!State.FreeRegs)
8283 return;
8284 if (Info.isIndirect() && Info.getInReg())
8285 State.FreeRegs--;
8286 else if (Info.isDirect() && Info.getInReg()) {
8287 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
8288 if (sz < State.FreeRegs)
8289 State.FreeRegs -= sz;
8290 else
8291 State.FreeRegs = 0;
8292 }
8293 }
8294
8295 void computeInfo(CGFunctionInfo &FI) const override {
8296 CCState State(FI.getCallingConvention());
8297 // ARC uses 8 registers to pass arguments.
8298 State.FreeRegs = 8;
8299
8300 if (!getCXXABI().classifyReturnType(FI))
8301 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8302 updateState(FI.getReturnInfo(), FI.getReturnType(), State);
8303 for (auto &I : FI.arguments()) {
8304 I.info = classifyArgumentType(I.type, State.FreeRegs);
8305 updateState(I.info, I.type, State);
8306 }
8307 }
8308
8309 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
8310 ABIArgInfo getIndirectByValue(QualType Ty) const;
8311 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
8312 ABIArgInfo classifyReturnType(QualType RetTy) const;
8313};
8314
8315class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
8316public:
8317 ARCTargetCodeGenInfo(CodeGenTypes &CGT)
8318 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {}
8319};
8320
8321
8322ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
8323 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
8324 getNaturalAlignIndirect(Ty, false);
8325}
8326
8327ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
Daniel Dunbara39bab32019-01-03 23:24:50 +00008328 // Compute the byval alignment.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008329 const unsigned MinABIStackAlignInBytes = 4;
8330 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8331 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8332 TypeAlign > MinABIStackAlignInBytes);
8333}
8334
8335Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8336 QualType Ty) const {
8337 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8338 getContext().getTypeInfoInChars(Ty),
8339 CharUnits::fromQuantity(4), true);
8340}
8341
8342ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
8343 uint8_t FreeRegs) const {
8344 // Handle the generic C++ ABI.
8345 const RecordType *RT = Ty->getAs<RecordType>();
8346 if (RT) {
8347 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8348 if (RAA == CGCXXABI::RAA_Indirect)
8349 return getIndirectByRef(Ty, FreeRegs > 0);
8350
8351 if (RAA == CGCXXABI::RAA_DirectInMemory)
8352 return getIndirectByValue(Ty);
8353 }
8354
8355 // Treat an enum type as its underlying type.
8356 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8357 Ty = EnumTy->getDecl()->getIntegerType();
8358
8359 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
8360
8361 if (isAggregateTypeForABI(Ty)) {
8362 // Structures with flexible arrays are always indirect.
8363 if (RT && RT->getDecl()->hasFlexibleArrayMember())
8364 return getIndirectByValue(Ty);
8365
8366 // Ignore empty structs/unions.
8367 if (isEmptyRecord(getContext(), Ty, true))
8368 return ABIArgInfo::getIgnore();
8369
8370 llvm::LLVMContext &LLVMContext = getVMContext();
8371
8372 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8373 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8374 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8375
8376 return FreeRegs >= SizeInRegs ?
8377 ABIArgInfo::getDirectInReg(Result) :
8378 ABIArgInfo::getDirect(Result, 0, nullptr, false);
8379 }
8380
8381 return Ty->isPromotableIntegerType() ?
8382 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) :
8383 ABIArgInfo::getExtend(Ty)) :
8384 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() :
8385 ABIArgInfo::getDirect());
8386}
8387
8388ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
8389 if (RetTy->isAnyComplexType())
8390 return ABIArgInfo::getDirectInReg();
8391
Daniel Dunbara39bab32019-01-03 23:24:50 +00008392 // Arguments of size > 4 registers are indirect.
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00008393 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
8394 if (RetSize > 4)
8395 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
8396
8397 return DefaultABIInfo::classifyReturnType(RetTy);
8398}
8399
8400} // End anonymous namespace.
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008401
Robert Lytton0e076492013-08-13 09:43:10 +00008402//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008403// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008404//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008405
Robert Lytton0e076492013-08-13 09:43:10 +00008406namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008407
8408/// A SmallStringEnc instance is used to build up the TypeString by passing
8409/// it by reference between functions that append to it.
8410typedef llvm::SmallString<128> SmallStringEnc;
8411
8412/// TypeStringCache caches the meta encodings of Types.
8413///
8414/// The reason for caching TypeStrings is two fold:
8415/// 1. To cache a type's encoding for later uses;
8416/// 2. As a means to break recursive member type inclusion.
8417///
8418/// A cache Entry can have a Status of:
8419/// NonRecursive: The type encoding is not recursive;
8420/// Recursive: The type encoding is recursive;
8421/// Incomplete: An incomplete TypeString;
8422/// IncompleteUsed: An incomplete TypeString that has been used in a
8423/// Recursive type encoding.
8424///
8425/// A NonRecursive entry will have all of its sub-members expanded as fully
8426/// as possible. Whilst it may contain types which are recursive, the type
8427/// itself is not recursive and thus its encoding may be safely used whenever
8428/// the type is encountered.
8429///
8430/// A Recursive entry will have all of its sub-members expanded as fully as
8431/// possible. The type itself is recursive and it may contain other types which
8432/// are recursive. The Recursive encoding must not be used during the expansion
8433/// of a recursive type's recursive branch. For simplicity the code uses
8434/// IncompleteCount to reject all usage of Recursive encodings for member types.
8435///
8436/// An Incomplete entry is always a RecordType and only encodes its
8437/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8438/// are placed into the cache during type expansion as a means to identify and
8439/// handle recursive inclusion of types as sub-members. If there is recursion
8440/// the entry becomes IncompleteUsed.
8441///
8442/// During the expansion of a RecordType's members:
8443///
8444/// If the cache contains a NonRecursive encoding for the member type, the
8445/// cached encoding is used;
8446///
8447/// If the cache contains a Recursive encoding for the member type, the
8448/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8449///
8450/// If the member is a RecordType, an Incomplete encoding is placed into the
8451/// cache to break potential recursive inclusion of itself as a sub-member;
8452///
8453/// Once a member RecordType has been expanded, its temporary incomplete
8454/// entry is removed from the cache. If a Recursive encoding was swapped out
8455/// it is swapped back in;
8456///
8457/// If an incomplete entry is used to expand a sub-member, the incomplete
8458/// entry is marked as IncompleteUsed. The cache keeps count of how many
8459/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8460///
8461/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8462/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8463/// Else the member is part of a recursive type and thus the recursion has
8464/// been exited too soon for the encoding to be correct for the member.
8465///
8466class TypeStringCache {
8467 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8468 struct Entry {
8469 std::string Str; // The encoded TypeString for the type.
8470 enum Status State; // Information about the encoding in 'Str'.
8471 std::string Swapped; // A temporary place holder for a Recursive encoding
8472 // during the expansion of RecordType's members.
8473 };
8474 std::map<const IdentifierInfo *, struct Entry> Map;
8475 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8476 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8477public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008478 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008479 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8480 bool removeIncomplete(const IdentifierInfo *ID);
8481 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8482 bool IsRecursive);
8483 StringRef lookupStr(const IdentifierInfo *ID);
8484};
8485
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008486/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008487/// FieldEncoding is a helper for this ordering process.
8488class FieldEncoding {
8489 bool HasName;
8490 std::string Enc;
8491public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008492 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008493 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008494 bool operator<(const FieldEncoding &rhs) const {
8495 if (HasName != rhs.HasName) return HasName;
8496 return Enc < rhs.Enc;
8497 }
8498};
8499
Robert Lytton7d1db152013-08-19 09:46:39 +00008500class XCoreABIInfo : public DefaultABIInfo {
8501public:
8502 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008503 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8504 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008505};
8506
Robert Lyttond21e2d72014-03-03 13:45:29 +00008507class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008508 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008509public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008510 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008511 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008512 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8513 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008514};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008515
Robert Lytton2d196952013-10-11 10:29:34 +00008516} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008517
James Y Knight29b5f082016-02-24 02:59:33 +00008518// TODO: this implementation is likely now redundant with the default
8519// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008520Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8521 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008522 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008523
Robert Lytton2d196952013-10-11 10:29:34 +00008524 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008525 CharUnits SlotSize = CharUnits::fromQuantity(4);
8526 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008527
Robert Lytton2d196952013-10-11 10:29:34 +00008528 // Handle the argument.
8529 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008530 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008531 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8532 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8533 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008534 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008535
8536 Address Val = Address::invalid();
8537 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008538 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008539 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008540 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008541 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008542 llvm_unreachable("Unsupported ABI kind for va_arg");
8543 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008544 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8545 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008546 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008547 case ABIArgInfo::Extend:
8548 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008549 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8550 ArgSize = CharUnits::fromQuantity(
8551 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008552 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008553 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008554 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008555 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8556 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8557 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008558 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008559 }
Robert Lytton2d196952013-10-11 10:29:34 +00008560
8561 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008562 if (!ArgSize.isZero()) {
8563 llvm::Value *APN =
8564 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8565 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008566 }
John McCall7f416cc2015-09-08 08:05:57 +00008567
Robert Lytton2d196952013-10-11 10:29:34 +00008568 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008569}
Robert Lytton0e076492013-08-13 09:43:10 +00008570
Robert Lytton844aeeb2014-05-02 09:33:20 +00008571/// During the expansion of a RecordType, an incomplete TypeString is placed
8572/// into the cache as a means to identify and break recursion.
8573/// If there is a Recursive encoding in the cache, it is swapped out and will
8574/// be reinserted by removeIncomplete().
8575/// All other types of encoding should have been used rather than arriving here.
8576void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8577 std::string StubEnc) {
8578 if (!ID)
8579 return;
8580 Entry &E = Map[ID];
8581 assert( (E.Str.empty() || E.State == Recursive) &&
8582 "Incorrectly use of addIncomplete");
8583 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8584 E.Swapped.swap(E.Str); // swap out the Recursive
8585 E.Str.swap(StubEnc);
8586 E.State = Incomplete;
8587 ++IncompleteCount;
8588}
8589
8590/// Once the RecordType has been expanded, the temporary incomplete TypeString
8591/// must be removed from the cache.
8592/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8593/// Returns true if the RecordType was defined recursively.
8594bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8595 if (!ID)
8596 return false;
8597 auto I = Map.find(ID);
8598 assert(I != Map.end() && "Entry not present");
8599 Entry &E = I->second;
8600 assert( (E.State == Incomplete ||
8601 E.State == IncompleteUsed) &&
8602 "Entry must be an incomplete type");
8603 bool IsRecursive = false;
8604 if (E.State == IncompleteUsed) {
8605 // We made use of our Incomplete encoding, thus we are recursive.
8606 IsRecursive = true;
8607 --IncompleteUsedCount;
8608 }
8609 if (E.Swapped.empty())
8610 Map.erase(I);
8611 else {
8612 // Swap the Recursive back.
8613 E.Swapped.swap(E.Str);
8614 E.Swapped.clear();
8615 E.State = Recursive;
8616 }
8617 --IncompleteCount;
8618 return IsRecursive;
8619}
8620
8621/// Add the encoded TypeString to the cache only if it is NonRecursive or
8622/// Recursive (viz: all sub-members were expanded as fully as possible).
8623void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8624 bool IsRecursive) {
8625 if (!ID || IncompleteUsedCount)
8626 return; // No key or it is is an incomplete sub-type so don't add.
8627 Entry &E = Map[ID];
8628 if (IsRecursive && !E.Str.empty()) {
8629 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8630 "This is not the same Recursive entry");
8631 // The parent container was not recursive after all, so we could have used
8632 // this Recursive sub-member entry after all, but we assumed the worse when
8633 // we started viz: IncompleteCount!=0.
8634 return;
8635 }
8636 assert(E.Str.empty() && "Entry already present");
8637 E.Str = Str.str();
8638 E.State = IsRecursive? Recursive : NonRecursive;
8639}
8640
8641/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8642/// are recursively expanding a type (IncompleteCount != 0) and the cached
8643/// encoding is Recursive, return an empty StringRef.
8644StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8645 if (!ID)
8646 return StringRef(); // We have no key.
8647 auto I = Map.find(ID);
8648 if (I == Map.end())
8649 return StringRef(); // We have no encoding.
8650 Entry &E = I->second;
8651 if (E.State == Recursive && IncompleteCount)
8652 return StringRef(); // We don't use Recursive encodings for member types.
8653
8654 if (E.State == Incomplete) {
8655 // The incomplete type is being used to break out of recursion.
8656 E.State = IncompleteUsed;
8657 ++IncompleteUsedCount;
8658 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008659 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008660}
8661
8662/// The XCore ABI includes a type information section that communicates symbol
8663/// type information to the linker. The linker uses this information to verify
8664/// safety/correctness of things such as array bound and pointers et al.
8665/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8666/// This type information (TypeString) is emitted into meta data for all global
8667/// symbols: definitions, declarations, functions & variables.
8668///
8669/// The TypeString carries type, qualifier, name, size & value details.
8670/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008671/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008672/// The output is tested by test/CodeGen/xcore-stringtype.c.
8673///
8674static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8675 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8676
8677/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8678void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8679 CodeGen::CodeGenModule &CGM) const {
8680 SmallStringEnc Enc;
8681 if (getTypeString(Enc, D, CGM, TSC)) {
8682 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008683 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8684 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008685 llvm::NamedMDNode *MD =
8686 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8687 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8688 }
8689}
8690
Xiuli Pan972bea82016-03-24 03:57:17 +00008691//===----------------------------------------------------------------------===//
8692// SPIR ABI Implementation
8693//===----------------------------------------------------------------------===//
8694
8695namespace {
8696class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8697public:
8698 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8699 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008700 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008701};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008702
Xiuli Pan972bea82016-03-24 03:57:17 +00008703} // End anonymous namespace.
8704
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008705namespace clang {
8706namespace CodeGen {
8707void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8708 DefaultABIInfo SPIRABI(CGM.getTypes());
8709 SPIRABI.computeInfo(FI);
8710}
8711}
8712}
8713
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008714unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8715 return llvm::CallingConv::SPIR_KERNEL;
8716}
8717
Robert Lytton844aeeb2014-05-02 09:33:20 +00008718static bool appendType(SmallStringEnc &Enc, QualType QType,
8719 const CodeGen::CodeGenModule &CGM,
8720 TypeStringCache &TSC);
8721
8722/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008723/// Builds a SmallVector containing the encoded field types in declaration
8724/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008725static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8726 const RecordDecl *RD,
8727 const CodeGen::CodeGenModule &CGM,
8728 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008729 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008730 SmallStringEnc Enc;
8731 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008732 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008733 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008734 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008735 Enc += "b(";
8736 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008737 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008738 Enc += ':';
8739 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008740 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008741 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008742 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008743 Enc += ')';
8744 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008745 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008746 }
8747 return true;
8748}
8749
8750/// Appends structure and union types to Enc and adds encoding to cache.
8751/// Recursively calls appendType (via extractFieldType) for each field.
8752/// Union types have their fields ordered according to the ABI.
8753static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8754 const CodeGen::CodeGenModule &CGM,
8755 TypeStringCache &TSC, const IdentifierInfo *ID) {
8756 // Append the cached TypeString if we have one.
8757 StringRef TypeString = TSC.lookupStr(ID);
8758 if (!TypeString.empty()) {
8759 Enc += TypeString;
8760 return true;
8761 }
8762
8763 // Start to emit an incomplete TypeString.
8764 size_t Start = Enc.size();
8765 Enc += (RT->isUnionType()? 'u' : 's');
8766 Enc += '(';
8767 if (ID)
8768 Enc += ID->getName();
8769 Enc += "){";
8770
8771 // We collect all encoded fields and order as necessary.
8772 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008773 const RecordDecl *RD = RT->getDecl()->getDefinition();
8774 if (RD && !RD->field_empty()) {
8775 // An incomplete TypeString stub is placed in the cache for this RecordType
8776 // so that recursive calls to this RecordType will use it whilst building a
8777 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008778 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008779 std::string StubEnc(Enc.substr(Start).str());
8780 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8781 TSC.addIncomplete(ID, std::move(StubEnc));
8782 if (!extractFieldType(FE, RD, CGM, TSC)) {
8783 (void) TSC.removeIncomplete(ID);
8784 return false;
8785 }
8786 IsRecursive = TSC.removeIncomplete(ID);
8787 // The ABI requires unions to be sorted but not structures.
8788 // See FieldEncoding::operator< for sort algorithm.
8789 if (RT->isUnionType())
Fangrui Song55fab262018-09-26 22:16:28 +00008790 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008791 // We can now complete the TypeString.
8792 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008793 for (unsigned I = 0; I != E; ++I) {
8794 if (I)
8795 Enc += ',';
8796 Enc += FE[I].str();
8797 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008798 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008799 Enc += '}';
8800 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8801 return true;
8802}
8803
8804/// Appends enum types to Enc and adds the encoding to the cache.
8805static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8806 TypeStringCache &TSC,
8807 const IdentifierInfo *ID) {
8808 // Append the cached TypeString if we have one.
8809 StringRef TypeString = TSC.lookupStr(ID);
8810 if (!TypeString.empty()) {
8811 Enc += TypeString;
8812 return true;
8813 }
8814
8815 size_t Start = Enc.size();
8816 Enc += "e(";
8817 if (ID)
8818 Enc += ID->getName();
8819 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008820
8821 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008822 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008823 SmallVector<FieldEncoding, 16> FE;
8824 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8825 ++I) {
8826 SmallStringEnc EnumEnc;
8827 EnumEnc += "m(";
8828 EnumEnc += I->getName();
8829 EnumEnc += "){";
8830 I->getInitVal().toString(EnumEnc);
8831 EnumEnc += '}';
8832 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8833 }
Fangrui Song55fab262018-09-26 22:16:28 +00008834 llvm::sort(FE);
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008835 unsigned E = FE.size();
8836 for (unsigned I = 0; I != E; ++I) {
8837 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008838 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008839 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008840 }
8841 }
8842 Enc += '}';
8843 TSC.addIfComplete(ID, Enc.substr(Start), false);
8844 return true;
8845}
8846
8847/// Appends type's qualifier to Enc.
8848/// This is done prior to appending the type's encoding.
8849static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8850 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008851 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008852 int Lookup = 0;
8853 if (QT.isConstQualified())
8854 Lookup += 1<<0;
8855 if (QT.isRestrictQualified())
8856 Lookup += 1<<1;
8857 if (QT.isVolatileQualified())
8858 Lookup += 1<<2;
8859 Enc += Table[Lookup];
8860}
8861
8862/// Appends built-in types to Enc.
8863static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8864 const char *EncType;
8865 switch (BT->getKind()) {
8866 case BuiltinType::Void:
8867 EncType = "0";
8868 break;
8869 case BuiltinType::Bool:
8870 EncType = "b";
8871 break;
8872 case BuiltinType::Char_U:
8873 EncType = "uc";
8874 break;
8875 case BuiltinType::UChar:
8876 EncType = "uc";
8877 break;
8878 case BuiltinType::SChar:
8879 EncType = "sc";
8880 break;
8881 case BuiltinType::UShort:
8882 EncType = "us";
8883 break;
8884 case BuiltinType::Short:
8885 EncType = "ss";
8886 break;
8887 case BuiltinType::UInt:
8888 EncType = "ui";
8889 break;
8890 case BuiltinType::Int:
8891 EncType = "si";
8892 break;
8893 case BuiltinType::ULong:
8894 EncType = "ul";
8895 break;
8896 case BuiltinType::Long:
8897 EncType = "sl";
8898 break;
8899 case BuiltinType::ULongLong:
8900 EncType = "ull";
8901 break;
8902 case BuiltinType::LongLong:
8903 EncType = "sll";
8904 break;
8905 case BuiltinType::Float:
8906 EncType = "ft";
8907 break;
8908 case BuiltinType::Double:
8909 EncType = "d";
8910 break;
8911 case BuiltinType::LongDouble:
8912 EncType = "ld";
8913 break;
8914 default:
8915 return false;
8916 }
8917 Enc += EncType;
8918 return true;
8919}
8920
8921/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8922static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8923 const CodeGen::CodeGenModule &CGM,
8924 TypeStringCache &TSC) {
8925 Enc += "p(";
8926 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8927 return false;
8928 Enc += ')';
8929 return true;
8930}
8931
8932/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008933static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8934 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008935 const CodeGen::CodeGenModule &CGM,
8936 TypeStringCache &TSC, StringRef NoSizeEnc) {
8937 if (AT->getSizeModifier() != ArrayType::Normal)
8938 return false;
8939 Enc += "a(";
8940 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8941 CAT->getSize().toStringUnsigned(Enc);
8942 else
8943 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8944 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008945 // The Qualifiers should be attached to the type rather than the array.
8946 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008947 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8948 return false;
8949 Enc += ')';
8950 return true;
8951}
8952
8953/// Appends a function encoding to Enc, calling appendType for the return type
8954/// and the arguments.
8955static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8956 const CodeGen::CodeGenModule &CGM,
8957 TypeStringCache &TSC) {
8958 Enc += "f{";
8959 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8960 return false;
8961 Enc += "}(";
8962 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8963 // N.B. we are only interested in the adjusted param types.
8964 auto I = FPT->param_type_begin();
8965 auto E = FPT->param_type_end();
8966 if (I != E) {
8967 do {
8968 if (!appendType(Enc, *I, CGM, TSC))
8969 return false;
8970 ++I;
8971 if (I != E)
8972 Enc += ',';
8973 } while (I != E);
8974 if (FPT->isVariadic())
8975 Enc += ",va";
8976 } else {
8977 if (FPT->isVariadic())
8978 Enc += "va";
8979 else
8980 Enc += '0';
8981 }
8982 }
8983 Enc += ')';
8984 return true;
8985}
8986
8987/// Handles the type's qualifier before dispatching a call to handle specific
8988/// type encodings.
8989static bool appendType(SmallStringEnc &Enc, QualType QType,
8990 const CodeGen::CodeGenModule &CGM,
8991 TypeStringCache &TSC) {
8992
8993 QualType QT = QType.getCanonicalType();
8994
Robert Lytton6adb20f2014-06-05 09:06:21 +00008995 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8996 // The Qualifiers should be attached to the type rather than the array.
8997 // Thus we don't call appendQualifier() here.
8998 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8999
Robert Lytton844aeeb2014-05-02 09:33:20 +00009000 appendQualifier(Enc, QT);
9001
9002 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
9003 return appendBuiltinType(Enc, BT);
9004
Robert Lytton844aeeb2014-05-02 09:33:20 +00009005 if (const PointerType *PT = QT->getAs<PointerType>())
9006 return appendPointerType(Enc, PT, CGM, TSC);
9007
9008 if (const EnumType *ET = QT->getAs<EnumType>())
9009 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9010
9011 if (const RecordType *RT = QT->getAsStructureType())
9012 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9013
9014 if (const RecordType *RT = QT->getAsUnionType())
9015 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9016
9017 if (const FunctionType *FT = QT->getAs<FunctionType>())
9018 return appendFunctionType(Enc, FT, CGM, TSC);
9019
9020 return false;
9021}
9022
9023static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9024 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9025 if (!D)
9026 return false;
9027
9028 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9029 if (FD->getLanguageLinkage() != CLanguageLinkage)
9030 return false;
9031 return appendType(Enc, FD->getType(), CGM, TSC);
9032 }
9033
9034 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9035 if (VD->getLanguageLinkage() != CLanguageLinkage)
9036 return false;
9037 QualType QT = VD->getType().getCanonicalType();
9038 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9039 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00009040 // The Qualifiers should be attached to the type rather than the array.
9041 // Thus we don't call appendQualifier() here.
9042 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00009043 }
9044 return appendType(Enc, QT, CGM, TSC);
9045 }
9046 return false;
9047}
9048
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009049//===----------------------------------------------------------------------===//
9050// RISCV ABI Implementation
9051//===----------------------------------------------------------------------===//
9052
9053namespace {
9054class RISCVABIInfo : public DefaultABIInfo {
9055private:
9056 unsigned XLen; // Size of the integer ('x') registers in bits.
9057 static const int NumArgGPRs = 8;
9058
9059public:
9060 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
9061 : DefaultABIInfo(CGT), XLen(XLen) {}
9062
9063 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9064 // non-virtual, but computeInfo is virtual, so we overload it.
9065 void computeInfo(CGFunctionInfo &FI) const override;
9066
9067 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed,
9068 int &ArgGPRsLeft) const;
9069 ABIArgInfo classifyReturnType(QualType RetTy) const;
9070
9071 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9072 QualType Ty) const override;
9073
9074 ABIArgInfo extendType(QualType Ty) const;
9075};
9076} // end anonymous namespace
9077
9078void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9079 QualType RetTy = FI.getReturnType();
9080 if (!getCXXABI().classifyReturnType(FI))
9081 FI.getReturnInfo() = classifyReturnType(RetTy);
9082
9083 // IsRetIndirect is true if classifyArgumentType indicated the value should
9084 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
9085 // is passed direct in LLVM IR, relying on the backend lowering code to
9086 // rewrite the argument list and pass indirectly on RV32.
9087 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
9088 getContext().getTypeSize(RetTy) > (2 * XLen);
9089
9090 // We must track the number of GPRs used in order to conform to the RISC-V
9091 // ABI, as integer scalars passed in registers should have signext/zeroext
9092 // when promoted, but are anyext if passed on the stack. As GPR usage is
9093 // different for variadic arguments, we must also track whether we are
9094 // examining a vararg or not.
9095 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
9096 int NumFixedArgs = FI.getNumRequiredArgs();
9097
9098 int ArgNum = 0;
9099 for (auto &ArgInfo : FI.arguments()) {
9100 bool IsFixed = ArgNum < NumFixedArgs;
9101 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft);
9102 ArgNum++;
9103 }
9104}
9105
9106ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
9107 int &ArgGPRsLeft) const {
9108 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
9109 Ty = useFirstFieldIfTransparentUnion(Ty);
9110
9111 // Structures with either a non-trivial destructor or a non-trivial
9112 // copy constructor are always passed indirectly.
9113 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
9114 if (ArgGPRsLeft)
9115 ArgGPRsLeft -= 1;
9116 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
9117 CGCXXABI::RAA_DirectInMemory);
9118 }
9119
9120 // Ignore empty structs/unions.
9121 if (isEmptyRecord(getContext(), Ty, true))
9122 return ABIArgInfo::getIgnore();
9123
9124 uint64_t Size = getContext().getTypeSize(Ty);
9125 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
9126 bool MustUseStack = false;
9127 // Determine the number of GPRs needed to pass the current argument
9128 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
9129 // register pairs, so may consume 3 registers.
9130 int NeededArgGPRs = 1;
9131 if (!IsFixed && NeededAlign == 2 * XLen)
9132 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
9133 else if (Size > XLen && Size <= 2 * XLen)
9134 NeededArgGPRs = 2;
9135
9136 if (NeededArgGPRs > ArgGPRsLeft) {
9137 MustUseStack = true;
9138 NeededArgGPRs = ArgGPRsLeft;
9139 }
9140
9141 ArgGPRsLeft -= NeededArgGPRs;
9142
9143 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
9144 // Treat an enum type as its underlying type.
9145 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9146 Ty = EnumTy->getDecl()->getIntegerType();
9147
9148 // All integral types are promoted to XLen width, unless passed on the
9149 // stack.
9150 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9151 return extendType(Ty);
9152 }
9153
9154 return ABIArgInfo::getDirect();
9155 }
9156
9157 // Aggregates which are <= 2*XLen will be passed in registers if possible,
9158 // so coerce to integers.
9159 if (Size <= 2 * XLen) {
9160 unsigned Alignment = getContext().getTypeAlign(Ty);
9161
9162 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9163 // required, and a 2-element XLen array if only XLen alignment is required.
9164 if (Size <= XLen) {
9165 return ABIArgInfo::getDirect(
9166 llvm::IntegerType::get(getVMContext(), XLen));
9167 } else if (Alignment == 2 * XLen) {
9168 return ABIArgInfo::getDirect(
9169 llvm::IntegerType::get(getVMContext(), 2 * XLen));
9170 } else {
9171 return ABIArgInfo::getDirect(llvm::ArrayType::get(
9172 llvm::IntegerType::get(getVMContext(), XLen), 2));
9173 }
9174 }
9175 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9176}
9177
9178ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9179 if (RetTy->isVoidType())
9180 return ABIArgInfo::getIgnore();
9181
9182 int ArgGPRsLeft = 2;
9183
9184 // The rules for return and argument types are the same, so defer to
9185 // classifyArgumentType.
9186 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft);
9187}
9188
9189Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9190 QualType Ty) const {
9191 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9192
9193 // Empty records are ignored for parameter passing purposes.
9194 if (isEmptyRecord(getContext(), Ty, true)) {
9195 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9196 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9197 return Addr;
9198 }
9199
9200 std::pair<CharUnits, CharUnits> SizeAndAlign =
9201 getContext().getTypeInfoInChars(Ty);
9202
9203 // Arguments bigger than 2*Xlen bytes are passed indirectly.
9204 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9205
9206 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9207 SlotSize, /*AllowHigherAlign=*/true);
9208}
9209
9210ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9211 int TySize = getContext().getTypeSize(Ty);
9212 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9213 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9214 return ABIArgInfo::getSignExtend(Ty);
9215 return ABIArgInfo::getExtend(Ty);
9216}
9217
9218namespace {
9219class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9220public:
9221 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
9222 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {}
Ana Pazos1eee1b72018-07-26 17:37:45 +00009223
9224 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9225 CodeGen::CodeGenModule &CGM) const override {
9226 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9227 if (!FD) return;
9228
9229 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9230 if (!Attr)
9231 return;
9232
9233 const char *Kind;
9234 switch (Attr->getInterrupt()) {
9235 case RISCVInterruptAttr::user: Kind = "user"; break;
9236 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9237 case RISCVInterruptAttr::machine: Kind = "machine"; break;
9238 }
9239
9240 auto *Fn = cast<llvm::Function>(GV);
9241
9242 Fn->addFnAttr("interrupt", Kind);
9243 }
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009244};
9245} // namespace
Robert Lytton844aeeb2014-05-02 09:33:20 +00009246
Robert Lytton0e076492013-08-13 09:43:10 +00009247//===----------------------------------------------------------------------===//
9248// Driver code
9249//===----------------------------------------------------------------------===//
9250
Rafael Espindola9f834732014-09-19 01:54:22 +00009251bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00009252 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00009253}
9254
Chris Lattner2b037972010-07-29 02:01:43 +00009255const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009256 if (TheTargetCodeGenInfo)
9257 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009258
Reid Kleckner9305fd12016-04-13 23:37:17 +00009259 // Helper to set the unique_ptr while still keeping the return value.
9260 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9261 this->TheTargetCodeGenInfo.reset(P);
9262 return *P;
9263 };
9264
John McCallc8e01702013-04-16 22:48:15 +00009265 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00009266 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00009267 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009268 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00009269
Derek Schuff09338a22012-09-06 17:37:28 +00009270 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009271 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00009272 case llvm::Triple::mips:
9273 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00009274 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00009275 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9276 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009277
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00009278 case llvm::Triple::mips64:
9279 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009280 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00009281
Dylan McKaye8232d72017-02-08 05:09:26 +00009282 case llvm::Triple::avr:
9283 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9284
Tim Northover25e8a672014-05-24 12:51:25 +00009285 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00009286 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00009287 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00009288 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00009289 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00009290 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00009291 return SetCGInfo(
9292 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00009293
Reid Kleckner9305fd12016-04-13 23:37:17 +00009294 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00009295 }
9296
Dan Gohmanc2853072015-09-03 22:51:53 +00009297 case llvm::Triple::wasm32:
9298 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009299 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00009300
Daniel Dunbard59655c2009-09-12 00:59:49 +00009301 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00009302 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00009303 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009304 case llvm::Triple::thumbeb: {
9305 if (Triple.getOS() == llvm::Triple::Win32) {
9306 return SetCGInfo(
9307 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00009308 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00009309
Reid Kleckner9305fd12016-04-13 23:37:17 +00009310 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9311 StringRef ABIStr = getTarget().getABI();
9312 if (ABIStr == "apcs-gnu")
9313 Kind = ARMABIInfo::APCS;
9314 else if (ABIStr == "aapcs16")
9315 Kind = ARMABIInfo::AAPCS16_VFP;
9316 else if (CodeGenOpts.FloatABI == "hard" ||
9317 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009318 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00009319 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00009320 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00009321 Kind = ARMABIInfo::AAPCS_VFP;
9322
9323 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9324 }
9325
John McCallea8d8bb2010-03-11 00:10:12 +00009326 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009327 return SetCGInfo(
9328 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00009329 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00009330 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00009331 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00009332 if (getTarget().getABI() == "elfv2")
9333 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009334 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009335 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009336
Hal Finkel415c2a32016-10-02 02:10:45 +00009337 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9338 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009339 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00009340 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009341 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00009342 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00009343 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009344 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00009345 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00009346 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00009347 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00009348
Hal Finkel415c2a32016-10-02 02:10:45 +00009349 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9350 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00009351 }
John McCallea8d8bb2010-03-11 00:10:12 +00009352
Peter Collingbournec947aae2012-05-20 23:28:41 +00009353 case llvm::Triple::nvptx:
9354 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009355 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00009356
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00009357 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009358 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00009359
Alex Bradbury8cbdd482018-01-15 17:54:52 +00009360 case llvm::Triple::riscv32:
9361 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32));
9362 case llvm::Triple::riscv64:
9363 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64));
9364
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009365 case llvm::Triple::systemz: {
9366 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00009367 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00009368 }
Ulrich Weigand47445072013-05-06 16:26:41 +00009369
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009370 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00009371 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009372 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00009373
Eli Friedman33465822011-07-08 23:31:17 +00009374 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00009375 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00009376 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00009377 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00009378 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00009379
John McCall1fe2a8c2013-06-18 02:46:29 +00009380 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009381 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9382 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9383 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00009384 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00009385 return SetCGInfo(new X86_32TargetCodeGenInfo(
9386 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9387 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9388 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009389 }
Eli Friedman33465822011-07-08 23:31:17 +00009390 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009391
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009392 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009393 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00009394 X86AVXABILevel AVXLevel =
9395 (ABI == "avx512"
9396 ? X86AVXABILevel::AVX512
9397 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00009398
Chris Lattner04dc9572010-08-31 16:44:54 +00009399 switch (Triple.getOS()) {
9400 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009401 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00009402 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009403 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009404 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009405 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00009406 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00009407 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00009408 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009409 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00009410 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009411 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00009412 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009413 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00009414 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009415 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00009416 case llvm::Triple::sparc:
9417 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00009418 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009419 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00009420 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009421 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Tatyana Krasnukhaf8c264e2018-11-27 19:52:10 +00009422 case llvm::Triple::arc:
9423 return SetCGInfo(new ARCTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00009424 case llvm::Triple::spir:
9425 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00009426 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00009427 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00009428}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009429
9430/// Create an OpenCL kernel for an enqueued block.
9431///
9432/// The kernel has the same function type as the block invoke function. Its
9433/// name is the name of the block invoke function postfixed with "_kernel".
9434/// It simply calls the block invoke function then returns.
9435llvm::Function *
9436TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9437 llvm::Function *Invoke,
9438 llvm::Value *BlockLiteral) const {
9439 auto *InvokeFT = Invoke->getFunctionType();
9440 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9441 for (auto &P : InvokeFT->params())
9442 ArgTys.push_back(P);
9443 auto &C = CGF.getLLVMContext();
9444 std::string Name = Invoke->getName().str() + "_kernel";
9445 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9446 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9447 &CGF.CGM.getModule());
9448 auto IP = CGF.Builder.saveIP();
9449 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9450 auto &Builder = CGF.Builder;
9451 Builder.SetInsertPoint(BB);
9452 llvm::SmallVector<llvm::Value *, 2> Args;
9453 for (auto &A : F->args())
9454 Args.push_back(&A);
9455 Builder.CreateCall(Invoke, Args);
9456 Builder.CreateRetVoid();
9457 Builder.restoreIP(IP);
9458 return F;
9459}
9460
9461/// Create an OpenCL kernel for an enqueued block.
9462///
9463/// The type of the first argument (the block literal) is the struct type
9464/// of the block literal instead of a pointer type. The first argument
9465/// (block literal) is passed directly by value to the kernel. The kernel
9466/// allocates the same type of struct on stack and stores the block literal
9467/// to it and passes its pointer to the block invoke function. The kernel
9468/// has "enqueued-block" function attribute and kernel argument metadata.
9469llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9470 CodeGenFunction &CGF, llvm::Function *Invoke,
9471 llvm::Value *BlockLiteral) const {
9472 auto &Builder = CGF.Builder;
9473 auto &C = CGF.getLLVMContext();
9474
9475 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9476 auto *InvokeFT = Invoke->getFunctionType();
9477 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9478 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9479 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9480 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9481 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9482 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9483 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9484
9485 ArgTys.push_back(BlockTy);
9486 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9487 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9488 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9489 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9490 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9491 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9492 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9493 ArgTys.push_back(InvokeFT->getParamType(I));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009494 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9495 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9496 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9497 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9498 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9499 ArgNames.push_back(
Yaxun Liu98f0c432017-10-14 12:51:52 +00009500 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
Yaxun Liuc2a87a02017-10-14 12:23:50 +00009501 }
9502 std::string Name = Invoke->getName().str() + "_kernel";
9503 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9504 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9505 &CGF.CGM.getModule());
9506 F->addFnAttr("enqueued-block");
9507 auto IP = CGF.Builder.saveIP();
9508 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9509 Builder.SetInsertPoint(BB);
9510 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9511 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9512 BlockPtr->setAlignment(BlockAlign);
9513 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9514 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9515 llvm::SmallVector<llvm::Value *, 2> Args;
9516 Args.push_back(Cast);
9517 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9518 Args.push_back(I);
9519 Builder.CreateCall(Invoke, Args);
9520 Builder.CreateRetVoid();
9521 Builder.restoreIP(IP);
9522
9523 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9524 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9525 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9526 F->setMetadata("kernel_arg_base_type",
9527 llvm::MDNode::get(C, ArgBaseTypeNames));
9528 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9529 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9530 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9531
9532 return F;
9533}