blob: bca278019e1e7fe1afed0a5b0d1d299112754147 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Yaxun Liuc2a87a02017-10-14 12:23:50 +000017#include "CGBlocks.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000018#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000019#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000020#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000024#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000025#include "llvm/ADT/StringExtras.h"
Coby Tayree7b49dc92017-08-24 09:07:34 +000026#include "llvm/ADT/StringSwitch.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000027#include "llvm/ADT/Triple.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());
142 if (!RD)
143 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000144 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000145}
146
147static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000148 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000149 const RecordType *RT = T->getAs<RecordType>();
150 if (!RT)
151 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000152 return getRecordArgABI(RT, CXXABI);
153}
154
Reid Klecknerb1be6832014-11-15 01:41:41 +0000155/// Pass transparent unions as if they were the type of the first element. Sema
156/// should ensure that all elements of the union have the same "machine type".
157static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
158 if (const RecordType *UT = Ty->getAsUnionType()) {
159 const RecordDecl *UD = UT->getDecl();
160 if (UD->hasAttr<TransparentUnionAttr>()) {
161 assert(!UD->field_empty() && "sema created an empty transparent union");
162 return UD->field_begin()->getType();
163 }
164 }
165 return Ty;
166}
167
Mark Lacey3825e832013-10-06 01:33:34 +0000168CGCXXABI &ABIInfo::getCXXABI() const {
169 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000170}
171
Chris Lattner2b037972010-07-29 02:01:43 +0000172ASTContext &ABIInfo::getContext() const {
173 return CGT.getContext();
174}
175
176llvm::LLVMContext &ABIInfo::getVMContext() const {
177 return CGT.getLLVMContext();
178}
179
Micah Villmowdd31ca12012-10-08 16:25:52 +0000180const llvm::DataLayout &ABIInfo::getDataLayout() const {
181 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000182}
183
John McCallc8e01702013-04-16 22:48:15 +0000184const TargetInfo &ABIInfo::getTarget() const {
185 return CGT.getTarget();
186}
Chris Lattner2b037972010-07-29 02:01:43 +0000187
Richard Smithf667ad52017-08-26 01:04:35 +0000188const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
189 return CGT.getCodeGenOpts();
190}
191
192bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000193
Reid Klecknere9f6a712014-10-31 17:10:41 +0000194bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
195 return false;
196}
197
198bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
199 uint64_t Members) const {
200 return false;
201}
202
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000203bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
204 return false;
205}
206
Yaron Kerencdae9412016-01-29 19:38:18 +0000207LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000208 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000209 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000210 switch (TheKind) {
211 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000212 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000213 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000214 Ty->print(OS);
215 else
216 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000217 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000218 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000219 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000220 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000221 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000222 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000223 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000224 case InAlloca:
225 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
226 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000227 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000228 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000229 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000230 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000231 break;
232 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000233 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000234 break;
John McCallf26e73d2016-03-11 04:30:43 +0000235 case CoerceAndExpand:
236 OS << "CoerceAndExpand Type=";
237 getCoerceAndExpandType()->print(OS);
238 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000239 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000240 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000241}
242
Petar Jovanovic402257b2015-12-04 00:26:47 +0000243// Dynamically round a pointer up to a multiple of the given alignment.
244static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
245 llvm::Value *Ptr,
246 CharUnits Align) {
247 llvm::Value *PtrAsInt = Ptr;
248 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
249 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
250 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
251 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
252 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
253 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
254 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
255 Ptr->getType(),
256 Ptr->getName() + ".aligned");
257 return PtrAsInt;
258}
259
John McCall7f416cc2015-09-08 08:05:57 +0000260/// Emit va_arg for a platform using the common void* representation,
261/// where arguments are simply emitted in an array of slots on the stack.
262///
263/// This version implements the core direct-value passing rules.
264///
265/// \param SlotSize - The size and alignment of a stack slot.
266/// Each argument will be allocated to a multiple of this number of
267/// slots, and all the slots will be aligned to this value.
268/// \param AllowHigherAlign - The slot alignment is not a cap;
269/// an argument type with an alignment greater than the slot size
270/// will be emitted on a higher-alignment address, potentially
271/// leaving one or more empty slots behind as padding. If this
272/// is false, the returned address might be less-aligned than
273/// DirectAlign.
274static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
275 Address VAListAddr,
276 llvm::Type *DirectTy,
277 CharUnits DirectSize,
278 CharUnits DirectAlign,
279 CharUnits SlotSize,
280 bool AllowHigherAlign) {
281 // Cast the element type to i8* if necessary. Some platforms define
282 // va_list as a struct containing an i8* instead of just an i8*.
283 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
284 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
285
286 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
287
288 // If the CC aligns values higher than the slot size, do so if needed.
289 Address Addr = Address::invalid();
290 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000291 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
292 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000293 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000294 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000295 }
296
297 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000298 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000299 llvm::Value *NextPtr =
300 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
301 "argp.next");
302 CGF.Builder.CreateStore(NextPtr, VAListAddr);
303
304 // If the argument is smaller than a slot, and this is a big-endian
305 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000306 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
307 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000308 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
309 }
310
311 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
312 return Addr;
313}
314
315/// Emit va_arg for a platform using the common void* representation,
316/// where arguments are simply emitted in an array of slots on the stack.
317///
318/// \param IsIndirect - Values of this type are passed indirectly.
319/// \param ValueInfo - The size and alignment of this type, generally
320/// computed with getContext().getTypeInfoInChars(ValueTy).
321/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
322/// Each argument will be allocated to a multiple of this number of
323/// slots, and all the slots will be aligned to this value.
324/// \param AllowHigherAlign - The slot alignment is not a cap;
325/// an argument type with an alignment greater than the slot size
326/// will be emitted on a higher-alignment address, potentially
327/// leaving one or more empty slots behind as padding.
328static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
329 QualType ValueTy, bool IsIndirect,
330 std::pair<CharUnits, CharUnits> ValueInfo,
331 CharUnits SlotSizeAndAlign,
332 bool AllowHigherAlign) {
333 // The size and alignment of the value that was passed directly.
334 CharUnits DirectSize, DirectAlign;
335 if (IsIndirect) {
336 DirectSize = CGF.getPointerSize();
337 DirectAlign = CGF.getPointerAlign();
338 } else {
339 DirectSize = ValueInfo.first;
340 DirectAlign = ValueInfo.second;
341 }
342
343 // Cast the address we've calculated to the right type.
344 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
345 if (IsIndirect)
346 DirectTy = DirectTy->getPointerTo(0);
347
348 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
349 DirectSize, DirectAlign,
350 SlotSizeAndAlign,
351 AllowHigherAlign);
352
353 if (IsIndirect) {
354 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
355 }
356
357 return Addr;
358
359}
360
361static Address emitMergePHI(CodeGenFunction &CGF,
362 Address Addr1, llvm::BasicBlock *Block1,
363 Address Addr2, llvm::BasicBlock *Block2,
364 const llvm::Twine &Name = "") {
365 assert(Addr1.getType() == Addr2.getType());
366 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
367 PHI->addIncoming(Addr1.getPointer(), Block1);
368 PHI->addIncoming(Addr2.getPointer(), Block2);
369 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
370 return Address(PHI, Align);
371}
372
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000373TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
374
John McCall3480ef22011-08-30 01:42:09 +0000375// If someone can figure out a general rule for this, that would be great.
376// It's probably just doomed to be platform-dependent, though.
377unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
378 // Verified for:
379 // x86-64 FreeBSD, Linux, Darwin
380 // x86-32 FreeBSD, Linux, Darwin
381 // PowerPC Linux, Darwin
382 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000383 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000384 return 32;
385}
386
John McCalla729c622012-02-17 03:33:10 +0000387bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
388 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000389 // The following conventions are known to require this to be false:
390 // x86_stdcall
391 // MIPS
392 // For everything else, we just prefer false unless we opt out.
393 return false;
394}
395
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000396void
397TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
398 llvm::SmallString<24> &Opt) const {
399 // This assumes the user is passing a library name like "rt" instead of a
400 // filename like "librt.a/so", and that they don't care whether it's static or
401 // dynamic.
402 Opt = "-l";
403 Opt += Lib;
404}
405
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000406unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000407 // OpenCL kernels are called via an explicit runtime API with arguments
408 // set with clSetKernelArg(), not as normal sub-functions.
409 // Return SPIR_KERNEL by default as the kernel calling convention to
410 // ensure the fingerprint is fixed such way that each OpenCL argument
411 // gets one matching argument in the produced kernel function argument
412 // list to enable feasible implementation of clSetKernelArg() with
413 // aggregates etc. In case we would use the default C calling conv here,
414 // clSetKernelArg() might break depending on the target-specific
415 // conventions; different targets might split structs passed as values
416 // to multiple function arguments etc.
417 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000418}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000419
Yaxun Liu402804b2016-12-15 08:09:08 +0000420llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
421 llvm::PointerType *T, QualType QT) const {
422 return llvm::ConstantPointerNull::get(T);
423}
424
Yaxun Liucbf647c2017-07-08 13:24:52 +0000425unsigned TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
426 const VarDecl *D) const {
427 assert(!CGM.getLangOpts().OpenCL &&
428 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
429 "Address space agnostic languages only");
Yaxun Liu7bce6422017-07-08 19:13:41 +0000430 return D ? D->getType().getAddressSpace()
431 : static_cast<unsigned>(LangAS::Default);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000432}
433
Yaxun Liu402804b2016-12-15 08:09:08 +0000434llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000435 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
436 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000437 // Since target may map different address spaces in AST to the same address
438 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000439 if (auto *C = dyn_cast<llvm::Constant>(Src))
440 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000441 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000442}
443
Yaxun Liucbf647c2017-07-08 13:24:52 +0000444llvm::Constant *
445TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
446 unsigned SrcAddr, unsigned DestAddr,
447 llvm::Type *DestTy) const {
448 // Since target may map different address spaces in AST to the same address
449 // space, an address space conversion may end up as a bitcast.
450 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
451}
452
Yaxun Liu39195062017-08-04 18:16:31 +0000453llvm::SyncScope::ID
454TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
455 return C.getOrInsertSyncScopeID(""); /* default sync scope */
456}
457
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000458static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000459
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000460/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000461/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000462static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
463 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000464 if (FD->isUnnamedBitfield())
465 return true;
466
467 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000468
Eli Friedman0b3f2012011-11-18 03:47:20 +0000469 // Constant arrays of empty records count as empty, strip them off.
470 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000471 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000472 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
473 if (AT->getSize() == 0)
474 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000475 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000476 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000477
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000478 const RecordType *RT = FT->getAs<RecordType>();
479 if (!RT)
480 return false;
481
482 // C++ record fields are never empty, at least in the Itanium ABI.
483 //
484 // FIXME: We should use a predicate for whether this behavior is true in the
485 // current ABI.
486 if (isa<CXXRecordDecl>(RT->getDecl()))
487 return false;
488
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000489 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000490}
491
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000492/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000493/// fields. Note that a structure with a flexible array member is not
494/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000495static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000496 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000497 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000498 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000499 const RecordDecl *RD = RT->getDecl();
500 if (RD->hasFlexibleArrayMember())
501 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000502
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000503 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000504 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000505 for (const auto &I : CXXRD->bases())
506 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000507 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000508
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000509 for (const auto *I : RD->fields())
510 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000511 return false;
512 return true;
513}
514
515/// isSingleElementStruct - Determine if a structure is a "single
516/// element struct", i.e. it has exactly one non-empty field or
517/// exactly one field which is itself a single element
518/// struct. Structures with flexible array members are never
519/// considered single element structs.
520///
521/// \return The field declaration for the single non-empty field, if
522/// it exists.
523static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000524 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000526 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000527
528 const RecordDecl *RD = RT->getDecl();
529 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000530 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000531
Craig Topper8a13c412014-05-21 05:09:00 +0000532 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000533
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000534 // If this is a C++ record, check the bases first.
535 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000536 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000537 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000538 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000539 continue;
540
541 // If we already found an element then this isn't a single-element struct.
542 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000543 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000544
545 // If this is non-empty and not a single element struct, the composite
546 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000547 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000548 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000549 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000550 }
551 }
552
553 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000554 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000555 QualType FT = FD->getType();
556
557 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000558 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000559 continue;
560
561 // If we already found an element then this isn't a single-element
562 // struct.
563 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000564 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000565
566 // Treat single element arrays as the element.
567 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
568 if (AT->getSize().getZExtValue() != 1)
569 break;
570 FT = AT->getElementType();
571 }
572
John McCalla1dee5302010-08-22 10:59:02 +0000573 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000574 Found = FT.getTypePtr();
575 } else {
576 Found = isSingleElementStruct(FT, Context);
577 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000578 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000579 }
580 }
581
Eli Friedmanee945342011-11-18 01:25:50 +0000582 // We don't consider a struct a single-element struct if it has
583 // padding beyond the element type.
584 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000585 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000586
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000587 return Found;
588}
589
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000590namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000591Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
592 const ABIArgInfo &AI) {
593 // This default implementation defers to the llvm backend's va_arg
594 // instruction. It can handle only passing arguments directly
595 // (typically only handled in the backend for primitive types), or
596 // aggregates passed indirectly by pointer (NOTE: if the "byval"
597 // flag has ABI impact in the callee, this implementation cannot
598 // work.)
599
600 // Only a few cases are covered here at the moment -- those needed
601 // by the default abi.
602 llvm::Value *Val;
603
604 if (AI.isIndirect()) {
605 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000606 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000607 assert(
608 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000609 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000610
611 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
612 CharUnits TyAlignForABI = TyInfo.second;
613
614 llvm::Type *BaseTy =
615 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
616 llvm::Value *Addr =
617 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
618 return Address(Addr, TyAlignForABI);
619 } else {
620 assert((AI.isDirect() || AI.isExtend()) &&
621 "Unexpected ArgInfo Kind in generic VAArg emitter!");
622
623 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000624 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000625 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000626 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000627 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000628 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000629 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000630 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000631
632 Address Temp = CGF.CreateMemTemp(Ty, "varet");
633 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
634 CGF.Builder.CreateStore(Val, Temp);
635 return Temp;
636 }
637}
638
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000639/// DefaultABIInfo - The default implementation for ABI specific
640/// details. This implementation provides information which results in
641/// self-consistent and sensible LLVM IR generation, but does not
642/// conform to any particular ABI.
643class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000644public:
645 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000646
Chris Lattner458b2aa2010-07-29 02:16:43 +0000647 ABIArgInfo classifyReturnType(QualType RetTy) const;
648 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000649
Craig Topper4f12f102014-03-12 06:41:41 +0000650 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000651 if (!getCXXABI().classifyReturnType(FI))
652 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000653 for (auto &I : FI.arguments())
654 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000655 }
656
John McCall7f416cc2015-09-08 08:05:57 +0000657 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000658 QualType Ty) const override {
659 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
660 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000661};
662
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000663class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
664public:
Chris Lattner2b037972010-07-29 02:01:43 +0000665 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
666 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000667};
668
Chris Lattner458b2aa2010-07-29 02:16:43 +0000669ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000670 Ty = useFirstFieldIfTransparentUnion(Ty);
671
672 if (isAggregateTypeForABI(Ty)) {
673 // Records with non-trivial destructors/copy-constructors should not be
674 // passed by value.
675 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000676 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000677
John McCall7f416cc2015-09-08 08:05:57 +0000678 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000679 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000680
Chris Lattner9723d6c2010-03-11 18:19:55 +0000681 // Treat an enum type as its underlying type.
682 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
683 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000684
Chris Lattner9723d6c2010-03-11 18:19:55 +0000685 return (Ty->isPromotableIntegerType() ?
686 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000687}
688
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000689ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
690 if (RetTy->isVoidType())
691 return ABIArgInfo::getIgnore();
692
693 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000694 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000695
696 // Treat an enum type as its underlying type.
697 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
698 RetTy = EnumTy->getDecl()->getIntegerType();
699
700 return (RetTy->isPromotableIntegerType() ?
701 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
702}
703
Derek Schuff09338a22012-09-06 17:37:28 +0000704//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000705// WebAssembly ABI Implementation
706//
707// This is a very simple ABI that relies a lot on DefaultABIInfo.
708//===----------------------------------------------------------------------===//
709
710class WebAssemblyABIInfo final : public DefaultABIInfo {
711public:
712 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
713 : DefaultABIInfo(CGT) {}
714
715private:
716 ABIArgInfo classifyReturnType(QualType RetTy) const;
717 ABIArgInfo classifyArgumentType(QualType Ty) const;
718
719 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000720 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000721 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000722 void computeInfo(CGFunctionInfo &FI) const override {
723 if (!getCXXABI().classifyReturnType(FI))
724 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
725 for (auto &Arg : FI.arguments())
726 Arg.info = classifyArgumentType(Arg.type);
727 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000728
729 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
730 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000731};
732
733class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
734public:
735 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
736 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
737};
738
739/// \brief Classify argument of given type \p Ty.
740ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
741 Ty = useFirstFieldIfTransparentUnion(Ty);
742
743 if (isAggregateTypeForABI(Ty)) {
744 // Records with non-trivial destructors/copy-constructors should not be
745 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000746 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000747 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000748 // Ignore empty structs/unions.
749 if (isEmptyRecord(getContext(), Ty, true))
750 return ABIArgInfo::getIgnore();
751 // Lower single-element structs to just pass a regular value. TODO: We
752 // could do reasonable-size multiple-element structs too, using getExpand(),
753 // though watch out for things like bitfields.
754 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
755 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000756 }
757
758 // Otherwise just do the default thing.
759 return DefaultABIInfo::classifyArgumentType(Ty);
760}
761
762ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
763 if (isAggregateTypeForABI(RetTy)) {
764 // Records with non-trivial destructors/copy-constructors should not be
765 // returned by value.
766 if (!getRecordArgABI(RetTy, getCXXABI())) {
767 // Ignore empty structs/unions.
768 if (isEmptyRecord(getContext(), RetTy, true))
769 return ABIArgInfo::getIgnore();
770 // Lower single-element structs to just return a regular value. TODO: We
771 // could do reasonable-size multiple-element structs too, using
772 // ABIArgInfo::getDirect().
773 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
774 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
775 }
776 }
777
778 // Otherwise just do the default thing.
779 return DefaultABIInfo::classifyReturnType(RetTy);
780}
781
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000782Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
783 QualType Ty) const {
784 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
785 getContext().getTypeInfoInChars(Ty),
786 CharUnits::fromQuantity(4),
787 /*AllowHigherAlign=*/ true);
788}
789
Dan Gohmanc2853072015-09-03 22:51:53 +0000790//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000791// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000792//
793// This is a simplified version of the x86_32 ABI. Arguments and return values
794// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000795//===----------------------------------------------------------------------===//
796
797class PNaClABIInfo : public ABIInfo {
798 public:
799 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
800
801 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000802 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000803
Craig Topper4f12f102014-03-12 06:41:41 +0000804 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000805 Address EmitVAArg(CodeGenFunction &CGF,
806 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000807};
808
809class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
810 public:
811 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
812 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
813};
814
815void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000816 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000817 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
818
Reid Kleckner40ca9132014-05-13 22:05:45 +0000819 for (auto &I : FI.arguments())
820 I.info = classifyArgumentType(I.type);
821}
Derek Schuff09338a22012-09-06 17:37:28 +0000822
John McCall7f416cc2015-09-08 08:05:57 +0000823Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
824 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000825 // The PNaCL ABI is a bit odd, in that varargs don't use normal
826 // function classification. Structs get passed directly for varargs
827 // functions, through a rewriting transform in
828 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
829 // this target to actually support a va_arg instructions with an
830 // aggregate type, unlike other targets.
831 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000832}
833
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000834/// \brief Classify argument of given type \p Ty.
835ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000836 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000837 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000838 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
839 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000840 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
841 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000842 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000843 } else if (Ty->isFloatingType()) {
844 // Floating-point types don't go inreg.
845 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000846 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000847
848 return (Ty->isPromotableIntegerType() ?
849 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000850}
851
852ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
853 if (RetTy->isVoidType())
854 return ABIArgInfo::getIgnore();
855
Eli Benderskye20dad62013-04-04 22:49:35 +0000856 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000857 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000858 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000859
860 // Treat an enum type as its underlying type.
861 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
862 RetTy = EnumTy->getDecl()->getIntegerType();
863
864 return (RetTy->isPromotableIntegerType() ?
865 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
866}
867
Chad Rosier651c1832013-03-25 21:00:27 +0000868/// IsX86_MMXType - Return true if this is an MMX type.
869bool IsX86_MMXType(llvm::Type *IRType) {
870 // 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 +0000871 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
872 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
873 IRType->getScalarSizeInBits() != 64;
874}
875
Jay Foad7c57be32011-07-11 09:56:20 +0000876static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000877 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000878 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000879 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
880 .Cases("y", "&y", "^Ym", true)
881 .Default(false);
882 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000883 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
884 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000885 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000886 }
887
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000888 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000889 }
890
891 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000892 return Ty;
893}
894
Reid Kleckner80944df2014-10-31 22:00:51 +0000895/// Returns true if this type can be passed in SSE registers with the
896/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
897static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
898 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000899 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
900 if (BT->getKind() == BuiltinType::LongDouble) {
901 if (&Context.getTargetInfo().getLongDoubleFormat() ==
902 &llvm::APFloat::x87DoubleExtended())
903 return false;
904 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000905 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000906 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000907 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
908 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
909 // registers specially.
910 unsigned VecSize = Context.getTypeSize(VT);
911 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
912 return true;
913 }
914 return false;
915}
916
917/// Returns true if this aggregate is small enough to be passed in SSE registers
918/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
919static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
920 return NumMembers <= 4;
921}
922
Erich Keane521ed962017-01-05 00:20:51 +0000923/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
924static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
925 auto AI = ABIArgInfo::getDirect(T);
926 AI.setInReg(true);
927 AI.setCanBeFlattened(false);
928 return AI;
929}
930
Chris Lattner0cf24192010-06-28 20:05:43 +0000931//===----------------------------------------------------------------------===//
932// X86-32 ABI Implementation
933//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000934
Reid Kleckner661f35b2014-01-18 01:12:41 +0000935/// \brief Similar to llvm::CCState, but for Clang.
936struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000937 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000938
939 unsigned CC;
940 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000941 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000942};
943
Erich Keane521ed962017-01-05 00:20:51 +0000944enum {
945 // Vectorcall only allows the first 6 parameters to be passed in registers.
946 VectorcallMaxParamNumAsReg = 6
947};
948
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000949/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000950class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000951 enum Class {
952 Integer,
953 Float
954 };
955
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000956 static const unsigned MinABIStackAlignInBytes = 4;
957
David Chisnallde3a0692009-08-17 23:08:21 +0000958 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000959 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000960 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000961 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000962 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000963 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000964
965 static bool isRegisterSize(unsigned Size) {
966 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
967 }
968
Reid Kleckner80944df2014-10-31 22:00:51 +0000969 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
970 // FIXME: Assumes vectorcall is in use.
971 return isX86VectorTypeForVectorCall(getContext(), Ty);
972 }
973
974 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
975 uint64_t NumMembers) const override {
976 // FIXME: Assumes vectorcall is in use.
977 return isX86VectorCallAggregateSmallEnough(NumMembers);
978 }
979
Reid Kleckner40ca9132014-05-13 22:05:45 +0000980 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000981
Daniel Dunbar557893d2010-04-21 19:10:51 +0000982 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
983 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000984 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
985
John McCall7f416cc2015-09-08 08:05:57 +0000986 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000987
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000988 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000989 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000990
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000991 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000992 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000993 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +0000994
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000995 /// \brief Updates the number of available free registers, returns
996 /// true if any registers were allocated.
997 bool updateFreeRegs(QualType Ty, CCState &State) const;
998
999 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1000 bool &NeedsPadding) const;
1001 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001002
Reid Kleckner04046052016-05-02 17:41:07 +00001003 bool canExpandIndirectArgument(QualType Ty) const;
1004
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001005 /// \brief Rewrite the function info so that all memory arguments use
1006 /// inalloca.
1007 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1008
1009 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001010 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001011 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001012 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1013 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001014
Rafael Espindola75419dc2012-07-23 23:30:29 +00001015public:
1016
Craig Topper4f12f102014-03-12 06:41:41 +00001017 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001018 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1019 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001020
Michael Kupersteindc745202015-10-19 07:52:25 +00001021 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1022 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001023 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001024 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001025 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1026 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001027 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001028 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001029 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001030
1031 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1032 ArrayRef<llvm::Type*> scalars,
1033 bool asReturnValue) const override {
1034 // LLVM's x86-32 lowering currently only assigns up to three
1035 // integer registers and three fp registers. Oddly, it'll use up to
1036 // four vector registers for vectors, but those can overlap with the
1037 // scalar registers.
1038 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1039 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001040
1041 bool isSwiftErrorInRegister() const override {
1042 // x86-32 lowering does not support passing swifterror in a register.
1043 return false;
1044 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001045};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001046
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001047class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1048public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001049 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1050 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001051 unsigned NumRegisterParameters, bool SoftFloatABI)
1052 : TargetCodeGenInfo(new X86_32ABIInfo(
1053 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1054 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001055
John McCall1fe2a8c2013-06-18 02:46:29 +00001056 static bool isStructReturnInRegABI(
1057 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1058
Eric Christopher162c91c2015-06-05 22:03:00 +00001059 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001060 CodeGen::CodeGenModule &CGM,
1061 ForDefinition_t IsForDefinition) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001062
Craig Topper4f12f102014-03-12 06:41:41 +00001063 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001064 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001065 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001066 return 4;
1067 }
1068
1069 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001070 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001071
Jay Foad7c57be32011-07-11 09:56:20 +00001072 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001073 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001074 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001075 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1076 }
1077
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001078 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1079 std::string &Constraints,
1080 std::vector<llvm::Type *> &ResultRegTypes,
1081 std::vector<llvm::Type *> &ResultTruncRegTypes,
1082 std::vector<LValue> &ResultRegDests,
1083 std::string &AsmString,
1084 unsigned NumOutputs) const override;
1085
Craig Topper4f12f102014-03-12 06:41:41 +00001086 llvm::Constant *
1087 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001088 unsigned Sig = (0xeb << 0) | // jmp rel8
1089 (0x06 << 8) | // .+0x08
Vedant Kumarbb5d4852017-09-13 00:04:35 +00001090 ('v' << 16) |
1091 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001092 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1093 }
John McCall01391782016-02-05 21:37:38 +00001094
1095 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1096 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001097 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001098 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001099};
1100
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001101}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001102
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001103/// Rewrite input constraint references after adding some output constraints.
1104/// In the case where there is one output and one input and we add one output,
1105/// we need to replace all operand references greater than or equal to 1:
1106/// mov $0, $1
1107/// mov eax, $1
1108/// The result will be:
1109/// mov $0, $2
1110/// mov eax, $2
1111static void rewriteInputConstraintReferences(unsigned FirstIn,
1112 unsigned NumNewOuts,
1113 std::string &AsmString) {
1114 std::string Buf;
1115 llvm::raw_string_ostream OS(Buf);
1116 size_t Pos = 0;
1117 while (Pos < AsmString.size()) {
1118 size_t DollarStart = AsmString.find('$', Pos);
1119 if (DollarStart == std::string::npos)
1120 DollarStart = AsmString.size();
1121 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1122 if (DollarEnd == std::string::npos)
1123 DollarEnd = AsmString.size();
1124 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1125 Pos = DollarEnd;
1126 size_t NumDollars = DollarEnd - DollarStart;
1127 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1128 // We have an operand reference.
1129 size_t DigitStart = Pos;
1130 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1131 if (DigitEnd == std::string::npos)
1132 DigitEnd = AsmString.size();
1133 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1134 unsigned OperandIndex;
1135 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1136 if (OperandIndex >= FirstIn)
1137 OperandIndex += NumNewOuts;
1138 OS << OperandIndex;
1139 } else {
1140 OS << OperandStr;
1141 }
1142 Pos = DigitEnd;
1143 }
1144 }
1145 AsmString = std::move(OS.str());
1146}
1147
1148/// Add output constraints for EAX:EDX because they are return registers.
1149void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1150 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1151 std::vector<llvm::Type *> &ResultRegTypes,
1152 std::vector<llvm::Type *> &ResultTruncRegTypes,
1153 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1154 unsigned NumOutputs) const {
1155 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1156
1157 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1158 // larger.
1159 if (!Constraints.empty())
1160 Constraints += ',';
1161 if (RetWidth <= 32) {
1162 Constraints += "={eax}";
1163 ResultRegTypes.push_back(CGF.Int32Ty);
1164 } else {
1165 // Use the 'A' constraint for EAX:EDX.
1166 Constraints += "=A";
1167 ResultRegTypes.push_back(CGF.Int64Ty);
1168 }
1169
1170 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1171 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1172 ResultTruncRegTypes.push_back(CoerceTy);
1173
1174 // Coerce the integer by bitcasting the return slot pointer.
1175 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1176 CoerceTy->getPointerTo()));
1177 ResultRegDests.push_back(ReturnSlot);
1178
1179 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1180}
1181
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001182/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001183/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001184bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1185 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001186 uint64_t Size = Context.getTypeSize(Ty);
1187
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001188 // For i386, type must be register sized.
1189 // For the MCU ABI, it only needs to be <= 8-byte
1190 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1191 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001192
1193 if (Ty->isVectorType()) {
1194 // 64- and 128- bit vectors inside structures are not returned in
1195 // registers.
1196 if (Size == 64 || Size == 128)
1197 return false;
1198
1199 return true;
1200 }
1201
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001202 // If this is a builtin, pointer, enum, complex type, member pointer, or
1203 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001204 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001205 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001206 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001207 return true;
1208
1209 // Arrays are treated like records.
1210 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001211 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001212
1213 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001214 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001215 if (!RT) return false;
1216
Anders Carlsson40446e82010-01-27 03:25:19 +00001217 // FIXME: Traverse bases here too.
1218
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001219 // Structure types are passed in register if all fields would be
1220 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001221 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001222 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001223 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001224 continue;
1225
1226 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001227 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001228 return false;
1229 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001230 return true;
1231}
1232
Reid Kleckner04046052016-05-02 17:41:07 +00001233static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1234 // Treat complex types as the element type.
1235 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1236 Ty = CTy->getElementType();
1237
1238 // Check for a type which we know has a simple scalar argument-passing
1239 // convention without any padding. (We're specifically looking for 32
1240 // and 64-bit integer and integer-equivalents, float, and double.)
1241 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1242 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1243 return false;
1244
1245 uint64_t Size = Context.getTypeSize(Ty);
1246 return Size == 32 || Size == 64;
1247}
1248
Reid Kleckner791bbf62017-01-13 17:18:19 +00001249static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1250 uint64_t &Size) {
1251 for (const auto *FD : RD->fields()) {
1252 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1253 // argument is smaller than 32-bits, expanding the struct will create
1254 // alignment padding.
1255 if (!is32Or64BitBasicType(FD->getType(), Context))
1256 return false;
1257
1258 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1259 // how to expand them yet, and the predicate for telling if a bitfield still
1260 // counts as "basic" is more complicated than what we were doing previously.
1261 if (FD->isBitField())
1262 return false;
1263
1264 Size += Context.getTypeSize(FD->getType());
1265 }
1266 return true;
1267}
1268
1269static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1270 uint64_t &Size) {
1271 // Don't do this if there are any non-empty bases.
1272 for (const CXXBaseSpecifier &Base : RD->bases()) {
1273 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1274 Size))
1275 return false;
1276 }
1277 if (!addFieldSizes(Context, RD, Size))
1278 return false;
1279 return true;
1280}
1281
Reid Kleckner04046052016-05-02 17:41:07 +00001282/// Test whether an argument type which is to be passed indirectly (on the
1283/// stack) would have the equivalent layout if it was expanded into separate
1284/// arguments. If so, we prefer to do the latter to avoid inhibiting
1285/// optimizations.
1286bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1287 // We can only expand structure types.
1288 const RecordType *RT = Ty->getAs<RecordType>();
1289 if (!RT)
1290 return false;
1291 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001292 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001293 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001294 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001295 // On non-Windows, we have to conservatively match our old bitcode
1296 // prototypes in order to be ABI-compatible at the bitcode level.
1297 if (!CXXRD->isCLike())
1298 return false;
1299 } else {
1300 // Don't do this for dynamic classes.
1301 if (CXXRD->isDynamicClass())
1302 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001303 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001304 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001305 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001306 } else {
1307 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001308 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001309 }
1310
1311 // We can do this if there was no alignment padding.
1312 return Size == getContext().getTypeSize(Ty);
1313}
1314
John McCall7f416cc2015-09-08 08:05:57 +00001315ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001316 // If the return value is indirect, then the hidden argument is consuming one
1317 // integer register.
1318 if (State.FreeRegs) {
1319 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001320 if (!IsMCUABI)
1321 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001322 }
John McCall7f416cc2015-09-08 08:05:57 +00001323 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001324}
1325
Eric Christopher7565e0d2015-05-29 23:09:49 +00001326ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1327 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001328 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001329 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001330
Reid Kleckner80944df2014-10-31 22:00:51 +00001331 const Type *Base = nullptr;
1332 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001333 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1334 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001335 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1336 // The LLVM struct type for such an aggregate should lower properly.
1337 return ABIArgInfo::getDirect();
1338 }
1339
Chris Lattner458b2aa2010-07-29 02:16:43 +00001340 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001341 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001342 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001343 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001344
1345 // 128-bit vectors are a special case; they are returned in
1346 // registers and we need to make sure to pick a type the LLVM
1347 // backend will like.
1348 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001349 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001350 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001351
1352 // Always return in register if it fits in a general purpose
1353 // register, or if it is 64 bits and has a single element.
1354 if ((Size == 8 || Size == 16 || Size == 32) ||
1355 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001356 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001357 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001358
John McCall7f416cc2015-09-08 08:05:57 +00001359 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001360 }
1361
1362 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001363 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001364
John McCalla1dee5302010-08-22 10:59:02 +00001365 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001366 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001367 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001368 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001369 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001370 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001371
David Chisnallde3a0692009-08-17 23:08:21 +00001372 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001373 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001374 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001375
Denis Zobnin380b2242016-02-11 11:26:03 +00001376 // Ignore empty structs/unions.
1377 if (isEmptyRecord(getContext(), RetTy, true))
1378 return ABIArgInfo::getIgnore();
1379
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001380 // Small structures which are register sized are generally returned
1381 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001382 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001383 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001384
1385 // As a special-case, if the struct is a "single-element" struct, and
1386 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001387 // floating-point register. (MSVC does not apply this special case.)
1388 // We apply a similar transformation for pointer types to improve the
1389 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001390 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001391 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001392 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001393 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1394
1395 // FIXME: We should be able to narrow this integer in cases with dead
1396 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001397 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001398 }
1399
John McCall7f416cc2015-09-08 08:05:57 +00001400 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001401 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001402
Chris Lattner458b2aa2010-07-29 02:16:43 +00001403 // Treat an enum type as its underlying type.
1404 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1405 RetTy = EnumTy->getDecl()->getIntegerType();
1406
1407 return (RetTy->isPromotableIntegerType() ?
1408 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001409}
1410
Eli Friedman7919bea2012-06-05 19:40:46 +00001411static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1412 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1413}
1414
Daniel Dunbared23de32010-09-16 20:42:00 +00001415static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1416 const RecordType *RT = Ty->getAs<RecordType>();
1417 if (!RT)
1418 return 0;
1419 const RecordDecl *RD = RT->getDecl();
1420
1421 // If this is a C++ record, check the bases first.
1422 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001423 for (const auto &I : CXXRD->bases())
1424 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001425 return false;
1426
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001427 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001428 QualType FT = i->getType();
1429
Eli Friedman7919bea2012-06-05 19:40:46 +00001430 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001431 return true;
1432
1433 if (isRecordWithSSEVectorType(Context, FT))
1434 return true;
1435 }
1436
1437 return false;
1438}
1439
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001440unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1441 unsigned Align) const {
1442 // Otherwise, if the alignment is less than or equal to the minimum ABI
1443 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001444 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001445 return 0; // Use default alignment.
1446
1447 // On non-Darwin, the stack type alignment is always 4.
1448 if (!IsDarwinVectorABI) {
1449 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001450 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001451 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001452
Daniel Dunbared23de32010-09-16 20:42:00 +00001453 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001454 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1455 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001456 return 16;
1457
1458 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001459}
1460
Rafael Espindola703c47f2012-10-19 05:04:37 +00001461ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001462 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001463 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001464 if (State.FreeRegs) {
1465 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001466 if (!IsMCUABI)
1467 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001468 }
John McCall7f416cc2015-09-08 08:05:57 +00001469 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001470 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001471
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001472 // Compute the byval alignment.
1473 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1474 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1475 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001476 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001477
1478 // If the stack alignment is less than the type alignment, realign the
1479 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001480 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001481 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1482 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001483}
1484
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001485X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1486 const Type *T = isSingleElementStruct(Ty, getContext());
1487 if (!T)
1488 T = Ty.getTypePtr();
1489
1490 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1491 BuiltinType::Kind K = BT->getKind();
1492 if (K == BuiltinType::Float || K == BuiltinType::Double)
1493 return Float;
1494 }
1495 return Integer;
1496}
1497
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001498bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001499 if (!IsSoftFloatABI) {
1500 Class C = classify(Ty);
1501 if (C == Float)
1502 return false;
1503 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001504
Rafael Espindola077dd592012-10-24 01:58:58 +00001505 unsigned Size = getContext().getTypeSize(Ty);
1506 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001507
1508 if (SizeInRegs == 0)
1509 return false;
1510
Michael Kuperstein68901882015-10-25 08:18:20 +00001511 if (!IsMCUABI) {
1512 if (SizeInRegs > State.FreeRegs) {
1513 State.FreeRegs = 0;
1514 return false;
1515 }
1516 } else {
1517 // The MCU psABI allows passing parameters in-reg even if there are
1518 // earlier parameters that are passed on the stack. Also,
1519 // it does not allow passing >8-byte structs in-register,
1520 // even if there are 3 free registers available.
1521 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1522 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001523 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001524
Reid Kleckner661f35b2014-01-18 01:12:41 +00001525 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001526 return true;
1527}
1528
1529bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1530 bool &InReg,
1531 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001532 // On Windows, aggregates other than HFAs are never passed in registers, and
1533 // they do not consume register slots. Homogenous floating-point aggregates
1534 // (HFAs) have already been dealt with at this point.
1535 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1536 return false;
1537
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001538 NeedsPadding = false;
1539 InReg = !IsMCUABI;
1540
1541 if (!updateFreeRegs(Ty, State))
1542 return false;
1543
1544 if (IsMCUABI)
1545 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001546
Reid Kleckner80944df2014-10-31 22:00:51 +00001547 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001548 State.CC == llvm::CallingConv::X86_VectorCall ||
1549 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001550 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001551 NeedsPadding = true;
1552
Rafael Espindola077dd592012-10-24 01:58:58 +00001553 return false;
1554 }
1555
Rafael Espindola703c47f2012-10-19 05:04:37 +00001556 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001557}
1558
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001559bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1560 if (!updateFreeRegs(Ty, State))
1561 return false;
1562
1563 if (IsMCUABI)
1564 return false;
1565
1566 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001567 State.CC == llvm::CallingConv::X86_VectorCall ||
1568 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001569 if (getContext().getTypeSize(Ty) > 32)
1570 return false;
1571
1572 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1573 Ty->isReferenceType());
1574 }
1575
1576 return true;
1577}
1578
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001579ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1580 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001581 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001582
Reid Klecknerb1be6832014-11-15 01:41:41 +00001583 Ty = useFirstFieldIfTransparentUnion(Ty);
1584
Reid Kleckner80944df2014-10-31 22:00:51 +00001585 // Check with the C++ ABI first.
1586 const RecordType *RT = Ty->getAs<RecordType>();
1587 if (RT) {
1588 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1589 if (RAA == CGCXXABI::RAA_Indirect) {
1590 return getIndirectResult(Ty, false, State);
1591 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1592 // The field index doesn't matter, we'll fix it up later.
1593 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1594 }
1595 }
1596
Erich Keane4bd39302017-06-21 16:37:22 +00001597 // Regcall uses the concept of a homogenous vector aggregate, similar
1598 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001599 const Type *Base = nullptr;
1600 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001601 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001602 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001603
Erich Keane4bd39302017-06-21 16:37:22 +00001604 if (State.FreeSSERegs >= NumElts) {
1605 State.FreeSSERegs -= NumElts;
1606 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001607 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001608 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001609 }
Erich Keane4bd39302017-06-21 16:37:22 +00001610 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001611 }
1612
1613 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001614 // Structures with flexible arrays are always indirect.
1615 // FIXME: This should not be byval!
1616 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1617 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001618
Reid Kleckner04046052016-05-02 17:41:07 +00001619 // Ignore empty structs/unions on non-Windows.
1620 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001621 return ABIArgInfo::getIgnore();
1622
Rafael Espindolafad28de2012-10-24 01:59:00 +00001623 llvm::LLVMContext &LLVMContext = getVMContext();
1624 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001625 bool NeedsPadding = false;
1626 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001627 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001628 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001629 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001630 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001631 if (InReg)
1632 return ABIArgInfo::getDirectInReg(Result);
1633 else
1634 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001635 }
Craig Topper8a13c412014-05-21 05:09:00 +00001636 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001637
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001638 // Expand small (<= 128-bit) record types when we know that the stack layout
1639 // of those arguments will match the struct. This is important because the
1640 // LLVM backend isn't smart enough to remove byval, which inhibits many
1641 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001642 // Don't do this for the MCU if there are still free integer registers
1643 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001644 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1645 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001646 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001647 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001648 State.CC == llvm::CallingConv::X86_VectorCall ||
1649 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001650 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001651
Reid Kleckner661f35b2014-01-18 01:12:41 +00001652 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001653 }
1654
Chris Lattnerd774ae92010-08-26 20:05:13 +00001655 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001656 // On Darwin, some vectors are passed in memory, we handle this by passing
1657 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001658 if (IsDarwinVectorABI) {
1659 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001660 if ((Size == 8 || Size == 16 || Size == 32) ||
1661 (Size == 64 && VT->getNumElements() == 1))
1662 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1663 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001664 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001665
Chad Rosier651c1832013-03-25 21:00:27 +00001666 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1667 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001668
Chris Lattnerd774ae92010-08-26 20:05:13 +00001669 return ABIArgInfo::getDirect();
1670 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001671
1672
Chris Lattner458b2aa2010-07-29 02:16:43 +00001673 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1674 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001675
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001676 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001677
1678 if (Ty->isPromotableIntegerType()) {
1679 if (InReg)
1680 return ABIArgInfo::getExtendInReg();
1681 return ABIArgInfo::getExtend();
1682 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001683
Rafael Espindola703c47f2012-10-19 05:04:37 +00001684 if (InReg)
1685 return ABIArgInfo::getDirectInReg();
1686 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001687}
1688
Erich Keane521ed962017-01-05 00:20:51 +00001689void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1690 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001691 // Vectorcall x86 works subtly different than in x64, so the format is
1692 // a bit different than the x64 version. First, all vector types (not HVAs)
1693 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1694 // This differs from the x64 implementation, where the first 6 by INDEX get
1695 // registers.
1696 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1697 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1698 // first take up the remaining YMM/XMM registers. If insufficient registers
1699 // remain but an integer register (ECX/EDX) is available, it will be passed
1700 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001701 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001702 // First pass do all the vector types.
1703 const Type *Base = nullptr;
1704 uint64_t NumElts = 0;
1705 const QualType& Ty = I.type;
1706 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1707 isHomogeneousAggregate(Ty, Base, NumElts)) {
1708 if (State.FreeSSERegs >= NumElts) {
1709 State.FreeSSERegs -= NumElts;
1710 I.info = ABIArgInfo::getDirect();
1711 } else {
1712 I.info = classifyArgumentType(Ty, State);
1713 }
1714 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1715 }
Erich Keane521ed962017-01-05 00:20:51 +00001716 }
Erich Keane4bd39302017-06-21 16:37:22 +00001717
Erich Keane521ed962017-01-05 00:20:51 +00001718 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001719 // Second pass, do the rest!
1720 const Type *Base = nullptr;
1721 uint64_t NumElts = 0;
1722 const QualType& Ty = I.type;
1723 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1724
1725 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1726 // Assign true HVAs (non vector/native FP types).
1727 if (State.FreeSSERegs >= NumElts) {
1728 State.FreeSSERegs -= NumElts;
1729 I.info = getDirectX86Hva();
1730 } else {
1731 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1732 }
1733 } else if (!IsHva) {
1734 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1735 I.info = classifyArgumentType(Ty, State);
1736 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1737 }
Erich Keane521ed962017-01-05 00:20:51 +00001738 }
1739}
1740
Rafael Espindolaa6472962012-07-24 00:01:07 +00001741void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001742 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001743 if (IsMCUABI)
1744 State.FreeRegs = 3;
1745 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001746 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001747 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1748 State.FreeRegs = 2;
1749 State.FreeSSERegs = 6;
1750 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001751 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001752 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1753 State.FreeRegs = 5;
1754 State.FreeSSERegs = 8;
1755 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001756 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001757
Reid Kleckner677539d2014-07-10 01:58:55 +00001758 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001759 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001760 } else if (FI.getReturnInfo().isIndirect()) {
1761 // The C++ ABI is not aware of register usage, so we have to check if the
1762 // return value was sret and put it in a register ourselves if appropriate.
1763 if (State.FreeRegs) {
1764 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001765 if (!IsMCUABI)
1766 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001767 }
1768 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001769
Peter Collingbournef7706832014-12-12 23:41:25 +00001770 // The chain argument effectively gives us another free register.
1771 if (FI.isChainCall())
1772 ++State.FreeRegs;
1773
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001774 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001775 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1776 computeVectorCallArgs(FI, State, UsedInAlloca);
1777 } else {
1778 // If not vectorcall, revert to normal behavior.
1779 for (auto &I : FI.arguments()) {
1780 I.info = classifyArgumentType(I.type, State);
1781 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1782 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001783 }
1784
1785 // If we needed to use inalloca for any argument, do a second pass and rewrite
1786 // all the memory arguments to use inalloca.
1787 if (UsedInAlloca)
1788 rewriteWithInAlloca(FI);
1789}
1790
1791void
1792X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001793 CharUnits &StackOffset, ABIArgInfo &Info,
1794 QualType Type) const {
1795 // Arguments are always 4-byte-aligned.
1796 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1797
1798 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001799 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1800 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001801 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001802
John McCall7f416cc2015-09-08 08:05:57 +00001803 // Insert padding bytes to respect alignment.
1804 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001805 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001806 if (StackOffset != FieldEnd) {
1807 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001808 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001809 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001810 FrameFields.push_back(Ty);
1811 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001812}
1813
Reid Kleckner852361d2014-07-26 00:12:26 +00001814static bool isArgInAlloca(const ABIArgInfo &Info) {
1815 // Leave ignored and inreg arguments alone.
1816 switch (Info.getKind()) {
1817 case ABIArgInfo::InAlloca:
1818 return true;
1819 case ABIArgInfo::Indirect:
1820 assert(Info.getIndirectByVal());
1821 return true;
1822 case ABIArgInfo::Ignore:
1823 return false;
1824 case ABIArgInfo::Direct:
1825 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001826 if (Info.getInReg())
1827 return false;
1828 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001829 case ABIArgInfo::Expand:
1830 case ABIArgInfo::CoerceAndExpand:
1831 // These are aggregate types which are never passed in registers when
1832 // inalloca is involved.
1833 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001834 }
1835 llvm_unreachable("invalid enum");
1836}
1837
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001838void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1839 assert(IsWin32StructABI && "inalloca only supported on win32");
1840
1841 // Build a packed struct type for all of the arguments in memory.
1842 SmallVector<llvm::Type *, 6> FrameFields;
1843
John McCall7f416cc2015-09-08 08:05:57 +00001844 // The stack alignment is always 4.
1845 CharUnits StackAlign = CharUnits::fromQuantity(4);
1846
1847 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001848 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1849
1850 // Put 'this' into the struct before 'sret', if necessary.
1851 bool IsThisCall =
1852 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1853 ABIArgInfo &Ret = FI.getReturnInfo();
1854 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1855 isArgInAlloca(I->info)) {
1856 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1857 ++I;
1858 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001859
1860 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001861 if (Ret.isIndirect() && !Ret.getInReg()) {
1862 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1863 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001864 // On Windows, the hidden sret parameter is always returned in eax.
1865 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001866 }
1867
1868 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001869 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001870 ++I;
1871
1872 // Put arguments passed in memory into the struct.
1873 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001874 if (isArgInAlloca(I->info))
1875 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001876 }
1877
1878 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001879 /*isPacked=*/true),
1880 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001881}
1882
John McCall7f416cc2015-09-08 08:05:57 +00001883Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1884 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001885
John McCall7f416cc2015-09-08 08:05:57 +00001886 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001887
John McCall7f416cc2015-09-08 08:05:57 +00001888 // x86-32 changes the alignment of certain arguments on the stack.
1889 //
1890 // Just messing with TypeInfo like this works because we never pass
1891 // anything indirectly.
1892 TypeInfo.second = CharUnits::fromQuantity(
1893 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001894
John McCall7f416cc2015-09-08 08:05:57 +00001895 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1896 TypeInfo, CharUnits::fromQuantity(4),
1897 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001898}
1899
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001900bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1901 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1902 assert(Triple.getArch() == llvm::Triple::x86);
1903
1904 switch (Opts.getStructReturnConvention()) {
1905 case CodeGenOptions::SRCK_Default:
1906 break;
1907 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1908 return false;
1909 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1910 return true;
1911 }
1912
Michael Kupersteind749f232015-10-27 07:46:22 +00001913 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001914 return true;
1915
1916 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001917 case llvm::Triple::DragonFly:
1918 case llvm::Triple::FreeBSD:
1919 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001920 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001921 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001922 default:
1923 return false;
1924 }
1925}
1926
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001927void X86_32TargetCodeGenInfo::setTargetAttributes(
1928 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
1929 ForDefinition_t IsForDefinition) const {
1930 if (!IsForDefinition)
1931 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001932 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001933 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1934 // Get the LLVM function.
1935 llvm::Function *Fn = cast<llvm::Function>(GV);
1936
1937 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001938 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001939 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001940 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001941 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001942 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1943 llvm::Function *Fn = cast<llvm::Function>(GV);
1944 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1945 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001946 }
1947}
1948
John McCallbeec5a02010-03-06 00:35:14 +00001949bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1950 CodeGen::CodeGenFunction &CGF,
1951 llvm::Value *Address) const {
1952 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001953
Chris Lattnerece04092012-02-07 00:39:47 +00001954 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001955
John McCallbeec5a02010-03-06 00:35:14 +00001956 // 0-7 are the eight integer registers; the order is different
1957 // on Darwin (for EH), but the range is the same.
1958 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001959 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001960
John McCallc8e01702013-04-16 22:48:15 +00001961 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001962 // 12-16 are st(0..4). Not sure why we stop at 4.
1963 // These have size 16, which is sizeof(long double) on
1964 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001965 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001966 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001967
John McCallbeec5a02010-03-06 00:35:14 +00001968 } else {
1969 // 9 is %eflags, which doesn't get a size on Darwin for some
1970 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001971 Builder.CreateAlignedStore(
1972 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1973 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001974
1975 // 11-16 are st(0..5). Not sure why we stop at 5.
1976 // These have size 12, which is sizeof(long double) on
1977 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001978 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001979 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1980 }
John McCallbeec5a02010-03-06 00:35:14 +00001981
1982 return false;
1983}
1984
Chris Lattner0cf24192010-06-28 20:05:43 +00001985//===----------------------------------------------------------------------===//
1986// X86-64 ABI Implementation
1987//===----------------------------------------------------------------------===//
1988
1989
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001990namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001991/// The AVX ABI level for X86 targets.
1992enum class X86AVXABILevel {
1993 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001994 AVX,
1995 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001996};
1997
1998/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1999static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2000 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002001 case X86AVXABILevel::AVX512:
2002 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002003 case X86AVXABILevel::AVX:
2004 return 256;
2005 case X86AVXABILevel::None:
2006 return 128;
2007 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002008 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002009}
2010
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002011/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002012class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002013 enum Class {
2014 Integer = 0,
2015 SSE,
2016 SSEUp,
2017 X87,
2018 X87Up,
2019 ComplexX87,
2020 NoClass,
2021 Memory
2022 };
2023
2024 /// merge - Implement the X86_64 ABI merging algorithm.
2025 ///
2026 /// Merge an accumulating classification \arg Accum with a field
2027 /// classification \arg Field.
2028 ///
2029 /// \param Accum - The accumulating classification. This should
2030 /// always be either NoClass or the result of a previous merge
2031 /// call. In addition, this should never be Memory (the caller
2032 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002033 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002034
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002035 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2036 ///
2037 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2038 /// final MEMORY or SSE classes when necessary.
2039 ///
2040 /// \param AggregateSize - The size of the current aggregate in
2041 /// the classification process.
2042 ///
2043 /// \param Lo - The classification for the parts of the type
2044 /// residing in the low word of the containing object.
2045 ///
2046 /// \param Hi - The classification for the parts of the type
2047 /// residing in the higher words of the containing object.
2048 ///
2049 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2050
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002051 /// classify - Determine the x86_64 register classes in which the
2052 /// given type T should be passed.
2053 ///
2054 /// \param Lo - The classification for the parts of the type
2055 /// residing in the low word of the containing object.
2056 ///
2057 /// \param Hi - The classification for the parts of the type
2058 /// residing in the high word of the containing object.
2059 ///
2060 /// \param OffsetBase - The bit offset of this type in the
2061 /// containing object. Some parameters are classified different
2062 /// depending on whether they straddle an eightbyte boundary.
2063 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002064 /// \param isNamedArg - Whether the argument in question is a "named"
2065 /// argument, as used in AMD64-ABI 3.5.7.
2066 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002067 /// If a word is unused its result will be NoClass; if a type should
2068 /// be passed in Memory then at least the classification of \arg Lo
2069 /// will be Memory.
2070 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002071 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002072 ///
2073 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2074 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002075 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2076 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002077
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002078 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002079 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2080 unsigned IROffset, QualType SourceTy,
2081 unsigned SourceOffset) const;
2082 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2083 unsigned IROffset, QualType SourceTy,
2084 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002085
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002086 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002087 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002088 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002089
2090 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002091 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002092 ///
2093 /// \param freeIntRegs - The number of free integer registers remaining
2094 /// available.
2095 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002096
Chris Lattner458b2aa2010-07-29 02:16:43 +00002097 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002098
Erich Keane757d3172016-11-02 18:29:35 +00002099 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2100 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002101 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002102
Erich Keane757d3172016-11-02 18:29:35 +00002103 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2104 unsigned &NeededSSE) const;
2105
2106 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2107 unsigned &NeededSSE) const;
2108
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002109 bool IsIllegalVectorType(QualType Ty) const;
2110
John McCalle0fda732011-04-21 01:20:55 +00002111 /// The 0.98 ABI revision clarified a lot of ambiguities,
2112 /// unfortunately in ways that were not always consistent with
2113 /// certain previous compilers. In particular, platforms which
2114 /// required strict binary compatibility with older versions of GCC
2115 /// may need to exempt themselves.
2116 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002117 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002118 }
2119
Richard Smithf667ad52017-08-26 01:04:35 +00002120 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2121 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002122 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002123 // Clang <= 3.8 did not do this.
2124 if (getCodeGenOpts().getClangABICompat() <=
2125 CodeGenOptions::ClangABI::Ver3_8)
2126 return false;
2127
David Majnemere2ae2282016-03-04 05:26:16 +00002128 const llvm::Triple &Triple = getTarget().getTriple();
2129 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2130 return false;
2131 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2132 return false;
2133 return true;
2134 }
2135
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002136 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002137 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2138 // 64-bit hardware.
2139 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002140
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002141public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002142 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002143 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002144 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002145 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002146
John McCalla729c622012-02-17 03:33:10 +00002147 bool isPassedUsingAVXType(QualType type) const {
2148 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002149 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002150 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2151 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002152 if (info.isDirect()) {
2153 llvm::Type *ty = info.getCoerceToType();
2154 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2155 return (vectorTy->getBitWidth() > 128);
2156 }
2157 return false;
2158 }
2159
Craig Topper4f12f102014-03-12 06:41:41 +00002160 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002161
John McCall7f416cc2015-09-08 08:05:57 +00002162 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2163 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002164 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2165 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002166
2167 bool has64BitPointers() const {
2168 return Has64BitPointers;
2169 }
John McCall12f23522016-04-04 18:33:08 +00002170
2171 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2172 ArrayRef<llvm::Type*> scalars,
2173 bool asReturnValue) const override {
2174 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2175 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002176 bool isSwiftErrorInRegister() const override {
2177 return true;
2178 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002179};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002180
Chris Lattner04dc9572010-08-31 16:44:54 +00002181/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002182class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002183public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002184 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002185 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002186 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002187
Craig Topper4f12f102014-03-12 06:41:41 +00002188 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002189
John McCall7f416cc2015-09-08 08:05:57 +00002190 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2191 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002192
2193 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2194 // FIXME: Assumes vectorcall is in use.
2195 return isX86VectorTypeForVectorCall(getContext(), Ty);
2196 }
2197
2198 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2199 uint64_t NumMembers) const override {
2200 // FIXME: Assumes vectorcall is in use.
2201 return isX86VectorCallAggregateSmallEnough(NumMembers);
2202 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002203
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002204 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2205 ArrayRef<llvm::Type *> scalars,
2206 bool asReturnValue) const override {
2207 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2208 }
2209
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002210 bool isSwiftErrorInRegister() const override {
2211 return true;
2212 }
2213
Reid Kleckner11a17192015-10-28 22:29:52 +00002214private:
Erich Keane521ed962017-01-05 00:20:51 +00002215 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2216 bool IsVectorCall, bool IsRegCall) const;
2217 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2218 const ABIArgInfo &current) const;
2219 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2220 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002221
Erich Keane521ed962017-01-05 00:20:51 +00002222 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002223};
2224
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002225class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2226public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002227 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002228 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002229
John McCalla729c622012-02-17 03:33:10 +00002230 const X86_64ABIInfo &getABIInfo() const {
2231 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2232 }
2233
Craig Topper4f12f102014-03-12 06:41:41 +00002234 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002235 return 7;
2236 }
2237
2238 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002239 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002240 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002241
John McCall943fae92010-05-27 06:19:26 +00002242 // 0-15 are the 16 integer registers.
2243 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002244 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002245 return false;
2246 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002247
Jay Foad7c57be32011-07-11 09:56:20 +00002248 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002249 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002250 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002251 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2252 }
2253
John McCalla729c622012-02-17 03:33:10 +00002254 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002255 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002256 // The default CC on x86-64 sets %al to the number of SSA
2257 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002258 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002259 // that when AVX types are involved: the ABI explicitly states it is
2260 // undefined, and it doesn't work in practice because of how the ABI
2261 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002262 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002263 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002264 for (CallArgList::const_iterator
2265 it = args.begin(), ie = args.end(); it != ie; ++it) {
2266 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2267 HasAVXType = true;
2268 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002269 }
2270 }
John McCalla729c622012-02-17 03:33:10 +00002271
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002272 if (!HasAVXType)
2273 return true;
2274 }
John McCallcbc038a2011-09-21 08:08:30 +00002275
John McCalla729c622012-02-17 03:33:10 +00002276 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002277 }
2278
Craig Topper4f12f102014-03-12 06:41:41 +00002279 llvm::Constant *
2280 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Vedant Kumarbb5d4852017-09-13 00:04:35 +00002281 unsigned Sig = (0xeb << 0) | // jmp rel8
2282 (0x06 << 8) | // .+0x08
2283 ('v' << 16) |
2284 ('2' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002285 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2286 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002287
2288 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002289 CodeGen::CodeGenModule &CGM,
2290 ForDefinition_t IsForDefinition) const override {
2291 if (!IsForDefinition)
2292 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002293 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002294 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2295 // Get the LLVM function.
2296 auto *Fn = cast<llvm::Function>(GV);
2297
2298 // Now add the 'alignstack' attribute with a value of 16.
2299 llvm::AttrBuilder B;
2300 B.addStackAlignmentAttr(16);
2301 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2302 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002303 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2304 llvm::Function *Fn = cast<llvm::Function>(GV);
2305 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2306 }
2307 }
2308 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002309};
2310
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002311class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2312public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002313 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2314 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002315
2316 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002317 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002318 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002319 // If the argument contains a space, enclose it in quotes.
2320 if (Lib.find(" ") != StringRef::npos)
2321 Opt += "\"" + Lib.str() + "\"";
2322 else
2323 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002324 }
2325};
2326
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002327static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002328 // If the argument does not end in .lib, automatically add the suffix.
2329 // If the argument contains a space, enclose it in quotes.
2330 // This matches the behavior of MSVC.
2331 bool Quote = (Lib.find(" ") != StringRef::npos);
2332 std::string ArgStr = Quote ? "\"" : "";
2333 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002334 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002335 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002336 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002337 return ArgStr;
2338}
2339
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002340class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2341public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002342 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002343 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2344 unsigned NumRegisterParameters)
2345 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002346 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002347
Eric Christopher162c91c2015-06-05 22:03:00 +00002348 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002349 CodeGen::CodeGenModule &CGM,
2350 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002351
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002352 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002353 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002354 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002355 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002356 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002357
2358 void getDetectMismatchOption(llvm::StringRef Name,
2359 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002360 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002361 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002362 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002363};
2364
Hans Wennborg77dc2362015-01-20 19:45:50 +00002365static void addStackProbeSizeTargetAttribute(const Decl *D,
2366 llvm::GlobalValue *GV,
2367 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002368 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002369 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2370 llvm::Function *Fn = cast<llvm::Function>(GV);
2371
Eric Christopher7565e0d2015-05-29 23:09:49 +00002372 Fn->addFnAttr("stack-probe-size",
2373 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002374 }
2375 }
2376}
2377
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002378void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2379 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2380 ForDefinition_t IsForDefinition) const {
2381 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2382 if (!IsForDefinition)
2383 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002384 addStackProbeSizeTargetAttribute(D, GV, CGM);
2385}
2386
Chris Lattner04dc9572010-08-31 16:44:54 +00002387class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2388public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002389 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2390 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002391 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002392
Eric Christopher162c91c2015-06-05 22:03:00 +00002393 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002394 CodeGen::CodeGenModule &CGM,
2395 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002396
Craig Topper4f12f102014-03-12 06:41:41 +00002397 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002398 return 7;
2399 }
2400
2401 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002402 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002403 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002404
Chris Lattner04dc9572010-08-31 16:44:54 +00002405 // 0-15 are the 16 integer registers.
2406 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002407 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002408 return false;
2409 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002410
2411 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002412 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002413 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002414 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002415 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002416
2417 void getDetectMismatchOption(llvm::StringRef Name,
2418 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002419 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002420 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002421 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002422};
2423
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002424void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2425 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2426 ForDefinition_t IsForDefinition) const {
2427 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2428 if (!IsForDefinition)
2429 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002430 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002431 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2432 // Get the LLVM function.
2433 auto *Fn = cast<llvm::Function>(GV);
2434
2435 // Now add the 'alignstack' attribute with a value of 16.
2436 llvm::AttrBuilder B;
2437 B.addStackAlignmentAttr(16);
2438 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2439 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002440 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2441 llvm::Function *Fn = cast<llvm::Function>(GV);
2442 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2443 }
2444 }
2445
Hans Wennborg77dc2362015-01-20 19:45:50 +00002446 addStackProbeSizeTargetAttribute(D, GV, CGM);
2447}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002448}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002449
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002450void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2451 Class &Hi) const {
2452 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2453 //
2454 // (a) If one of the classes is Memory, the whole argument is passed in
2455 // memory.
2456 //
2457 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2458 // memory.
2459 //
2460 // (c) If the size of the aggregate exceeds two eightbytes and the first
2461 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2462 // argument is passed in memory. NOTE: This is necessary to keep the
2463 // ABI working for processors that don't support the __m256 type.
2464 //
2465 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2466 //
2467 // Some of these are enforced by the merging logic. Others can arise
2468 // only with unions; for example:
2469 // union { _Complex double; unsigned; }
2470 //
2471 // Note that clauses (b) and (c) were added in 0.98.
2472 //
2473 if (Hi == Memory)
2474 Lo = Memory;
2475 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2476 Lo = Memory;
2477 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2478 Lo = Memory;
2479 if (Hi == SSEUp && Lo != SSE)
2480 Hi = SSE;
2481}
2482
Chris Lattnerd776fb12010-06-28 21:43:59 +00002483X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002484 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2485 // classified recursively so that always two fields are
2486 // considered. The resulting class is calculated according to
2487 // the classes of the fields in the eightbyte:
2488 //
2489 // (a) If both classes are equal, this is the resulting class.
2490 //
2491 // (b) If one of the classes is NO_CLASS, the resulting class is
2492 // the other class.
2493 //
2494 // (c) If one of the classes is MEMORY, the result is the MEMORY
2495 // class.
2496 //
2497 // (d) If one of the classes is INTEGER, the result is the
2498 // INTEGER.
2499 //
2500 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2501 // MEMORY is used as class.
2502 //
2503 // (f) Otherwise class SSE is used.
2504
2505 // Accum should never be memory (we should have returned) or
2506 // ComplexX87 (because this cannot be passed in a structure).
2507 assert((Accum != Memory && Accum != ComplexX87) &&
2508 "Invalid accumulated classification during merge.");
2509 if (Accum == Field || Field == NoClass)
2510 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002511 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002512 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002513 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002514 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002515 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002516 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002517 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2518 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002519 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002520 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002521}
2522
Chris Lattner5c740f12010-06-30 19:14:05 +00002523void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002524 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002525 // FIXME: This code can be simplified by introducing a simple value class for
2526 // Class pairs with appropriate constructor methods for the various
2527 // situations.
2528
2529 // FIXME: Some of the split computations are wrong; unaligned vectors
2530 // shouldn't be passed in registers for example, so there is no chance they
2531 // can straddle an eightbyte. Verify & simplify.
2532
2533 Lo = Hi = NoClass;
2534
2535 Class &Current = OffsetBase < 64 ? Lo : Hi;
2536 Current = Memory;
2537
John McCall9dd450b2009-09-21 23:43:11 +00002538 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002539 BuiltinType::Kind k = BT->getKind();
2540
2541 if (k == BuiltinType::Void) {
2542 Current = NoClass;
2543 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2544 Lo = Integer;
2545 Hi = Integer;
2546 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2547 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002548 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002549 Current = SSE;
2550 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002551 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002552 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002553 Lo = SSE;
2554 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002555 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002556 Lo = X87;
2557 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002558 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002559 Current = SSE;
2560 } else
2561 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002562 }
2563 // FIXME: _Decimal32 and _Decimal64 are SSE.
2564 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002565 return;
2566 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002567
Chris Lattnerd776fb12010-06-28 21:43:59 +00002568 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002569 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002570 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002571 return;
2572 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002573
Chris Lattnerd776fb12010-06-28 21:43:59 +00002574 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002575 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002576 return;
2577 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002578
Chris Lattnerd776fb12010-06-28 21:43:59 +00002579 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002580 if (Ty->isMemberFunctionPointerType()) {
2581 if (Has64BitPointers) {
2582 // If Has64BitPointers, this is an {i64, i64}, so classify both
2583 // Lo and Hi now.
2584 Lo = Hi = Integer;
2585 } else {
2586 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2587 // straddles an eightbyte boundary, Hi should be classified as well.
2588 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2589 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2590 if (EB_FuncPtr != EB_ThisAdj) {
2591 Lo = Hi = Integer;
2592 } else {
2593 Current = Integer;
2594 }
2595 }
2596 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002597 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002598 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002599 return;
2600 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002601
Chris Lattnerd776fb12010-06-28 21:43:59 +00002602 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002603 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002604 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2605 // gcc passes the following as integer:
2606 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2607 // 2 bytes - <2 x char>, <1 x short>
2608 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002609 Current = Integer;
2610
2611 // If this type crosses an eightbyte boundary, it should be
2612 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002613 uint64_t EB_Lo = (OffsetBase) / 64;
2614 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2615 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 Hi = Lo;
2617 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002618 QualType ElementType = VT->getElementType();
2619
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002621 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 return;
2623
David Majnemere2ae2282016-03-04 05:26:16 +00002624 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2625 // pass them as integer. For platforms where clang is the de facto
2626 // platform compiler, we must continue to use integer.
2627 if (!classifyIntegerMMXAsSSE() &&
2628 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2629 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2630 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2631 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002632 Current = Integer;
2633 else
2634 Current = SSE;
2635
2636 // If this type crosses an eightbyte boundary, it should be
2637 // split.
2638 if (OffsetBase && OffsetBase != 64)
2639 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002640 } else if (Size == 128 ||
2641 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002642 // Arguments of 256-bits are split into four eightbyte chunks. The
2643 // least significant one belongs to class SSE and all the others to class
2644 // SSEUP. The original Lo and Hi design considers that types can't be
2645 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2646 // This design isn't correct for 256-bits, but since there're no cases
2647 // where the upper parts would need to be inspected, avoid adding
2648 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002649 //
2650 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2651 // registers if they are "named", i.e. not part of the "..." of a
2652 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002653 //
2654 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2655 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002656 Lo = SSE;
2657 Hi = SSEUp;
2658 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002659 return;
2660 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002661
Chris Lattnerd776fb12010-06-28 21:43:59 +00002662 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002663 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002664
Chris Lattner2b037972010-07-29 02:01:43 +00002665 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002666 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002667 if (Size <= 64)
2668 Current = Integer;
2669 else if (Size <= 128)
2670 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002671 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002672 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002673 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002675 } else if (ET == getContext().LongDoubleTy) {
2676 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002677 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002678 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002679 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002680 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002681 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002682 Lo = Hi = SSE;
2683 else
2684 llvm_unreachable("unexpected long double representation!");
2685 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002686
2687 // If this complex type crosses an eightbyte boundary then it
2688 // should be split.
2689 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002690 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002691 if (Hi == NoClass && EB_Real != EB_Imag)
2692 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002693
Chris Lattnerd776fb12010-06-28 21:43:59 +00002694 return;
2695 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002696
Chris Lattner2b037972010-07-29 02:01:43 +00002697 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698 // Arrays are treated like structures.
2699
Chris Lattner2b037972010-07-29 02:01:43 +00002700 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002701
2702 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002703 // than eight eightbytes, ..., it has class MEMORY.
2704 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002705 return;
2706
2707 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2708 // fields, it has class MEMORY.
2709 //
2710 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002711 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002712 return;
2713
2714 // Otherwise implement simplified merge. We could be smarter about
2715 // this, but it isn't worth it and would be harder to verify.
2716 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002717 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002718 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002719
2720 // The only case a 256-bit wide vector could be used is when the array
2721 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2722 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002723 //
2724 if (Size > 128 &&
2725 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002726 return;
2727
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002728 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2729 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002730 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002731 Lo = merge(Lo, FieldLo);
2732 Hi = merge(Hi, FieldHi);
2733 if (Lo == Memory || Hi == Memory)
2734 break;
2735 }
2736
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002737 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002739 return;
2740 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002741
Chris Lattnerd776fb12010-06-28 21:43:59 +00002742 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002743 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744
2745 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002746 // than eight eightbytes, ..., it has class MEMORY.
2747 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002748 return;
2749
Anders Carlsson20759ad2009-09-16 15:53:40 +00002750 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2751 // copy constructor or a non-trivial destructor, it is passed by invisible
2752 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002753 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002754 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002755
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002756 const RecordDecl *RD = RT->getDecl();
2757
2758 // Assume variable sized types are passed in memory.
2759 if (RD->hasFlexibleArrayMember())
2760 return;
2761
Chris Lattner2b037972010-07-29 02:01:43 +00002762 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002763
2764 // Reset Lo class, this will be recomputed.
2765 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002766
2767 // If this is a C++ record, classify the bases first.
2768 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002769 for (const auto &I : CXXRD->bases()) {
2770 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002771 "Unexpected base class!");
2772 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002773 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002774
2775 // Classify this field.
2776 //
2777 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2778 // single eightbyte, each is classified separately. Each eightbyte gets
2779 // initialized to class NO_CLASS.
2780 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002781 uint64_t Offset =
2782 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002783 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002784 Lo = merge(Lo, FieldLo);
2785 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002786 if (Lo == Memory || Hi == Memory) {
2787 postMerge(Size, Lo, Hi);
2788 return;
2789 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002790 }
2791 }
2792
2793 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002795 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002796 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002797 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2798 bool BitField = i->isBitField();
2799
David Majnemerb439dfe2016-08-15 07:20:40 +00002800 // Ignore padding bit-fields.
2801 if (BitField && i->isUnnamedBitfield())
2802 continue;
2803
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002804 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2805 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002806 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002807 // The only case a 256-bit wide vector could be used is when the struct
2808 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2809 // to work for sizes wider than 128, early check and fallback to memory.
2810 //
David Majnemerb229cb02016-08-15 06:39:18 +00002811 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2812 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002813 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002814 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002815 return;
2816 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002817 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002818 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002819 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002820 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002821 return;
2822 }
2823
2824 // Classify this field.
2825 //
2826 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2827 // exceeds a single eightbyte, each is classified
2828 // separately. Each eightbyte gets initialized to class
2829 // NO_CLASS.
2830 Class FieldLo, FieldHi;
2831
2832 // Bit-fields require special handling, they do not force the
2833 // structure to be passed in memory even if unaligned, and
2834 // therefore they can straddle an eightbyte.
2835 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002836 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002837 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002838 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002839
2840 uint64_t EB_Lo = Offset / 64;
2841 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002842
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002843 if (EB_Lo) {
2844 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2845 FieldLo = NoClass;
2846 FieldHi = Integer;
2847 } else {
2848 FieldLo = Integer;
2849 FieldHi = EB_Hi ? Integer : NoClass;
2850 }
2851 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002852 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002853 Lo = merge(Lo, FieldLo);
2854 Hi = merge(Hi, FieldHi);
2855 if (Lo == Memory || Hi == Memory)
2856 break;
2857 }
2858
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002859 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002860 }
2861}
2862
Chris Lattner22a931e2010-06-29 06:01:59 +00002863ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002864 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2865 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002866 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002867 // Treat an enum type as its underlying type.
2868 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2869 Ty = EnumTy->getDecl()->getIntegerType();
2870
2871 return (Ty->isPromotableIntegerType() ?
2872 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2873 }
2874
John McCall7f416cc2015-09-08 08:05:57 +00002875 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002876}
2877
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002878bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2879 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2880 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002881 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002882 if (Size <= 64 || Size > LargestVector)
2883 return true;
2884 }
2885
2886 return false;
2887}
2888
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002889ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2890 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002891 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2892 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002893 //
2894 // This assumption is optimistic, as there could be free registers available
2895 // when we need to pass this argument in memory, and LLVM could try to pass
2896 // the argument in the free register. This does not seem to happen currently,
2897 // but this code would be much safer if we could mark the argument with
2898 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002899 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002900 // Treat an enum type as its underlying type.
2901 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2902 Ty = EnumTy->getDecl()->getIntegerType();
2903
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002904 return (Ty->isPromotableIntegerType() ?
2905 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002906 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907
Mark Lacey3825e832013-10-06 01:33:34 +00002908 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002909 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002910
Chris Lattner44c2b902011-05-22 23:21:23 +00002911 // Compute the byval alignment. We specify the alignment of the byval in all
2912 // cases so that the mid-level optimizer knows the alignment of the byval.
2913 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002914
2915 // Attempt to avoid passing indirect results using byval when possible. This
2916 // is important for good codegen.
2917 //
2918 // We do this by coercing the value into a scalar type which the backend can
2919 // handle naturally (i.e., without using byval).
2920 //
2921 // For simplicity, we currently only do this when we have exhausted all of the
2922 // free integer registers. Doing this when there are free integer registers
2923 // would require more care, as we would have to ensure that the coerced value
2924 // did not claim the unused register. That would require either reording the
2925 // arguments to the function (so that any subsequent inreg values came first),
2926 // or only doing this optimization when there were no following arguments that
2927 // might be inreg.
2928 //
2929 // We currently expect it to be rare (particularly in well written code) for
2930 // arguments to be passed on the stack when there are still free integer
2931 // registers available (this would typically imply large structs being passed
2932 // by value), so this seems like a fair tradeoff for now.
2933 //
2934 // We can revisit this if the backend grows support for 'onstack' parameter
2935 // attributes. See PR12193.
2936 if (freeIntRegs == 0) {
2937 uint64_t Size = getContext().getTypeSize(Ty);
2938
2939 // If this type fits in an eightbyte, coerce it into the matching integral
2940 // type, which will end up on the stack (with alignment 8).
2941 if (Align == 8 && Size <= 64)
2942 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2943 Size));
2944 }
2945
John McCall7f416cc2015-09-08 08:05:57 +00002946 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002947}
2948
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002949/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2950/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002951llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002952 // Wrapper structs/arrays that only contain vectors are passed just like
2953 // vectors; strip them off if present.
2954 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2955 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002956
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002957 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002958 if (isa<llvm::VectorType>(IRType) ||
2959 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002960 return IRType;
2961
2962 // We couldn't find the preferred IR vector type for 'Ty'.
2963 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002964 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002965
2966 // Return a LLVM IR vector type based on the size of 'Ty'.
2967 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2968 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002969}
2970
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002971/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2972/// is known to either be off the end of the specified type or being in
2973/// alignment padding. The user type specified is known to be at most 128 bits
2974/// in size, and have passed through X86_64ABIInfo::classify with a successful
2975/// classification that put one of the two halves in the INTEGER class.
2976///
2977/// It is conservatively correct to return false.
2978static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2979 unsigned EndBit, ASTContext &Context) {
2980 // If the bytes being queried are off the end of the type, there is no user
2981 // data hiding here. This handles analysis of builtins, vectors and other
2982 // types that don't contain interesting padding.
2983 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2984 if (TySize <= StartBit)
2985 return true;
2986
Chris Lattner98076a22010-07-29 07:43:55 +00002987 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2988 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2989 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2990
2991 // Check each element to see if the element overlaps with the queried range.
2992 for (unsigned i = 0; i != NumElts; ++i) {
2993 // If the element is after the span we care about, then we're done..
2994 unsigned EltOffset = i*EltSize;
2995 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002996
Chris Lattner98076a22010-07-29 07:43:55 +00002997 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2998 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2999 EndBit-EltOffset, Context))
3000 return false;
3001 }
3002 // If it overlaps no elements, then it is safe to process as padding.
3003 return true;
3004 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003005
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003006 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3007 const RecordDecl *RD = RT->getDecl();
3008 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003009
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003010 // If this is a C++ record, check the bases first.
3011 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003012 for (const auto &I : CXXRD->bases()) {
3013 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003014 "Unexpected base class!");
3015 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003016 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003017
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003018 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003019 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003020 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003021
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003022 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003023 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003024 EndBit-BaseOffset, Context))
3025 return false;
3026 }
3027 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003028
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003029 // Verify that no field has data that overlaps the region of interest. Yes
3030 // this could be sped up a lot by being smarter about queried fields,
3031 // however we're only looking at structs up to 16 bytes, so we don't care
3032 // much.
3033 unsigned idx = 0;
3034 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3035 i != e; ++i, ++idx) {
3036 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003037
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003038 // If we found a field after the region we care about, then we're done.
3039 if (FieldOffset >= EndBit) break;
3040
3041 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3042 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3043 Context))
3044 return false;
3045 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003046
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003047 // If nothing in this record overlapped the area of interest, then we're
3048 // clean.
3049 return true;
3050 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003051
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003052 return false;
3053}
3054
Chris Lattnere556a712010-07-29 18:39:32 +00003055/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3056/// float member at the specified offset. For example, {int,{float}} has a
3057/// float at offset 4. It is conservatively correct for this routine to return
3058/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003059static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003060 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003061 // Base case if we find a float.
3062 if (IROffset == 0 && IRType->isFloatTy())
3063 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003064
Chris Lattnere556a712010-07-29 18:39:32 +00003065 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003066 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003067 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3068 unsigned Elt = SL->getElementContainingOffset(IROffset);
3069 IROffset -= SL->getElementOffset(Elt);
3070 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3071 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003072
Chris Lattnere556a712010-07-29 18:39:32 +00003073 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003074 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3075 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003076 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3077 IROffset -= IROffset/EltSize*EltSize;
3078 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3079 }
3080
3081 return false;
3082}
3083
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003084
3085/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3086/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003087llvm::Type *X86_64ABIInfo::
3088GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003089 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003090 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003091 // pass as float if the last 4 bytes is just padding. This happens for
3092 // structs that contain 3 floats.
3093 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3094 SourceOffset*8+64, getContext()))
3095 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003096
Chris Lattnere556a712010-07-29 18:39:32 +00003097 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3098 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3099 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003100 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3101 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003102 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003103
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003104 return llvm::Type::getDoubleTy(getVMContext());
3105}
3106
3107
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003108/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3109/// an 8-byte GPR. This means that we either have a scalar or we are talking
3110/// about the high or low part of an up-to-16-byte struct. This routine picks
3111/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003112/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3113/// etc).
3114///
3115/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3116/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3117/// the 8-byte value references. PrefType may be null.
3118///
Alp Toker9907f082014-07-09 14:06:35 +00003119/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003120/// an offset into this that we're processing (which is always either 0 or 8).
3121///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003122llvm::Type *X86_64ABIInfo::
3123GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003124 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003125 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3126 // returning an 8-byte unit starting with it. See if we can safely use it.
3127 if (IROffset == 0) {
3128 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003129 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3130 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003131 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003132
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003133 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3134 // goodness in the source type is just tail padding. This is allowed to
3135 // kick in for struct {double,int} on the int, but not on
3136 // struct{double,int,int} because we wouldn't return the second int. We
3137 // have to do this analysis on the source type because we can't depend on
3138 // unions being lowered a specific way etc.
3139 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003140 IRType->isIntegerTy(32) ||
3141 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3142 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3143 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003144
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003145 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3146 SourceOffset*8+64, getContext()))
3147 return IRType;
3148 }
3149 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003150
Chris Lattner2192fe52011-07-18 04:24:23 +00003151 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003152 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003153 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003154 if (IROffset < SL->getSizeInBytes()) {
3155 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3156 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003157
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003158 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3159 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003160 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003161 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003162
Chris Lattner2192fe52011-07-18 04:24:23 +00003163 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003164 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003165 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003166 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003167 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3168 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003169 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003170
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003171 // Okay, we don't have any better idea of what to pass, so we pass this in an
3172 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003173 unsigned TySizeInBytes =
3174 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003175
Chris Lattner3f763422010-07-29 17:34:39 +00003176 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003177
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003178 // It is always safe to classify this as an integer type up to i64 that
3179 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003180 return llvm::IntegerType::get(getVMContext(),
3181 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003182}
3183
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003184
3185/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3186/// be used as elements of a two register pair to pass or return, return a
3187/// first class aggregate to represent them. For example, if the low part of
3188/// a by-value argument should be passed as i32* and the high part as float,
3189/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003190static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003191GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003192 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003193 // In order to correctly satisfy the ABI, we need to the high part to start
3194 // at offset 8. If the high and low parts we inferred are both 4-byte types
3195 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3196 // the second element at offset 8. Check for this:
3197 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3198 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003199 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003200 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003201
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003202 // To handle this, we have to increase the size of the low part so that the
3203 // second element will start at an 8 byte offset. We can't increase the size
3204 // of the second element because it might make us access off the end of the
3205 // struct.
3206 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003207 // There are usually two sorts of types the ABI generation code can produce
3208 // for the low part of a pair that aren't 8 bytes in size: float or
3209 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3210 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003211 // Promote these to a larger type.
3212 if (Lo->isFloatTy())
3213 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3214 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003215 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3216 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003217 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3218 }
3219 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003220
Serge Guelton1d993272017-05-09 19:31:30 +00003221 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003222
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003223 // Verify that the second element is at an 8-byte offset.
3224 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3225 "Invalid x86-64 argument pair!");
3226 return Result;
3227}
3228
Chris Lattner31faff52010-07-28 23:06:14 +00003229ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003230classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003231 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3232 // classification algorithm.
3233 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003234 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003235
3236 // Check some invariants.
3237 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003238 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3239
Craig Topper8a13c412014-05-21 05:09:00 +00003240 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003241 switch (Lo) {
3242 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003243 if (Hi == NoClass)
3244 return ABIArgInfo::getIgnore();
3245 // If the low part is just padding, it takes no register, leave ResType
3246 // null.
3247 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3248 "Unknown missing lo part");
3249 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003250
3251 case SSEUp:
3252 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003253 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003254
3255 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3256 // hidden argument.
3257 case Memory:
3258 return getIndirectReturnResult(RetTy);
3259
3260 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3261 // available register of the sequence %rax, %rdx is used.
3262 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003263 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003264
Chris Lattner1f3a0632010-07-29 21:42:50 +00003265 // If we have a sign or zero extended integer, make sure to return Extend
3266 // so that the parameter gets the right LLVM IR attributes.
3267 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3268 // Treat an enum type as its underlying type.
3269 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3270 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003271
Chris Lattner1f3a0632010-07-29 21:42:50 +00003272 if (RetTy->isIntegralOrEnumerationType() &&
3273 RetTy->isPromotableIntegerType())
3274 return ABIArgInfo::getExtend();
3275 }
Chris Lattner31faff52010-07-28 23:06:14 +00003276 break;
3277
3278 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3279 // available SSE register of the sequence %xmm0, %xmm1 is used.
3280 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003281 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003282 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003283
3284 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3285 // returned on the X87 stack in %st0 as 80-bit x87 number.
3286 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003287 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003288 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003289
3290 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3291 // part of the value is returned in %st0 and the imaginary part in
3292 // %st1.
3293 case ComplexX87:
3294 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003295 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003296 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003297 break;
3298 }
3299
Craig Topper8a13c412014-05-21 05:09:00 +00003300 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003301 switch (Hi) {
3302 // Memory was handled previously and X87 should
3303 // never occur as a hi class.
3304 case Memory:
3305 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003306 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003307
3308 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003309 case NoClass:
3310 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003311
Chris Lattner52b3c132010-09-01 00:20:33 +00003312 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003313 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003314 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3315 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003316 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003317 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003318 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003319 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3320 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003321 break;
3322
3323 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003324 // is passed in the next available eightbyte chunk if the last used
3325 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003326 //
Chris Lattner57540c52011-04-15 05:22:18 +00003327 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003328 case SSEUp:
3329 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003330 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003331 break;
3332
3333 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3334 // returned together with the previous X87 value in %st0.
3335 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003336 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003337 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003338 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003339 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003340 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003341 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003342 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3343 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003344 }
Chris Lattner31faff52010-07-28 23:06:14 +00003345 break;
3346 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003347
Chris Lattner52b3c132010-09-01 00:20:33 +00003348 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003349 // known to pass in the high eightbyte of the result. We do this by forming a
3350 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003351 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003352 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003353
Chris Lattner1f3a0632010-07-29 21:42:50 +00003354 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003355}
3356
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003357ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003358 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3359 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003360 const
3361{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003362 Ty = useFirstFieldIfTransparentUnion(Ty);
3363
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003364 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003365 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003366
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003367 // Check some invariants.
3368 // FIXME: Enforce these by construction.
3369 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003370 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3371
3372 neededInt = 0;
3373 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003374 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003375 switch (Lo) {
3376 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003377 if (Hi == NoClass)
3378 return ABIArgInfo::getIgnore();
3379 // If the low part is just padding, it takes no register, leave ResType
3380 // null.
3381 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3382 "Unknown missing lo part");
3383 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003384
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003385 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3386 // on the stack.
3387 case Memory:
3388
3389 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3390 // COMPLEX_X87, it is passed in memory.
3391 case X87:
3392 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003393 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003394 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003395 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003396
3397 case SSEUp:
3398 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003399 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003400
3401 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3402 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3403 // and %r9 is used.
3404 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003405 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003406
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003407 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003408 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003409
3410 // If we have a sign or zero extended integer, make sure to return Extend
3411 // so that the parameter gets the right LLVM IR attributes.
3412 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3413 // Treat an enum type as its underlying type.
3414 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3415 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003416
Chris Lattner1f3a0632010-07-29 21:42:50 +00003417 if (Ty->isIntegralOrEnumerationType() &&
3418 Ty->isPromotableIntegerType())
3419 return ABIArgInfo::getExtend();
3420 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003421
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003422 break;
3423
3424 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3425 // available SSE register is used, the registers are taken in the
3426 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003427 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003428 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003429 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003430 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003431 break;
3432 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003433 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003434
Craig Topper8a13c412014-05-21 05:09:00 +00003435 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003436 switch (Hi) {
3437 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003438 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003439 // which is passed in memory.
3440 case Memory:
3441 case X87:
3442 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003443 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003444
3445 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003446
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003447 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003448 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003449 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003450 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003451
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003452 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3453 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003454 break;
3455
3456 // X87Up generally doesn't occur here (long double is passed in
3457 // memory), except in situations involving unions.
3458 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003459 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003460 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003461
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003462 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3463 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003464
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003465 ++neededSSE;
3466 break;
3467
3468 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3469 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003470 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003471 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003472 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003473 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003474 break;
3475 }
3476
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003477 // If a high part was specified, merge it together with the low part. It is
3478 // known to pass in the high eightbyte of the result. We do this by forming a
3479 // first class struct aggregate with the high and low part: {low, high}
3480 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003481 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003482
Chris Lattner1f3a0632010-07-29 21:42:50 +00003483 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003484}
3485
Erich Keane757d3172016-11-02 18:29:35 +00003486ABIArgInfo
3487X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3488 unsigned &NeededSSE) const {
3489 auto RT = Ty->getAs<RecordType>();
3490 assert(RT && "classifyRegCallStructType only valid with struct types");
3491
3492 if (RT->getDecl()->hasFlexibleArrayMember())
3493 return getIndirectReturnResult(Ty);
3494
3495 // Sum up bases
3496 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3497 if (CXXRD->isDynamicClass()) {
3498 NeededInt = NeededSSE = 0;
3499 return getIndirectReturnResult(Ty);
3500 }
3501
3502 for (const auto &I : CXXRD->bases())
3503 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3504 .isIndirect()) {
3505 NeededInt = NeededSSE = 0;
3506 return getIndirectReturnResult(Ty);
3507 }
3508 }
3509
3510 // Sum up members
3511 for (const auto *FD : RT->getDecl()->fields()) {
3512 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3513 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3514 .isIndirect()) {
3515 NeededInt = NeededSSE = 0;
3516 return getIndirectReturnResult(Ty);
3517 }
3518 } else {
3519 unsigned LocalNeededInt, LocalNeededSSE;
3520 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3521 LocalNeededSSE, true)
3522 .isIndirect()) {
3523 NeededInt = NeededSSE = 0;
3524 return getIndirectReturnResult(Ty);
3525 }
3526 NeededInt += LocalNeededInt;
3527 NeededSSE += LocalNeededSSE;
3528 }
3529 }
3530
3531 return ABIArgInfo::getDirect();
3532}
3533
3534ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3535 unsigned &NeededInt,
3536 unsigned &NeededSSE) const {
3537
3538 NeededInt = 0;
3539 NeededSSE = 0;
3540
3541 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3542}
3543
Chris Lattner22326a12010-07-29 02:31:05 +00003544void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003545
Erich Keane757d3172016-11-02 18:29:35 +00003546 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003547
3548 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003549 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3550 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3551 unsigned NeededInt, NeededSSE;
3552
Erich Keanede1b2a92017-07-21 18:50:36 +00003553 if (!getCXXABI().classifyReturnType(FI)) {
3554 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3555 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3556 FI.getReturnInfo() =
3557 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3558 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3559 FreeIntRegs -= NeededInt;
3560 FreeSSERegs -= NeededSSE;
3561 } else {
3562 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3563 }
3564 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3565 // Complex Long Double Type is passed in Memory when Regcall
3566 // calling convention is used.
3567 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3568 if (getContext().getCanonicalType(CT->getElementType()) ==
3569 getContext().LongDoubleTy)
3570 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3571 } else
3572 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3573 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003574
3575 // If the return value is indirect, then the hidden argument is consuming one
3576 // integer register.
3577 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003578 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003579
Peter Collingbournef7706832014-12-12 23:41:25 +00003580 // The chain argument effectively gives us another free register.
3581 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003582 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003583
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003584 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003585 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3586 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003587 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003588 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003589 it != ie; ++it, ++ArgNo) {
3590 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003591
Erich Keane757d3172016-11-02 18:29:35 +00003592 if (IsRegCall && it->type->isStructureOrClassType())
3593 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3594 else
3595 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3596 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003597
3598 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3599 // eightbyte of an argument, the whole argument is passed on the
3600 // stack. If registers have already been assigned for some
3601 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003602 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3603 FreeIntRegs -= NeededInt;
3604 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003605 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003606 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003607 }
3608 }
3609}
3610
John McCall7f416cc2015-09-08 08:05:57 +00003611static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3612 Address VAListAddr, QualType Ty) {
3613 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3614 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003615 llvm::Value *overflow_arg_area =
3616 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3617
3618 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3619 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003620 // It isn't stated explicitly in the standard, but in practice we use
3621 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003622 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3623 if (Align > CharUnits::fromQuantity(8)) {
3624 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3625 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003626 }
3627
3628 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003629 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003630 llvm::Value *Res =
3631 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003632 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003633
3634 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3635 // l->overflow_arg_area + sizeof(type).
3636 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3637 // an 8 byte boundary.
3638
3639 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003640 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003641 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003642 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3643 "overflow_arg_area.next");
3644 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3645
3646 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003647 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003648}
3649
John McCall7f416cc2015-09-08 08:05:57 +00003650Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3651 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003652 // Assume that va_list type is correct; should be pointer to LLVM type:
3653 // struct {
3654 // i32 gp_offset;
3655 // i32 fp_offset;
3656 // i8* overflow_arg_area;
3657 // i8* reg_save_area;
3658 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003659 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003660
John McCall7f416cc2015-09-08 08:05:57 +00003661 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003662 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003663 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003664
3665 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3666 // in the registers. If not go to step 7.
3667 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003668 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003669
3670 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3671 // general purpose registers needed to pass type and num_fp to hold
3672 // the number of floating point registers needed.
3673
3674 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3675 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3676 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3677 //
3678 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3679 // register save space).
3680
Craig Topper8a13c412014-05-21 05:09:00 +00003681 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003682 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3683 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003684 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003685 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003686 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3687 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003688 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003689 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3690 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003691 }
3692
3693 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003694 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003695 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3696 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003697 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3698 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003699 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3700 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003701 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3702 }
3703
3704 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3705 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3706 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3707 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3708
3709 // Emit code to load the value if it was passed in registers.
3710
3711 CGF.EmitBlock(InRegBlock);
3712
3713 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3714 // an offset of l->gp_offset and/or l->fp_offset. This may require
3715 // copying to a temporary location in case the parameter is passed
3716 // in different register classes or requires an alignment greater
3717 // than 8 for general purpose registers and 16 for XMM registers.
3718 //
3719 // FIXME: This really results in shameful code when we end up needing to
3720 // collect arguments from different places; often what should result in a
3721 // simple assembling of a structure from scattered addresses has many more
3722 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003723 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003724 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3725 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3726 "reg_save_area");
3727
3728 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003729 if (neededInt && neededSSE) {
3730 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003731 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003732 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003733 Address Tmp = CGF.CreateMemTemp(Ty);
3734 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003735 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003736 llvm::Type *TyLo = ST->getElementType(0);
3737 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003738 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003739 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003740 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3741 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003742 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3743 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003744 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3745 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003746
John McCall7f416cc2015-09-08 08:05:57 +00003747 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003748 // FIXME: Our choice of alignment here and below is probably pessimistic.
3749 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3750 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3751 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003752 CGF.Builder.CreateStore(V,
3753 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3754
3755 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003756 V = CGF.Builder.CreateAlignedLoad(
3757 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3758 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003759 CharUnits Offset = CharUnits::fromQuantity(
3760 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3761 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3762
3763 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003764 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003765 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3766 CharUnits::fromQuantity(8));
3767 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003768
3769 // Copy to a temporary if necessary to ensure the appropriate alignment.
3770 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003771 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003772 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003773 CharUnits TyAlign = SizeAlign.second;
3774
3775 // Copy into a temporary if the type is more aligned than the
3776 // register save area.
3777 if (TyAlign.getQuantity() > 8) {
3778 Address Tmp = CGF.CreateMemTemp(Ty);
3779 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003780 RegAddr = Tmp;
3781 }
John McCall7f416cc2015-09-08 08:05:57 +00003782
Chris Lattner0cf24192010-06-28 20:05:43 +00003783 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003784 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3785 CharUnits::fromQuantity(16));
3786 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003787 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003788 assert(neededSSE == 2 && "Invalid number of needed registers!");
3789 // SSE registers are spaced 16 bytes apart in the register save
3790 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003791 // The ABI isn't explicit about this, but it seems reasonable
3792 // to assume that the slots are 16-byte aligned, since the stack is
3793 // naturally 16-byte aligned and the prologue is expected to store
3794 // all the SSE registers to the RSA.
3795 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3796 CharUnits::fromQuantity(16));
3797 Address RegAddrHi =
3798 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3799 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003800 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003801 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003802 llvm::Value *V;
3803 Address Tmp = CGF.CreateMemTemp(Ty);
3804 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3805 V = CGF.Builder.CreateLoad(
3806 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3807 CGF.Builder.CreateStore(V,
3808 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3809 V = CGF.Builder.CreateLoad(
3810 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3811 CGF.Builder.CreateStore(V,
3812 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3813
3814 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003815 }
3816
3817 // AMD64-ABI 3.5.7p5: Step 5. Set:
3818 // l->gp_offset = l->gp_offset + num_gp * 8
3819 // l->fp_offset = l->fp_offset + num_fp * 16.
3820 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003821 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003822 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3823 gp_offset_p);
3824 }
3825 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003826 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003827 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3828 fp_offset_p);
3829 }
3830 CGF.EmitBranch(ContBlock);
3831
3832 // Emit code to load the value if it was passed in memory.
3833
3834 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003835 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003836
3837 // Return the appropriate result.
3838
3839 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003840 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3841 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003842 return ResAddr;
3843}
3844
Charles Davisc7d5c942015-09-17 20:55:33 +00003845Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3846 QualType Ty) const {
3847 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3848 CGF.getContext().getTypeInfoInChars(Ty),
3849 CharUnits::fromQuantity(8),
3850 /*allowHigherAlign*/ false);
3851}
3852
Erich Keane521ed962017-01-05 00:20:51 +00003853ABIArgInfo
3854WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3855 const ABIArgInfo &current) const {
3856 // Assumes vectorCall calling convention.
3857 const Type *Base = nullptr;
3858 uint64_t NumElts = 0;
3859
3860 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3861 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3862 FreeSSERegs -= NumElts;
3863 return getDirectX86Hva();
3864 }
3865 return current;
3866}
3867
Reid Kleckner80944df2014-10-31 22:00:51 +00003868ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003869 bool IsReturnType, bool IsVectorCall,
3870 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003871
3872 if (Ty->isVoidType())
3873 return ABIArgInfo::getIgnore();
3874
3875 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3876 Ty = EnumTy->getDecl()->getIntegerType();
3877
Reid Kleckner80944df2014-10-31 22:00:51 +00003878 TypeInfo Info = getContext().getTypeInfo(Ty);
3879 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003880 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003881
Reid Kleckner9005f412014-05-02 00:51:20 +00003882 const RecordType *RT = Ty->getAs<RecordType>();
3883 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003884 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003885 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003886 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003887 }
3888
3889 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003890 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003891
Reid Kleckner9005f412014-05-02 00:51:20 +00003892 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003893
Reid Kleckner80944df2014-10-31 22:00:51 +00003894 const Type *Base = nullptr;
3895 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003896 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3897 // other targets.
3898 if ((IsVectorCall || IsRegCall) &&
3899 isHomogeneousAggregate(Ty, Base, NumElts)) {
3900 if (IsRegCall) {
3901 if (FreeSSERegs >= NumElts) {
3902 FreeSSERegs -= NumElts;
3903 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3904 return ABIArgInfo::getDirect();
3905 return ABIArgInfo::getExpand();
3906 }
3907 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3908 } else if (IsVectorCall) {
3909 if (FreeSSERegs >= NumElts &&
3910 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3911 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003912 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003913 } else if (IsReturnType) {
3914 return ABIArgInfo::getExpand();
3915 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3916 // HVAs are delayed and reclassified in the 2nd step.
3917 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3918 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003919 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003920 }
3921
Reid Klecknerec87fec2014-05-02 01:17:12 +00003922 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003923 // If the member pointer is represented by an LLVM int or ptr, pass it
3924 // directly.
3925 llvm::Type *LLTy = CGT.ConvertType(Ty);
3926 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3927 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003928 }
3929
Michael Kuperstein4f818702015-02-24 09:35:58 +00003930 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003931 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3932 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003933 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003934 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003935
Reid Kleckner9005f412014-05-02 00:51:20 +00003936 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003937 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003938 }
3939
Julien Lerouge10dcff82014-08-27 00:36:55 +00003940 // Bool type is always extended to the ABI, other builtin types are not
3941 // extended.
3942 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3943 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003944 return ABIArgInfo::getExtend();
3945
Reid Kleckner11a17192015-10-28 22:29:52 +00003946 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3947 // passes them indirectly through memory.
3948 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3949 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003950 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003951 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3952 }
3953
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003954 return ABIArgInfo::getDirect();
3955}
3956
Erich Keane521ed962017-01-05 00:20:51 +00003957void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3958 unsigned FreeSSERegs,
3959 bool IsVectorCall,
3960 bool IsRegCall) const {
3961 unsigned Count = 0;
3962 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003963 // Vectorcall in x64 only permits the first 6 arguments to be passed
3964 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003965 if (Count < VectorcallMaxParamNumAsReg)
3966 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3967 else {
3968 // Since these cannot be passed in registers, pretend no registers
3969 // are left.
3970 unsigned ZeroSSERegsAvail = 0;
3971 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3972 IsVectorCall, IsRegCall);
3973 }
3974 ++Count;
3975 }
3976
Erich Keane521ed962017-01-05 00:20:51 +00003977 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003978 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003979 }
3980}
3981
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003982void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003983 bool IsVectorCall =
3984 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003985 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003986
Erich Keane757d3172016-11-02 18:29:35 +00003987 unsigned FreeSSERegs = 0;
3988 if (IsVectorCall) {
3989 // We can use up to 4 SSE return registers with vectorcall.
3990 FreeSSERegs = 4;
3991 } else if (IsRegCall) {
3992 // RegCall gives us 16 SSE registers.
3993 FreeSSERegs = 16;
3994 }
3995
Reid Kleckner80944df2014-10-31 22:00:51 +00003996 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003997 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3998 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003999
Erich Keane757d3172016-11-02 18:29:35 +00004000 if (IsVectorCall) {
4001 // We can use up to 6 SSE register parameters with vectorcall.
4002 FreeSSERegs = 6;
4003 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004004 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004005 FreeSSERegs = 16;
4006 }
4007
Erich Keane521ed962017-01-05 00:20:51 +00004008 if (IsVectorCall) {
4009 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4010 } else {
4011 for (auto &I : FI.arguments())
4012 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4013 }
4014
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004015}
4016
John McCall7f416cc2015-09-08 08:05:57 +00004017Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4018 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004019
4020 bool IsIndirect = false;
4021
4022 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4023 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4024 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4025 uint64_t Width = getContext().getTypeSize(Ty);
4026 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4027 }
4028
4029 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004030 CGF.getContext().getTypeInfoInChars(Ty),
4031 CharUnits::fromQuantity(8),
4032 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004033}
Chris Lattner0cf24192010-06-28 20:05:43 +00004034
John McCallea8d8bb2010-03-11 00:10:12 +00004035// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004036namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004037/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4038class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004039bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00004040public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004041 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4042 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004043
John McCall7f416cc2015-09-08 08:05:57 +00004044 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4045 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004046};
4047
4048class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4049public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004050 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4051 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004052
Craig Topper4f12f102014-03-12 06:41:41 +00004053 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004054 // This is recovered from gcc output.
4055 return 1; // r1 is the dedicated stack pointer
4056 }
4057
4058 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004059 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004060};
4061
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004062}
John McCallea8d8bb2010-03-11 00:10:12 +00004063
James Y Knight29b5f082016-02-24 02:59:33 +00004064// TODO: this implementation is now likely redundant with
4065// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004066Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4067 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004068 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004069 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4070 // TODO: Implement this. For now ignore.
4071 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004072 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004073 }
4074
John McCall7f416cc2015-09-08 08:05:57 +00004075 // struct __va_list_tag {
4076 // unsigned char gpr;
4077 // unsigned char fpr;
4078 // unsigned short reserved;
4079 // void *overflow_arg_area;
4080 // void *reg_save_area;
4081 // };
4082
Roman Divacky8a12d842014-11-03 18:32:54 +00004083 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004084 bool isInt =
4085 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004086 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004087
4088 // All aggregates are passed indirectly? That doesn't seem consistent
4089 // with the argument-lowering code.
4090 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004091
4092 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004093
4094 // The calling convention either uses 1-2 GPRs or 1 FPR.
4095 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004096 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004097 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4098 } else {
4099 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004100 }
John McCall7f416cc2015-09-08 08:05:57 +00004101
4102 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4103
4104 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004105 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004106 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4107 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4108 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004109
Eric Christopher7565e0d2015-05-29 23:09:49 +00004110 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004111 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004112
4113 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4114 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4115 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4116
4117 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4118
John McCall7f416cc2015-09-08 08:05:57 +00004119 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4120 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004121
John McCall7f416cc2015-09-08 08:05:57 +00004122 // Case 1: consume registers.
4123 Address RegAddr = Address::invalid();
4124 {
4125 CGF.EmitBlock(UsingRegs);
4126
4127 Address RegSaveAreaPtr =
4128 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4129 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4130 CharUnits::fromQuantity(8));
4131 assert(RegAddr.getElementType() == CGF.Int8Ty);
4132
4133 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004134 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004135 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4136 CharUnits::fromQuantity(32));
4137 }
4138
4139 // Get the address of the saved value by scaling the number of
4140 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004141 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004142 llvm::Value *RegOffset =
4143 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4144 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4145 RegAddr.getPointer(), RegOffset),
4146 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4147 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4148
4149 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004150 NumRegs =
4151 Builder.CreateAdd(NumRegs,
4152 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004153 Builder.CreateStore(NumRegs, NumRegsAddr);
4154
4155 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004156 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004157
John McCall7f416cc2015-09-08 08:05:57 +00004158 // Case 2: consume space in the overflow area.
4159 Address MemAddr = Address::invalid();
4160 {
4161 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004162
Roman Divacky039b9702016-02-20 08:31:24 +00004163 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4164
John McCall7f416cc2015-09-08 08:05:57 +00004165 // Everything in the overflow area is rounded up to a size of at least 4.
4166 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4167
4168 CharUnits Size;
4169 if (!isIndirect) {
4170 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004171 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004172 } else {
4173 Size = CGF.getPointerSize();
4174 }
4175
4176 Address OverflowAreaAddr =
4177 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004178 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004179 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004180 // Round up address of argument to alignment
4181 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4182 if (Align > OverflowAreaAlign) {
4183 llvm::Value *Ptr = OverflowArea.getPointer();
4184 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4185 Align);
4186 }
4187
John McCall7f416cc2015-09-08 08:05:57 +00004188 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4189
4190 // Increase the overflow area.
4191 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4192 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4193 CGF.EmitBranch(Cont);
4194 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004195
4196 CGF.EmitBlock(Cont);
4197
John McCall7f416cc2015-09-08 08:05:57 +00004198 // Merge the cases with a phi.
4199 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4200 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004201
John McCall7f416cc2015-09-08 08:05:57 +00004202 // Load the pointer if the argument was passed indirectly.
4203 if (isIndirect) {
4204 Result = Address(Builder.CreateLoad(Result, "aggr"),
4205 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004206 }
4207
4208 return Result;
4209}
4210
John McCallea8d8bb2010-03-11 00:10:12 +00004211bool
4212PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4213 llvm::Value *Address) const {
4214 // This is calculated from the LLVM and GCC tables and verified
4215 // against gcc output. AFAIK all ABIs use the same encoding.
4216
4217 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004218
Chris Lattnerece04092012-02-07 00:39:47 +00004219 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004220 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4221 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4222 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4223
4224 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004225 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004226
4227 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004228 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004229
4230 // 64-76 are various 4-byte special-purpose registers:
4231 // 64: mq
4232 // 65: lr
4233 // 66: ctr
4234 // 67: ap
4235 // 68-75 cr0-7
4236 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004237 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004238
4239 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004240 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004241
4242 // 109: vrsave
4243 // 110: vscr
4244 // 111: spe_acc
4245 // 112: spefscr
4246 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004247 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004248
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004249 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004250}
4251
Roman Divackyd966e722012-05-09 18:22:46 +00004252// PowerPC-64
4253
4254namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004255/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004256class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004257public:
4258 enum ABIKind {
4259 ELFv1 = 0,
4260 ELFv2
4261 };
4262
4263private:
4264 static const unsigned GPRBits = 64;
4265 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004266 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004267 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004268
4269 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4270 // will be passed in a QPX register.
4271 bool IsQPXVectorTy(const Type *Ty) const {
4272 if (!HasQPX)
4273 return false;
4274
4275 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4276 unsigned NumElements = VT->getNumElements();
4277 if (NumElements == 1)
4278 return false;
4279
4280 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4281 if (getContext().getTypeSize(Ty) <= 256)
4282 return true;
4283 } else if (VT->getElementType()->
4284 isSpecificBuiltinType(BuiltinType::Float)) {
4285 if (getContext().getTypeSize(Ty) <= 128)
4286 return true;
4287 }
4288 }
4289
4290 return false;
4291 }
4292
4293 bool IsQPXVectorTy(QualType Ty) const {
4294 return IsQPXVectorTy(Ty.getTypePtr());
4295 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004296
4297public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004298 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4299 bool SoftFloatABI)
4300 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4301 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004302
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004303 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004304 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004305
4306 ABIArgInfo classifyReturnType(QualType RetTy) const;
4307 ABIArgInfo classifyArgumentType(QualType Ty) const;
4308
Reid Klecknere9f6a712014-10-31 17:10:41 +00004309 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4310 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4311 uint64_t Members) const override;
4312
Bill Schmidt84d37792012-10-12 19:26:17 +00004313 // TODO: We can add more logic to computeInfo to improve performance.
4314 // Example: For aggregate arguments that fit in a register, we could
4315 // use getDirectInReg (as is done below for structs containing a single
4316 // floating-point value) to avoid pushing them to memory on function
4317 // entry. This would require changing the logic in PPCISelLowering
4318 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004319 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004320 if (!getCXXABI().classifyReturnType(FI))
4321 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004322 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004323 // We rely on the default argument classification for the most part.
4324 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004325 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004326 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004327 if (T) {
4328 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004329 if (IsQPXVectorTy(T) ||
4330 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004331 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004332 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004333 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004334 continue;
4335 }
4336 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004337 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004338 }
4339 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004340
John McCall7f416cc2015-09-08 08:05:57 +00004341 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4342 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004343};
4344
4345class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004346
Bill Schmidt25cb3492012-10-03 19:18:57 +00004347public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004348 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004349 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4350 bool SoftFloatABI)
4351 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4352 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004353
Craig Topper4f12f102014-03-12 06:41:41 +00004354 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004355 // This is recovered from gcc output.
4356 return 1; // r1 is the dedicated stack pointer
4357 }
4358
4359 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004360 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004361};
4362
Roman Divackyd966e722012-05-09 18:22:46 +00004363class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4364public:
4365 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4366
Craig Topper4f12f102014-03-12 06:41:41 +00004367 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004368 // This is recovered from gcc output.
4369 return 1; // r1 is the dedicated stack pointer
4370 }
4371
4372 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004373 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004374};
4375
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004376}
Roman Divackyd966e722012-05-09 18:22:46 +00004377
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004378// Return true if the ABI requires Ty to be passed sign- or zero-
4379// extended to 64 bits.
4380bool
4381PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4382 // Treat an enum type as its underlying type.
4383 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4384 Ty = EnumTy->getDecl()->getIntegerType();
4385
4386 // Promotable integer types are required to be promoted by the ABI.
4387 if (Ty->isPromotableIntegerType())
4388 return true;
4389
4390 // In addition to the usual promotable integer types, we also need to
4391 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4392 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4393 switch (BT->getKind()) {
4394 case BuiltinType::Int:
4395 case BuiltinType::UInt:
4396 return true;
4397 default:
4398 break;
4399 }
4400
4401 return false;
4402}
4403
John McCall7f416cc2015-09-08 08:05:57 +00004404/// isAlignedParamType - Determine whether a type requires 16-byte or
4405/// higher alignment in the parameter area. Always returns at least 8.
4406CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004407 // Complex types are passed just like their elements.
4408 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4409 Ty = CTy->getElementType();
4410
4411 // Only vector types of size 16 bytes need alignment (larger types are
4412 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004413 if (IsQPXVectorTy(Ty)) {
4414 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004415 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004416
John McCall7f416cc2015-09-08 08:05:57 +00004417 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004418 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004419 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004420 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004421
4422 // For single-element float/vector structs, we consider the whole type
4423 // to have the same alignment requirements as its single element.
4424 const Type *AlignAsType = nullptr;
4425 const Type *EltType = isSingleElementStruct(Ty, getContext());
4426 if (EltType) {
4427 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004428 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004429 getContext().getTypeSize(EltType) == 128) ||
4430 (BT && BT->isFloatingPoint()))
4431 AlignAsType = EltType;
4432 }
4433
Ulrich Weigandb7122372014-07-21 00:48:09 +00004434 // Likewise for ELFv2 homogeneous aggregates.
4435 const Type *Base = nullptr;
4436 uint64_t Members = 0;
4437 if (!AlignAsType && Kind == ELFv2 &&
4438 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4439 AlignAsType = Base;
4440
Ulrich Weigand581badc2014-07-10 17:20:07 +00004441 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004442 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4443 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004444 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004445
John McCall7f416cc2015-09-08 08:05:57 +00004446 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004447 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004448 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004449 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004450
4451 // Otherwise, we only need alignment for any aggregate type that
4452 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004453 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4454 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004455 return CharUnits::fromQuantity(32);
4456 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004457 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004458
John McCall7f416cc2015-09-08 08:05:57 +00004459 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004460}
4461
Ulrich Weigandb7122372014-07-21 00:48:09 +00004462/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4463/// aggregate. Base is set to the base element type, and Members is set
4464/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004465bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4466 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004467 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4468 uint64_t NElements = AT->getSize().getZExtValue();
4469 if (NElements == 0)
4470 return false;
4471 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4472 return false;
4473 Members *= NElements;
4474 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4475 const RecordDecl *RD = RT->getDecl();
4476 if (RD->hasFlexibleArrayMember())
4477 return false;
4478
4479 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004480
4481 // If this is a C++ record, check the bases first.
4482 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4483 for (const auto &I : CXXRD->bases()) {
4484 // Ignore empty records.
4485 if (isEmptyRecord(getContext(), I.getType(), true))
4486 continue;
4487
4488 uint64_t FldMembers;
4489 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4490 return false;
4491
4492 Members += FldMembers;
4493 }
4494 }
4495
Ulrich Weigandb7122372014-07-21 00:48:09 +00004496 for (const auto *FD : RD->fields()) {
4497 // Ignore (non-zero arrays of) empty records.
4498 QualType FT = FD->getType();
4499 while (const ConstantArrayType *AT =
4500 getContext().getAsConstantArrayType(FT)) {
4501 if (AT->getSize().getZExtValue() == 0)
4502 return false;
4503 FT = AT->getElementType();
4504 }
4505 if (isEmptyRecord(getContext(), FT, true))
4506 continue;
4507
4508 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4509 if (getContext().getLangOpts().CPlusPlus &&
4510 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4511 continue;
4512
4513 uint64_t FldMembers;
4514 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4515 return false;
4516
4517 Members = (RD->isUnion() ?
4518 std::max(Members, FldMembers) : Members + FldMembers);
4519 }
4520
4521 if (!Base)
4522 return false;
4523
4524 // Ensure there is no padding.
4525 if (getContext().getTypeSize(Base) * Members !=
4526 getContext().getTypeSize(Ty))
4527 return false;
4528 } else {
4529 Members = 1;
4530 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4531 Members = 2;
4532 Ty = CT->getElementType();
4533 }
4534
Reid Klecknere9f6a712014-10-31 17:10:41 +00004535 // Most ABIs only support float, double, and some vector type widths.
4536 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004537 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004538
4539 // The base type must be the same for all members. Types that
4540 // agree in both total size and mode (float vs. vector) are
4541 // treated as being equivalent here.
4542 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004543 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004544 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004545 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4546 // so make sure to widen it explicitly.
4547 if (const VectorType *VT = Base->getAs<VectorType>()) {
4548 QualType EltTy = VT->getElementType();
4549 unsigned NumElements =
4550 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4551 Base = getContext()
4552 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4553 .getTypePtr();
4554 }
4555 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004556
4557 if (Base->isVectorType() != TyPtr->isVectorType() ||
4558 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4559 return false;
4560 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004561 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4562}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004563
Reid Klecknere9f6a712014-10-31 17:10:41 +00004564bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4565 // Homogeneous aggregates for ELFv2 must have base types of float,
4566 // double, long double, or 128-bit vectors.
4567 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4568 if (BT->getKind() == BuiltinType::Float ||
4569 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004570 BT->getKind() == BuiltinType::LongDouble) {
4571 if (IsSoftFloatABI)
4572 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004573 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004574 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004575 }
4576 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004577 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004578 return true;
4579 }
4580 return false;
4581}
4582
4583bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4584 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004585 // Vector types require one register, floating point types require one
4586 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004587 uint32_t NumRegs =
4588 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004589
4590 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004591 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004592}
4593
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004594ABIArgInfo
4595PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004596 Ty = useFirstFieldIfTransparentUnion(Ty);
4597
Bill Schmidt90b22c92012-11-27 02:46:43 +00004598 if (Ty->isAnyComplexType())
4599 return ABIArgInfo::getDirect();
4600
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004601 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4602 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004603 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004604 uint64_t Size = getContext().getTypeSize(Ty);
4605 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004606 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004607 else if (Size < 128) {
4608 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4609 return ABIArgInfo::getDirect(CoerceTy);
4610 }
4611 }
4612
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004613 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004614 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004615 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004616
John McCall7f416cc2015-09-08 08:05:57 +00004617 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4618 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004619
4620 // ELFv2 homogeneous aggregates are passed as array types.
4621 const Type *Base = nullptr;
4622 uint64_t Members = 0;
4623 if (Kind == ELFv2 &&
4624 isHomogeneousAggregate(Ty, Base, Members)) {
4625 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4626 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4627 return ABIArgInfo::getDirect(CoerceTy);
4628 }
4629
Ulrich Weigand601957f2014-07-21 00:56:36 +00004630 // If an aggregate may end up fully in registers, we do not
4631 // use the ByVal method, but pass the aggregate as array.
4632 // This is usually beneficial since we avoid forcing the
4633 // back-end to store the argument to memory.
4634 uint64_t Bits = getContext().getTypeSize(Ty);
4635 if (Bits > 0 && Bits <= 8 * GPRBits) {
4636 llvm::Type *CoerceTy;
4637
4638 // Types up to 8 bytes are passed as integer type (which will be
4639 // properly aligned in the argument save area doubleword).
4640 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004641 CoerceTy =
4642 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004643 // Larger types are passed as arrays, with the base type selected
4644 // according to the required alignment in the save area.
4645 else {
4646 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004647 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004648 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4649 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4650 }
4651
4652 return ABIArgInfo::getDirect(CoerceTy);
4653 }
4654
Ulrich Weigandb7122372014-07-21 00:48:09 +00004655 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004656 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4657 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004658 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004659 }
4660
4661 return (isPromotableTypeForABI(Ty) ?
4662 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4663}
4664
4665ABIArgInfo
4666PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4667 if (RetTy->isVoidType())
4668 return ABIArgInfo::getIgnore();
4669
Bill Schmidta3d121c2012-12-17 04:20:17 +00004670 if (RetTy->isAnyComplexType())
4671 return ABIArgInfo::getDirect();
4672
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004673 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4674 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004675 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004676 uint64_t Size = getContext().getTypeSize(RetTy);
4677 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004678 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004679 else if (Size < 128) {
4680 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4681 return ABIArgInfo::getDirect(CoerceTy);
4682 }
4683 }
4684
Ulrich Weigandb7122372014-07-21 00:48:09 +00004685 if (isAggregateTypeForABI(RetTy)) {
4686 // ELFv2 homogeneous aggregates are returned as array types.
4687 const Type *Base = nullptr;
4688 uint64_t Members = 0;
4689 if (Kind == ELFv2 &&
4690 isHomogeneousAggregate(RetTy, Base, Members)) {
4691 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4692 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4693 return ABIArgInfo::getDirect(CoerceTy);
4694 }
4695
4696 // ELFv2 small aggregates are returned in up to two registers.
4697 uint64_t Bits = getContext().getTypeSize(RetTy);
4698 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4699 if (Bits == 0)
4700 return ABIArgInfo::getIgnore();
4701
4702 llvm::Type *CoerceTy;
4703 if (Bits > GPRBits) {
4704 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004705 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004706 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004707 CoerceTy =
4708 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004709 return ABIArgInfo::getDirect(CoerceTy);
4710 }
4711
4712 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004713 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004714 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004715
4716 return (isPromotableTypeForABI(RetTy) ?
4717 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4718}
4719
Bill Schmidt25cb3492012-10-03 19:18:57 +00004720// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004721Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4722 QualType Ty) const {
4723 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4724 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004725
John McCall7f416cc2015-09-08 08:05:57 +00004726 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004727
Bill Schmidt924c4782013-01-14 17:45:36 +00004728 // If we have a complex type and the base type is smaller than 8 bytes,
4729 // the ABI calls for the real and imaginary parts to be right-adjusted
4730 // in separate doublewords. However, Clang expects us to produce a
4731 // pointer to a structure with the two parts packed tightly. So generate
4732 // loads of the real and imaginary parts relative to the va_list pointer,
4733 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004734 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4735 CharUnits EltSize = TypeInfo.first / 2;
4736 if (EltSize < SlotSize) {
4737 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4738 SlotSize * 2, SlotSize,
4739 SlotSize, /*AllowHigher*/ true);
4740
4741 Address RealAddr = Addr;
4742 Address ImagAddr = RealAddr;
4743 if (CGF.CGM.getDataLayout().isBigEndian()) {
4744 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4745 SlotSize - EltSize);
4746 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4747 2 * SlotSize - EltSize);
4748 } else {
4749 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4750 }
4751
4752 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4753 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4754 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4755 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4756 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4757
4758 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4759 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4760 /*init*/ true);
4761 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004762 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004763 }
4764
John McCall7f416cc2015-09-08 08:05:57 +00004765 // Otherwise, just use the general rule.
4766 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4767 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004768}
4769
4770static bool
4771PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4772 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004773 // This is calculated from the LLVM and GCC tables and verified
4774 // against gcc output. AFAIK all ABIs use the same encoding.
4775
4776 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4777
4778 llvm::IntegerType *i8 = CGF.Int8Ty;
4779 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4780 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4781 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4782
4783 // 0-31: r0-31, the 8-byte general-purpose registers
4784 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4785
4786 // 32-63: fp0-31, the 8-byte floating-point registers
4787 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4788
Hal Finkel84832a72016-08-30 02:38:34 +00004789 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004790 // 64: mq
4791 // 65: lr
4792 // 66: ctr
4793 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004794 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4795
4796 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004797 // 68-75 cr0-7
4798 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004799 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004800
4801 // 77-108: v0-31, the 16-byte vector registers
4802 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4803
4804 // 109: vrsave
4805 // 110: vscr
4806 // 111: spe_acc
4807 // 112: spefscr
4808 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004809 // 114: tfhar
4810 // 115: tfiar
4811 // 116: texasr
4812 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004813
4814 return false;
4815}
John McCallea8d8bb2010-03-11 00:10:12 +00004816
Bill Schmidt25cb3492012-10-03 19:18:57 +00004817bool
4818PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4819 CodeGen::CodeGenFunction &CGF,
4820 llvm::Value *Address) const {
4821
4822 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4823}
4824
4825bool
4826PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4827 llvm::Value *Address) const {
4828
4829 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4830}
4831
Chris Lattner0cf24192010-06-28 20:05:43 +00004832//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004833// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004834//===----------------------------------------------------------------------===//
4835
4836namespace {
4837
John McCall12f23522016-04-04 18:33:08 +00004838class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004839public:
4840 enum ABIKind {
4841 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004842 DarwinPCS,
4843 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004844 };
4845
4846private:
4847 ABIKind Kind;
4848
4849public:
John McCall12f23522016-04-04 18:33:08 +00004850 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4851 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004852
4853private:
4854 ABIKind getABIKind() const { return Kind; }
4855 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4856
4857 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004858 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004859 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4860 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4861 uint64_t Members) const override;
4862
Tim Northovera2ee4332014-03-29 15:09:45 +00004863 bool isIllegalVectorType(QualType Ty) const;
4864
David Blaikie1cbb9712014-11-14 19:09:44 +00004865 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004866 if (!getCXXABI().classifyReturnType(FI))
4867 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004868
Tim Northoverb047bfa2014-11-27 21:02:49 +00004869 for (auto &it : FI.arguments())
4870 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004871 }
4872
John McCall7f416cc2015-09-08 08:05:57 +00004873 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4874 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004875
John McCall7f416cc2015-09-08 08:05:57 +00004876 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4877 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004878
John McCall7f416cc2015-09-08 08:05:57 +00004879 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4880 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004881 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4882 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4883 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004884 }
John McCall12f23522016-04-04 18:33:08 +00004885
Martin Storsjo502de222017-07-13 17:59:14 +00004886 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4887 QualType Ty) const override;
4888
John McCall12f23522016-04-04 18:33:08 +00004889 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4890 ArrayRef<llvm::Type*> scalars,
4891 bool asReturnValue) const override {
4892 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4893 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004894 bool isSwiftErrorInRegister() const override {
4895 return true;
4896 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004897
4898 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4899 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004900};
4901
Tim Northover573cbee2014-05-24 12:52:07 +00004902class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004903public:
Tim Northover573cbee2014-05-24 12:52:07 +00004904 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4905 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004906
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004907 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004908 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004909 }
4910
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004911 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4912 return 31;
4913 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004914
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004915 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004916};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004917
4918class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4919public:
4920 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4921 : AArch64TargetCodeGenInfo(CGT, K) {}
4922
4923 void getDependentLibraryOption(llvm::StringRef Lib,
4924 llvm::SmallString<24> &Opt) const override {
4925 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4926 }
4927
4928 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4929 llvm::SmallString<32> &Opt) const override {
4930 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4931 }
4932};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004933}
Tim Northovera2ee4332014-03-29 15:09:45 +00004934
Tim Northoverb047bfa2014-11-27 21:02:49 +00004935ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004936 Ty = useFirstFieldIfTransparentUnion(Ty);
4937
Tim Northovera2ee4332014-03-29 15:09:45 +00004938 // Handle illegal vector types here.
4939 if (isIllegalVectorType(Ty)) {
4940 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004941 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004942 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004943 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4944 return ABIArgInfo::getDirect(ResType);
4945 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004946 if (Size <= 32) {
4947 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004948 return ABIArgInfo::getDirect(ResType);
4949 }
4950 if (Size == 64) {
4951 llvm::Type *ResType =
4952 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004953 return ABIArgInfo::getDirect(ResType);
4954 }
4955 if (Size == 128) {
4956 llvm::Type *ResType =
4957 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004958 return ABIArgInfo::getDirect(ResType);
4959 }
John McCall7f416cc2015-09-08 08:05:57 +00004960 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004961 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004962
4963 if (!isAggregateTypeForABI(Ty)) {
4964 // Treat an enum type as its underlying type.
4965 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4966 Ty = EnumTy->getDecl()->getIntegerType();
4967
Tim Northovera2ee4332014-03-29 15:09:45 +00004968 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4969 ? ABIArgInfo::getExtend()
4970 : ABIArgInfo::getDirect());
4971 }
4972
4973 // Structures with either a non-trivial destructor or a non-trivial
4974 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004975 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004976 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4977 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004978 }
4979
4980 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4981 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00004982 uint64_t Size = getContext().getTypeSize(Ty);
4983 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4984 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004985 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4986 return ABIArgInfo::getIgnore();
4987
Tim Northover23bcad22017-05-05 22:36:06 +00004988 // GNU C mode. The only argument that gets ignored is an empty one with size
4989 // 0.
4990 if (IsEmpty && Size == 0)
4991 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00004992 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4993 }
4994
4995 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004996 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004997 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004998 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004999 return ABIArgInfo::getDirect(
5000 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005001 }
5002
5003 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005004 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005005 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5006 // same size and alignment.
5007 if (getTarget().isRenderScriptTarget()) {
5008 return coerceToIntArray(Ty, getContext(), getVMContext());
5009 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00005010 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005011 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005012
Tim Northovera2ee4332014-03-29 15:09:45 +00005013 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5014 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005015 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005016 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5017 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5018 }
5019 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5020 }
5021
John McCall7f416cc2015-09-08 08:05:57 +00005022 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005023}
5024
Tim Northover573cbee2014-05-24 12:52:07 +00005025ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005026 if (RetTy->isVoidType())
5027 return ABIArgInfo::getIgnore();
5028
5029 // Large vector types should be returned via memory.
5030 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005031 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005032
5033 if (!isAggregateTypeForABI(RetTy)) {
5034 // Treat an enum type as its underlying type.
5035 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5036 RetTy = EnumTy->getDecl()->getIntegerType();
5037
Tim Northover4dab6982014-04-18 13:46:08 +00005038 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5039 ? ABIArgInfo::getExtend()
5040 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005041 }
5042
Tim Northover23bcad22017-05-05 22:36:06 +00005043 uint64_t Size = getContext().getTypeSize(RetTy);
5044 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005045 return ABIArgInfo::getIgnore();
5046
Craig Topper8a13c412014-05-21 05:09:00 +00005047 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005048 uint64_t Members = 0;
5049 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005050 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5051 return ABIArgInfo::getDirect();
5052
5053 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005054 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005055 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5056 // same size and alignment.
5057 if (getTarget().isRenderScriptTarget()) {
5058 return coerceToIntArray(RetTy, getContext(), getVMContext());
5059 }
Pete Cooper635b5092015-04-17 22:16:24 +00005060 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005061 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005062
5063 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5064 // For aggregates with 16-byte alignment, we use i128.
5065 if (Alignment < 128 && Size == 128) {
5066 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5067 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5068 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005069 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5070 }
5071
John McCall7f416cc2015-09-08 08:05:57 +00005072 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005073}
5074
Tim Northover573cbee2014-05-24 12:52:07 +00005075/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5076bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005077 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5078 // Check whether VT is legal.
5079 unsigned NumElements = VT->getNumElements();
5080 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005081 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005082 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005083 return true;
5084 return Size != 64 && (Size != 128 || NumElements == 1);
5085 }
5086 return false;
5087}
5088
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005089bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5090 llvm::Type *eltTy,
5091 unsigned elts) const {
5092 if (!llvm::isPowerOf2_32(elts))
5093 return false;
5094 if (totalSize.getQuantity() != 8 &&
5095 (totalSize.getQuantity() != 16 || elts == 1))
5096 return false;
5097 return true;
5098}
5099
Reid Klecknere9f6a712014-10-31 17:10:41 +00005100bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5101 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5102 // point type or a short-vector type. This is the same as the 32-bit ABI,
5103 // but with the difference that any floating-point type is allowed,
5104 // including __fp16.
5105 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5106 if (BT->isFloatingPoint())
5107 return true;
5108 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5109 unsigned VecSize = getContext().getTypeSize(VT);
5110 if (VecSize == 64 || VecSize == 128)
5111 return true;
5112 }
5113 return false;
5114}
5115
5116bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5117 uint64_t Members) const {
5118 return Members <= 4;
5119}
5120
John McCall7f416cc2015-09-08 08:05:57 +00005121Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005122 QualType Ty,
5123 CodeGenFunction &CGF) const {
5124 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005125 bool IsIndirect = AI.isIndirect();
5126
Tim Northoverb047bfa2014-11-27 21:02:49 +00005127 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5128 if (IsIndirect)
5129 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5130 else if (AI.getCoerceToType())
5131 BaseTy = AI.getCoerceToType();
5132
5133 unsigned NumRegs = 1;
5134 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5135 BaseTy = ArrTy->getElementType();
5136 NumRegs = ArrTy->getNumElements();
5137 }
5138 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5139
Tim Northovera2ee4332014-03-29 15:09:45 +00005140 // The AArch64 va_list type and handling is specified in the Procedure Call
5141 // Standard, section B.4:
5142 //
5143 // struct {
5144 // void *__stack;
5145 // void *__gr_top;
5146 // void *__vr_top;
5147 // int __gr_offs;
5148 // int __vr_offs;
5149 // };
5150
5151 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5152 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5153 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5154 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005155
John McCall7f416cc2015-09-08 08:05:57 +00005156 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5157 CharUnits TyAlign = TyInfo.second;
5158
5159 Address reg_offs_p = Address::invalid();
5160 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005161 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005162 CharUnits reg_top_offset;
5163 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005164 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005165 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005166 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005167 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5168 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005169 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5170 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005171 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005172 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005173 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005174 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005175 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005176 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5177 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005178 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5179 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005180 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005181 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005182 }
5183
5184 //=======================================
5185 // Find out where argument was passed
5186 //=======================================
5187
5188 // If reg_offs >= 0 we're already using the stack for this type of
5189 // argument. We don't want to keep updating reg_offs (in case it overflows,
5190 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5191 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005192 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005193 UsingStack = CGF.Builder.CreateICmpSGE(
5194 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5195
5196 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5197
5198 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005199 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005200 CGF.EmitBlock(MaybeRegBlock);
5201
5202 // Integer arguments may need to correct register alignment (for example a
5203 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5204 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005205 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5206 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005207
5208 reg_offs = CGF.Builder.CreateAdd(
5209 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5210 "align_regoffs");
5211 reg_offs = CGF.Builder.CreateAnd(
5212 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5213 "aligned_regoffs");
5214 }
5215
5216 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005217 // The fact that this is done unconditionally reflects the fact that
5218 // allocating an argument to the stack also uses up all the remaining
5219 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005220 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005221 NewOffset = CGF.Builder.CreateAdd(
5222 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5223 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5224
5225 // Now we're in a position to decide whether this argument really was in
5226 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005227 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005228 InRegs = CGF.Builder.CreateICmpSLE(
5229 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5230
5231 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5232
5233 //=======================================
5234 // Argument was in registers
5235 //=======================================
5236
5237 // Now we emit the code for if the argument was originally passed in
5238 // registers. First start the appropriate block:
5239 CGF.EmitBlock(InRegBlock);
5240
John McCall7f416cc2015-09-08 08:05:57 +00005241 llvm::Value *reg_top = nullptr;
5242 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5243 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005244 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005245 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5246 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5247 Address RegAddr = Address::invalid();
5248 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005249
5250 if (IsIndirect) {
5251 // If it's been passed indirectly (actually a struct), whatever we find from
5252 // stored registers or on the stack will actually be a struct **.
5253 MemTy = llvm::PointerType::getUnqual(MemTy);
5254 }
5255
Craig Topper8a13c412014-05-21 05:09:00 +00005256 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005257 uint64_t NumMembers = 0;
5258 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005259 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005260 // Homogeneous aggregates passed in registers will have their elements split
5261 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5262 // qN+1, ...). We reload and store into a temporary local variable
5263 // contiguously.
5264 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005265 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005266 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5267 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005268 Address Tmp = CGF.CreateTempAlloca(HFATy,
5269 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005270
John McCall7f416cc2015-09-08 08:05:57 +00005271 // On big-endian platforms, the value will be right-aligned in its slot.
5272 int Offset = 0;
5273 if (CGF.CGM.getDataLayout().isBigEndian() &&
5274 BaseTyInfo.first.getQuantity() < 16)
5275 Offset = 16 - BaseTyInfo.first.getQuantity();
5276
Tim Northovera2ee4332014-03-29 15:09:45 +00005277 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005278 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5279 Address LoadAddr =
5280 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5281 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5282
5283 Address StoreAddr =
5284 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005285
5286 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5287 CGF.Builder.CreateStore(Elem, StoreAddr);
5288 }
5289
John McCall7f416cc2015-09-08 08:05:57 +00005290 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005291 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005292 // Otherwise the object is contiguous in memory.
5293
5294 // It might be right-aligned in its slot.
5295 CharUnits SlotSize = BaseAddr.getAlignment();
5296 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005297 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005298 TyInfo.first < SlotSize) {
5299 CharUnits Offset = SlotSize - TyInfo.first;
5300 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005301 }
5302
John McCall7f416cc2015-09-08 08:05:57 +00005303 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005304 }
5305
5306 CGF.EmitBranch(ContBlock);
5307
5308 //=======================================
5309 // Argument was on the stack
5310 //=======================================
5311 CGF.EmitBlock(OnStackBlock);
5312
John McCall7f416cc2015-09-08 08:05:57 +00005313 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5314 CharUnits::Zero(), "stack_p");
5315 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005316
John McCall7f416cc2015-09-08 08:05:57 +00005317 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005318 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005319 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5320 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005321
John McCall7f416cc2015-09-08 08:05:57 +00005322 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005323
John McCall7f416cc2015-09-08 08:05:57 +00005324 OnStackPtr = CGF.Builder.CreateAdd(
5325 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005326 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005327 OnStackPtr = CGF.Builder.CreateAnd(
5328 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005329 "align_stack");
5330
John McCall7f416cc2015-09-08 08:05:57 +00005331 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005332 }
John McCall7f416cc2015-09-08 08:05:57 +00005333 Address OnStackAddr(OnStackPtr,
5334 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005335
John McCall7f416cc2015-09-08 08:05:57 +00005336 // All stack slots are multiples of 8 bytes.
5337 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5338 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005339 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005340 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005341 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005342 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005343
John McCall7f416cc2015-09-08 08:05:57 +00005344 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005345 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005346 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005347
5348 // Write the new value of __stack for the next call to va_arg
5349 CGF.Builder.CreateStore(NewStack, stack_p);
5350
5351 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005352 TyInfo.first < StackSlotSize) {
5353 CharUnits Offset = StackSlotSize - TyInfo.first;
5354 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005355 }
5356
John McCall7f416cc2015-09-08 08:05:57 +00005357 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005358
5359 CGF.EmitBranch(ContBlock);
5360
5361 //=======================================
5362 // Tidy up
5363 //=======================================
5364 CGF.EmitBlock(ContBlock);
5365
John McCall7f416cc2015-09-08 08:05:57 +00005366 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5367 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005368
5369 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005370 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5371 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005372
5373 return ResAddr;
5374}
5375
John McCall7f416cc2015-09-08 08:05:57 +00005376Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5377 CodeGenFunction &CGF) const {
5378 // The backend's lowering doesn't support va_arg for aggregates or
5379 // illegal vector types. Lower VAArg here for these cases and use
5380 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005381 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005382 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005383
John McCall7f416cc2015-09-08 08:05:57 +00005384 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005385
John McCall7f416cc2015-09-08 08:05:57 +00005386 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005387 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005388 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5389 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5390 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005391 }
5392
John McCall7f416cc2015-09-08 08:05:57 +00005393 // The size of the actual thing passed, which might end up just
5394 // being a pointer for indirect types.
5395 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5396
5397 // Arguments bigger than 16 bytes which aren't homogeneous
5398 // aggregates should be passed indirectly.
5399 bool IsIndirect = false;
5400 if (TyInfo.first.getQuantity() > 16) {
5401 const Type *Base = nullptr;
5402 uint64_t Members = 0;
5403 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005404 }
5405
John McCall7f416cc2015-09-08 08:05:57 +00005406 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5407 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005408}
5409
Martin Storsjo502de222017-07-13 17:59:14 +00005410Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5411 QualType Ty) const {
5412 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5413 CGF.getContext().getTypeInfoInChars(Ty),
5414 CharUnits::fromQuantity(8),
5415 /*allowHigherAlign*/ false);
5416}
5417
Tim Northovera2ee4332014-03-29 15:09:45 +00005418//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005419// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005420//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005421
5422namespace {
5423
John McCall12f23522016-04-04 18:33:08 +00005424class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005425public:
5426 enum ABIKind {
5427 APCS = 0,
5428 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005429 AAPCS_VFP = 2,
5430 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005431 };
5432
5433private:
5434 ABIKind Kind;
5435
5436public:
John McCall12f23522016-04-04 18:33:08 +00005437 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5438 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005439 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005440 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005441
John McCall3480ef22011-08-30 01:42:09 +00005442 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005443 switch (getTarget().getTriple().getEnvironment()) {
5444 case llvm::Triple::Android:
5445 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005446 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005447 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005448 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005449 case llvm::Triple::MuslEABI:
5450 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005451 return true;
5452 default:
5453 return false;
5454 }
John McCall3480ef22011-08-30 01:42:09 +00005455 }
5456
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005457 bool isEABIHF() const {
5458 switch (getTarget().getTriple().getEnvironment()) {
5459 case llvm::Triple::EABIHF:
5460 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005461 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005462 return true;
5463 default:
5464 return false;
5465 }
5466 }
5467
Daniel Dunbar020daa92009-09-12 01:00:39 +00005468 ABIKind getABIKind() const { return Kind; }
5469
Tim Northovera484bc02013-10-01 14:34:25 +00005470private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005471 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005472 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005473 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005474
Reid Klecknere9f6a712014-10-31 17:10:41 +00005475 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5476 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5477 uint64_t Members) const override;
5478
Craig Topper4f12f102014-03-12 06:41:41 +00005479 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005480
John McCall7f416cc2015-09-08 08:05:57 +00005481 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5482 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005483
5484 llvm::CallingConv::ID getLLVMDefaultCC() const;
5485 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005486 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005487
5488 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5489 ArrayRef<llvm::Type*> scalars,
5490 bool asReturnValue) const override {
5491 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5492 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005493 bool isSwiftErrorInRegister() const override {
5494 return true;
5495 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005496 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5497 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005498};
5499
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005500class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5501public:
Chris Lattner2b037972010-07-29 02:01:43 +00005502 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5503 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005504
John McCall3480ef22011-08-30 01:42:09 +00005505 const ARMABIInfo &getABIInfo() const {
5506 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5507 }
5508
Craig Topper4f12f102014-03-12 06:41:41 +00005509 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005510 return 13;
5511 }
Roman Divackyc1617352011-05-18 19:36:54 +00005512
Craig Topper4f12f102014-03-12 06:41:41 +00005513 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005514 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005515 }
5516
Roman Divackyc1617352011-05-18 19:36:54 +00005517 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005518 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005519 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005520
5521 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005522 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005523 return false;
5524 }
John McCall3480ef22011-08-30 01:42:09 +00005525
Craig Topper4f12f102014-03-12 06:41:41 +00005526 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005527 if (getABIInfo().isEABI()) return 88;
5528 return TargetCodeGenInfo::getSizeOfUnwindException();
5529 }
Tim Northovera484bc02013-10-01 14:34:25 +00005530
Eric Christopher162c91c2015-06-05 22:03:00 +00005531 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005532 CodeGen::CodeGenModule &CGM,
5533 ForDefinition_t IsForDefinition) const override {
5534 if (!IsForDefinition)
5535 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005536 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005537 if (!FD)
5538 return;
5539
5540 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5541 if (!Attr)
5542 return;
5543
5544 const char *Kind;
5545 switch (Attr->getInterrupt()) {
5546 case ARMInterruptAttr::Generic: Kind = ""; break;
5547 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5548 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5549 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5550 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5551 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5552 }
5553
5554 llvm::Function *Fn = cast<llvm::Function>(GV);
5555
5556 Fn->addFnAttr("interrupt", Kind);
5557
Tim Northover5627d392015-10-30 16:30:45 +00005558 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5559 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005560 return;
5561
5562 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5563 // however this is not necessarily true on taking any interrupt. Instruct
5564 // the backend to perform a realignment as part of the function prologue.
5565 llvm::AttrBuilder B;
5566 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005567 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005568 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005569};
5570
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005571class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005572public:
5573 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5574 : ARMTargetCodeGenInfo(CGT, K) {}
5575
Eric Christopher162c91c2015-06-05 22:03:00 +00005576 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005577 CodeGen::CodeGenModule &CGM,
5578 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005579
5580 void getDependentLibraryOption(llvm::StringRef Lib,
5581 llvm::SmallString<24> &Opt) const override {
5582 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5583 }
5584
5585 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5586 llvm::SmallString<32> &Opt) const override {
5587 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5588 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005589};
5590
Eric Christopher162c91c2015-06-05 22:03:00 +00005591void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005592 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5593 ForDefinition_t IsForDefinition) const {
5594 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5595 if (!IsForDefinition)
5596 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005597 addStackProbeSizeTargetAttribute(D, GV, CGM);
5598}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005599}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005600
Chris Lattner22326a12010-07-29 02:31:05 +00005601void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005602 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005603 FI.getReturnInfo() =
5604 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005605
Tim Northoverbc784d12015-02-24 17:22:40 +00005606 for (auto &I : FI.arguments())
5607 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005608
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005609 // Always honor user-specified calling convention.
5610 if (FI.getCallingConvention() != llvm::CallingConv::C)
5611 return;
5612
John McCall882987f2013-02-28 19:01:20 +00005613 llvm::CallingConv::ID cc = getRuntimeCC();
5614 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005615 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005616}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005617
John McCall882987f2013-02-28 19:01:20 +00005618/// Return the default calling convention that LLVM will use.
5619llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5620 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005621 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005622 return llvm::CallingConv::ARM_AAPCS_VFP;
5623 else if (isEABI())
5624 return llvm::CallingConv::ARM_AAPCS;
5625 else
5626 return llvm::CallingConv::ARM_APCS;
5627}
5628
5629/// Return the calling convention that our ABI would like us to use
5630/// as the C calling convention.
5631llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005632 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005633 case APCS: return llvm::CallingConv::ARM_APCS;
5634 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5635 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005636 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005637 }
John McCall882987f2013-02-28 19:01:20 +00005638 llvm_unreachable("bad ABI kind");
5639}
5640
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005641void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005642 assert(getRuntimeCC() == llvm::CallingConv::C);
5643
5644 // Don't muddy up the IR with a ton of explicit annotations if
5645 // they'd just match what LLVM will infer from the triple.
5646 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5647 if (abiCC != getLLVMDefaultCC())
5648 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005649
Tim Northover5627d392015-10-30 16:30:45 +00005650 // AAPCS apparently requires runtime support functions to be soft-float, but
5651 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5652 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005653
5654 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5655 // AEABI-complying FP helper functions to use the base AAPCS.
5656 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5657 // support functions emitted by clang such as the _Complex helpers follow the
5658 // abiCC.
5659 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005660 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005661}
5662
Tim Northoverbc784d12015-02-24 17:22:40 +00005663ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5664 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005665 // 6.1.2.1 The following argument types are VFP CPRCs:
5666 // A single-precision floating-point type (including promoted
5667 // half-precision types); A double-precision floating-point type;
5668 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5669 // with a Base Type of a single- or double-precision floating-point type,
5670 // 64-bit containerized vectors or 128-bit containerized vectors with one
5671 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005672 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005673
Reid Klecknerb1be6832014-11-15 01:41:41 +00005674 Ty = useFirstFieldIfTransparentUnion(Ty);
5675
Manman Renfef9e312012-10-16 19:18:39 +00005676 // Handle illegal vector types here.
5677 if (isIllegalVectorType(Ty)) {
5678 uint64_t Size = getContext().getTypeSize(Ty);
5679 if (Size <= 32) {
5680 llvm::Type *ResType =
5681 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005682 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005683 }
5684 if (Size == 64) {
5685 llvm::Type *ResType = llvm::VectorType::get(
5686 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005687 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005688 }
5689 if (Size == 128) {
5690 llvm::Type *ResType = llvm::VectorType::get(
5691 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005692 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005693 }
John McCall7f416cc2015-09-08 08:05:57 +00005694 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005695 }
5696
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005697 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5698 // unspecified. This is not done for OpenCL as it handles the half type
5699 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005700 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005701 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5702 llvm::Type::getFloatTy(getVMContext()) :
5703 llvm::Type::getInt32Ty(getVMContext());
5704 return ABIArgInfo::getDirect(ResType);
5705 }
5706
John McCalla1dee5302010-08-22 10:59:02 +00005707 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005708 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005709 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005710 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005711 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005712
Tim Northover5a1558e2014-11-07 22:30:50 +00005713 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5714 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005715 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005716
Oliver Stannard405bded2014-02-11 09:25:50 +00005717 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005718 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005719 }
Tim Northover1060eae2013-06-21 22:49:34 +00005720
Daniel Dunbar09d33622009-09-14 21:54:03 +00005721 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005722 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005723 return ABIArgInfo::getIgnore();
5724
Tim Northover5a1558e2014-11-07 22:30:50 +00005725 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005726 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5727 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005728 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005729 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005730 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005731 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005732 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005733 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005734 }
Tim Northover5627d392015-10-30 16:30:45 +00005735 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5736 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5737 // this convention even for a variadic function: the backend will use GPRs
5738 // if needed.
5739 const Type *Base = nullptr;
5740 uint64_t Members = 0;
5741 if (isHomogeneousAggregate(Ty, Base, Members)) {
5742 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5743 llvm::Type *Ty =
5744 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5745 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5746 }
5747 }
5748
5749 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5750 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5751 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5752 // bigger than 128-bits, they get placed in space allocated by the caller,
5753 // and a pointer is passed.
5754 return ABIArgInfo::getIndirect(
5755 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005756 }
5757
Manman Ren6c30e132012-08-13 21:23:55 +00005758 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005759 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5760 // most 8-byte. We realign the indirect argument if type alignment is bigger
5761 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005762 uint64_t ABIAlign = 4;
5763 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5764 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005765 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005766 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005767
Manman Ren8cd99812012-11-06 04:58:01 +00005768 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005769 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005770 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5771 /*ByVal=*/true,
5772 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005773 }
5774
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005775 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5776 // same size and alignment.
5777 if (getTarget().isRenderScriptTarget()) {
5778 return coerceToIntArray(Ty, getContext(), getVMContext());
5779 }
5780
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005781 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005782 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005783 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005784 // FIXME: Try to match the types of the arguments more accurately where
5785 // we can.
5786 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005787 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5788 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005789 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005790 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5791 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005792 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005793
Tim Northover5a1558e2014-11-07 22:30:50 +00005794 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005795}
5796
Chris Lattner458b2aa2010-07-29 02:16:43 +00005797static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005798 llvm::LLVMContext &VMContext) {
5799 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5800 // is called integer-like if its size is less than or equal to one word, and
5801 // the offset of each of its addressable sub-fields is zero.
5802
5803 uint64_t Size = Context.getTypeSize(Ty);
5804
5805 // Check that the type fits in a word.
5806 if (Size > 32)
5807 return false;
5808
5809 // FIXME: Handle vector types!
5810 if (Ty->isVectorType())
5811 return false;
5812
Daniel Dunbard53bac72009-09-14 02:20:34 +00005813 // Float types are never treated as "integer like".
5814 if (Ty->isRealFloatingType())
5815 return false;
5816
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005817 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005818 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005819 return true;
5820
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005821 // Small complex integer types are "integer like".
5822 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5823 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005824
5825 // Single element and zero sized arrays should be allowed, by the definition
5826 // above, but they are not.
5827
5828 // Otherwise, it must be a record type.
5829 const RecordType *RT = Ty->getAs<RecordType>();
5830 if (!RT) return false;
5831
5832 // Ignore records with flexible arrays.
5833 const RecordDecl *RD = RT->getDecl();
5834 if (RD->hasFlexibleArrayMember())
5835 return false;
5836
5837 // Check that all sub-fields are at offset 0, and are themselves "integer
5838 // like".
5839 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5840
5841 bool HadField = false;
5842 unsigned idx = 0;
5843 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5844 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005845 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005846
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005847 // Bit-fields are not addressable, we only need to verify they are "integer
5848 // like". We still have to disallow a subsequent non-bitfield, for example:
5849 // struct { int : 0; int x }
5850 // is non-integer like according to gcc.
5851 if (FD->isBitField()) {
5852 if (!RD->isUnion())
5853 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005854
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005855 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5856 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005857
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005858 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005859 }
5860
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005861 // Check if this field is at offset 0.
5862 if (Layout.getFieldOffset(idx) != 0)
5863 return false;
5864
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005865 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5866 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005867
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005868 // Only allow at most one field in a structure. This doesn't match the
5869 // wording above, but follows gcc in situations with a field following an
5870 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005871 if (!RD->isUnion()) {
5872 if (HadField)
5873 return false;
5874
5875 HadField = true;
5876 }
5877 }
5878
5879 return true;
5880}
5881
Oliver Stannard405bded2014-02-11 09:25:50 +00005882ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5883 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005884 bool IsEffectivelyAAPCS_VFP =
5885 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005886
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005887 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005888 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005889
Daniel Dunbar19964db2010-09-23 01:54:32 +00005890 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005891 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005892 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005893 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005894
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005895 // __fp16 gets returned as if it were an int or float, but with the top 16
5896 // bits unspecified. This is not done for OpenCL as it handles the half type
5897 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005898 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005899 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5900 llvm::Type::getFloatTy(getVMContext()) :
5901 llvm::Type::getInt32Ty(getVMContext());
5902 return ABIArgInfo::getDirect(ResType);
5903 }
5904
John McCalla1dee5302010-08-22 10:59:02 +00005905 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005906 // Treat an enum type as its underlying type.
5907 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5908 RetTy = EnumTy->getDecl()->getIntegerType();
5909
Tim Northover5a1558e2014-11-07 22:30:50 +00005910 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5911 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005912 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005913
5914 // Are we following APCS?
5915 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005916 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005917 return ABIArgInfo::getIgnore();
5918
Daniel Dunbareedf1512010-02-01 23:31:19 +00005919 // Complex types are all returned as packed integers.
5920 //
5921 // FIXME: Consider using 2 x vector types if the back end handles them
5922 // correctly.
5923 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005924 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5925 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005926
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005927 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005928 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005929 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005930 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005931 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005932 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005933 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005934 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5935 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005936 }
5937
5938 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005939 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005940 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005941
5942 // Otherwise this is an AAPCS variant.
5943
Chris Lattner458b2aa2010-07-29 02:16:43 +00005944 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005945 return ABIArgInfo::getIgnore();
5946
Bob Wilson1d9269a2011-11-02 04:51:36 +00005947 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005948 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005949 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005950 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005951 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005952 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005953 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005954 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005955 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005956 }
5957
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005958 // Aggregates <= 4 bytes are returned in r0; other aggregates
5959 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005960 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005961 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005962 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5963 // same size and alignment.
5964 if (getTarget().isRenderScriptTarget()) {
5965 return coerceToIntArray(RetTy, getContext(), getVMContext());
5966 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005967 if (getDataLayout().isBigEndian())
5968 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005969 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005970
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005971 // Return in the smallest viable integer type.
5972 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005973 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005974 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005975 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5976 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005977 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5978 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5979 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005980 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005981 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005982 }
5983
John McCall7f416cc2015-09-08 08:05:57 +00005984 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005985}
5986
Manman Renfef9e312012-10-16 19:18:39 +00005987/// isIllegalVector - check whether Ty is an illegal vector type.
5988bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005989 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5990 if (isAndroid()) {
5991 // Android shipped using Clang 3.1, which supported a slightly different
5992 // vector ABI. The primary differences were that 3-element vector types
5993 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5994 // accepts that legacy behavior for Android only.
5995 // Check whether VT is legal.
5996 unsigned NumElements = VT->getNumElements();
5997 // NumElements should be power of 2 or equal to 3.
5998 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5999 return true;
6000 } else {
6001 // Check whether VT is legal.
6002 unsigned NumElements = VT->getNumElements();
6003 uint64_t Size = getContext().getTypeSize(VT);
6004 // NumElements should be power of 2.
6005 if (!llvm::isPowerOf2_32(NumElements))
6006 return true;
6007 // Size should be greater than 32 bits.
6008 return Size <= 32;
6009 }
Manman Renfef9e312012-10-16 19:18:39 +00006010 }
6011 return false;
6012}
6013
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006014bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6015 llvm::Type *eltTy,
6016 unsigned numElts) const {
6017 if (!llvm::isPowerOf2_32(numElts))
6018 return false;
6019 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6020 if (size > 64)
6021 return false;
6022 if (vectorSize.getQuantity() != 8 &&
6023 (vectorSize.getQuantity() != 16 || numElts == 1))
6024 return false;
6025 return true;
6026}
6027
Reid Klecknere9f6a712014-10-31 17:10:41 +00006028bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6029 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6030 // double, or 64-bit or 128-bit vectors.
6031 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6032 if (BT->getKind() == BuiltinType::Float ||
6033 BT->getKind() == BuiltinType::Double ||
6034 BT->getKind() == BuiltinType::LongDouble)
6035 return true;
6036 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6037 unsigned VecSize = getContext().getTypeSize(VT);
6038 if (VecSize == 64 || VecSize == 128)
6039 return true;
6040 }
6041 return false;
6042}
6043
6044bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6045 uint64_t Members) const {
6046 return Members <= 4;
6047}
6048
John McCall7f416cc2015-09-08 08:05:57 +00006049Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6050 QualType Ty) const {
6051 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006052
John McCall7f416cc2015-09-08 08:05:57 +00006053 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006054 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006055 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6056 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6057 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006058 }
6059
John McCall7f416cc2015-09-08 08:05:57 +00006060 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6061 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006062
John McCall7f416cc2015-09-08 08:05:57 +00006063 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6064 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006065 const Type *Base = nullptr;
6066 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006067 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6068 IsIndirect = true;
6069
Tim Northover5627d392015-10-30 16:30:45 +00006070 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6071 // allocated by the caller.
6072 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6073 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6074 !isHomogeneousAggregate(Ty, Base, Members)) {
6075 IsIndirect = true;
6076
John McCall7f416cc2015-09-08 08:05:57 +00006077 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006078 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6079 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006080 // Our callers should be prepared to handle an under-aligned address.
6081 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6082 getABIKind() == ARMABIInfo::AAPCS) {
6083 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6084 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006085 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6086 // ARMv7k allows type alignment up to 16 bytes.
6087 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6088 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006089 } else {
6090 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006091 }
John McCall7f416cc2015-09-08 08:05:57 +00006092 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006093
John McCall7f416cc2015-09-08 08:05:57 +00006094 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6095 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006096}
6097
Chris Lattner0cf24192010-06-28 20:05:43 +00006098//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006099// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006100//===----------------------------------------------------------------------===//
6101
6102namespace {
6103
Justin Holewinski83e96682012-05-24 17:43:12 +00006104class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006105public:
Justin Holewinski36837432013-03-30 14:38:24 +00006106 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006107
6108 ABIArgInfo classifyReturnType(QualType RetTy) const;
6109 ABIArgInfo classifyArgumentType(QualType Ty) const;
6110
Craig Topper4f12f102014-03-12 06:41:41 +00006111 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006112 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6113 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006114};
6115
Justin Holewinski83e96682012-05-24 17:43:12 +00006116class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006117public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006118 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6119 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006120
Eric Christopher162c91c2015-06-05 22:03:00 +00006121 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006122 CodeGen::CodeGenModule &M,
6123 ForDefinition_t IsForDefinition) const override;
6124
Justin Holewinski36837432013-03-30 14:38:24 +00006125private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006126 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6127 // resulting MDNode to the nvvm.annotations MDNode.
6128 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006129};
6130
Justin Holewinski83e96682012-05-24 17:43:12 +00006131ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006132 if (RetTy->isVoidType())
6133 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006134
6135 // note: this is different from default ABI
6136 if (!RetTy->isScalarType())
6137 return ABIArgInfo::getDirect();
6138
6139 // Treat an enum type as its underlying type.
6140 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6141 RetTy = EnumTy->getDecl()->getIntegerType();
6142
6143 return (RetTy->isPromotableIntegerType() ?
6144 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006145}
6146
Justin Holewinski83e96682012-05-24 17:43:12 +00006147ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006148 // Treat an enum type as its underlying type.
6149 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6150 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006151
Eli Bendersky95338a02014-10-29 13:43:21 +00006152 // Return aggregates type as indirect by value
6153 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006154 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006155
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006156 return (Ty->isPromotableIntegerType() ?
6157 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006158}
6159
Justin Holewinski83e96682012-05-24 17:43:12 +00006160void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006161 if (!getCXXABI().classifyReturnType(FI))
6162 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006163 for (auto &I : FI.arguments())
6164 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006165
6166 // Always honor user-specified calling convention.
6167 if (FI.getCallingConvention() != llvm::CallingConv::C)
6168 return;
6169
John McCall882987f2013-02-28 19:01:20 +00006170 FI.setEffectiveCallingConvention(getRuntimeCC());
6171}
6172
John McCall7f416cc2015-09-08 08:05:57 +00006173Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6174 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006175 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006176}
6177
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006178void NVPTXTargetCodeGenInfo::setTargetAttributes(
6179 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6180 ForDefinition_t IsForDefinition) const {
6181 if (!IsForDefinition)
6182 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006183 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006184 if (!FD) return;
6185
6186 llvm::Function *F = cast<llvm::Function>(GV);
6187
6188 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006189 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006190 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006191 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006192 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006193 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006194 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6195 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006196 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006197 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006198 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006199 }
Justin Holewinski38031972011-10-05 17:58:44 +00006200
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006201 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006202 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006203 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006204 // __global__ functions cannot be called from the device, we do not
6205 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006206 if (FD->hasAttr<CUDAGlobalAttr>()) {
6207 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6208 addNVVMMetadata(F, "kernel", 1);
6209 }
Artem Belevich7093e402015-04-21 22:55:54 +00006210 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006211 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006212 llvm::APSInt MaxThreads(32);
6213 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6214 if (MaxThreads > 0)
6215 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6216
6217 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6218 // not specified in __launch_bounds__ or if the user specified a 0 value,
6219 // we don't have to add a PTX directive.
6220 if (Attr->getMinBlocks()) {
6221 llvm::APSInt MinBlocks(32);
6222 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6223 if (MinBlocks > 0)
6224 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6225 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006226 }
6227 }
Justin Holewinski38031972011-10-05 17:58:44 +00006228 }
6229}
6230
Eli Benderskye06a2c42014-04-15 16:57:05 +00006231void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6232 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006233 llvm::Module *M = F->getParent();
6234 llvm::LLVMContext &Ctx = M->getContext();
6235
6236 // Get "nvvm.annotations" metadata node
6237 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6238
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006239 llvm::Metadata *MDVals[] = {
6240 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6241 llvm::ConstantAsMetadata::get(
6242 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006243 // Append metadata to nvvm.annotations
6244 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6245}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006246}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006247
6248//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006249// SystemZ ABI Implementation
6250//===----------------------------------------------------------------------===//
6251
6252namespace {
6253
Bryan Chane3f1ed52016-04-28 13:56:43 +00006254class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006255 bool HasVector;
6256
Ulrich Weigand47445072013-05-06 16:26:41 +00006257public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006258 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006259 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006260
6261 bool isPromotableIntegerType(QualType Ty) const;
6262 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006263 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006264 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006265 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006266
6267 ABIArgInfo classifyReturnType(QualType RetTy) const;
6268 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6269
Craig Topper4f12f102014-03-12 06:41:41 +00006270 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006271 if (!getCXXABI().classifyReturnType(FI))
6272 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006273 for (auto &I : FI.arguments())
6274 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006275 }
6276
John McCall7f416cc2015-09-08 08:05:57 +00006277 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6278 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006279
6280 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6281 ArrayRef<llvm::Type*> scalars,
6282 bool asReturnValue) const override {
6283 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6284 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006285 bool isSwiftErrorInRegister() const override {
6286 return true;
6287 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006288};
6289
6290class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6291public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006292 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6293 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006294};
6295
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006296}
Ulrich Weigand47445072013-05-06 16:26:41 +00006297
6298bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6299 // Treat an enum type as its underlying type.
6300 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6301 Ty = EnumTy->getDecl()->getIntegerType();
6302
6303 // Promotable integer types are required to be promoted by the ABI.
6304 if (Ty->isPromotableIntegerType())
6305 return true;
6306
6307 // 32-bit values must also be promoted.
6308 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6309 switch (BT->getKind()) {
6310 case BuiltinType::Int:
6311 case BuiltinType::UInt:
6312 return true;
6313 default:
6314 return false;
6315 }
6316 return false;
6317}
6318
6319bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006320 return (Ty->isAnyComplexType() ||
6321 Ty->isVectorType() ||
6322 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006323}
6324
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006325bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6326 return (HasVector &&
6327 Ty->isVectorType() &&
6328 getContext().getTypeSize(Ty) <= 128);
6329}
6330
Ulrich Weigand47445072013-05-06 16:26:41 +00006331bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6332 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6333 switch (BT->getKind()) {
6334 case BuiltinType::Float:
6335 case BuiltinType::Double:
6336 return true;
6337 default:
6338 return false;
6339 }
6340
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006341 return false;
6342}
6343
6344QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006345 if (const RecordType *RT = Ty->getAsStructureType()) {
6346 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006347 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006348
6349 // If this is a C++ record, check the bases first.
6350 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006351 for (const auto &I : CXXRD->bases()) {
6352 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006353
6354 // Empty bases don't affect things either way.
6355 if (isEmptyRecord(getContext(), Base, true))
6356 continue;
6357
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006358 if (!Found.isNull())
6359 return Ty;
6360 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006361 }
6362
6363 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006364 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006365 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006366 // Unlike isSingleElementStruct(), empty structure and array fields
6367 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006368 if (getContext().getLangOpts().CPlusPlus &&
6369 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6370 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006371
6372 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006373 // Nested structures still do though.
6374 if (!Found.isNull())
6375 return Ty;
6376 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006377 }
6378
6379 // Unlike isSingleElementStruct(), trailing padding is allowed.
6380 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006381 if (!Found.isNull())
6382 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006383 }
6384
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006385 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006386}
6387
John McCall7f416cc2015-09-08 08:05:57 +00006388Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6389 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006390 // Assume that va_list type is correct; should be pointer to LLVM type:
6391 // struct {
6392 // i64 __gpr;
6393 // i64 __fpr;
6394 // i8 *__overflow_arg_area;
6395 // i8 *__reg_save_area;
6396 // };
6397
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006398 // Every non-vector argument occupies 8 bytes and is passed by preference
6399 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6400 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006401 Ty = getContext().getCanonicalType(Ty);
6402 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006403 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006404 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006405 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006406 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006407 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006408 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006409 CharUnits UnpaddedSize;
6410 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006411 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006412 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6413 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006414 } else {
6415 if (AI.getCoerceToType())
6416 ArgTy = AI.getCoerceToType();
6417 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006418 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006419 UnpaddedSize = TyInfo.first;
6420 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006421 }
John McCall7f416cc2015-09-08 08:05:57 +00006422 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6423 if (IsVector && UnpaddedSize > PaddedSize)
6424 PaddedSize = CharUnits::fromQuantity(16);
6425 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006426
John McCall7f416cc2015-09-08 08:05:57 +00006427 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006428
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006429 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006430 llvm::Value *PaddedSizeV =
6431 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006432
6433 if (IsVector) {
6434 // Work out the address of a vector argument on the stack.
6435 // Vector arguments are always passed in the high bits of a
6436 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006437 Address OverflowArgAreaPtr =
6438 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006439 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006440 Address OverflowArgArea =
6441 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6442 TyInfo.second);
6443 Address MemAddr =
6444 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006445
6446 // Update overflow_arg_area_ptr pointer
6447 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006448 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6449 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006450 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6451
6452 return MemAddr;
6453 }
6454
John McCall7f416cc2015-09-08 08:05:57 +00006455 assert(PaddedSize.getQuantity() == 8);
6456
6457 unsigned MaxRegs, RegCountField, RegSaveIndex;
6458 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006459 if (InFPRs) {
6460 MaxRegs = 4; // Maximum of 4 FPR arguments
6461 RegCountField = 1; // __fpr
6462 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006463 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006464 } else {
6465 MaxRegs = 5; // Maximum of 5 GPR arguments
6466 RegCountField = 0; // __gpr
6467 RegSaveIndex = 2; // save offset for r2
6468 RegPadding = Padding; // values are passed in the low bits of a GPR
6469 }
6470
John McCall7f416cc2015-09-08 08:05:57 +00006471 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6472 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6473 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006474 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006475 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6476 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006477 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006478
6479 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6480 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6481 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6482 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6483
6484 // Emit code to load the value if it was passed in registers.
6485 CGF.EmitBlock(InRegBlock);
6486
6487 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006488 llvm::Value *ScaledRegCount =
6489 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6490 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006491 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6492 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006493 llvm::Value *RegOffset =
6494 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006495 Address RegSaveAreaPtr =
6496 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6497 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006498 llvm::Value *RegSaveArea =
6499 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006500 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6501 "raw_reg_addr"),
6502 PaddedSize);
6503 Address RegAddr =
6504 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006505
6506 // Update the register count
6507 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6508 llvm::Value *NewRegCount =
6509 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6510 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6511 CGF.EmitBranch(ContBlock);
6512
6513 // Emit code to load the value if it was passed in memory.
6514 CGF.EmitBlock(InMemBlock);
6515
6516 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006517 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6518 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6519 Address OverflowArgArea =
6520 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6521 PaddedSize);
6522 Address RawMemAddr =
6523 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6524 Address MemAddr =
6525 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006526
6527 // Update overflow_arg_area_ptr pointer
6528 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006529 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6530 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006531 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6532 CGF.EmitBranch(ContBlock);
6533
6534 // Return the appropriate result.
6535 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006536 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6537 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006538
6539 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006540 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6541 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006542
6543 return ResAddr;
6544}
6545
Ulrich Weigand47445072013-05-06 16:26:41 +00006546ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6547 if (RetTy->isVoidType())
6548 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006549 if (isVectorArgumentType(RetTy))
6550 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006551 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006552 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006553 return (isPromotableIntegerType(RetTy) ?
6554 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6555}
6556
6557ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6558 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006559 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006560 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006561
6562 // Integers and enums are extended to full register width.
6563 if (isPromotableIntegerType(Ty))
6564 return ABIArgInfo::getExtend();
6565
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006566 // Handle vector types and vector-like structure types. Note that
6567 // as opposed to float-like structure types, we do not allow any
6568 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006569 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006570 QualType SingleElementTy = GetSingleElementType(Ty);
6571 if (isVectorArgumentType(SingleElementTy) &&
6572 getContext().getTypeSize(SingleElementTy) == Size)
6573 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6574
6575 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006576 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006577 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006578
6579 // Handle small structures.
6580 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6581 // Structures with flexible arrays have variable length, so really
6582 // fail the size test above.
6583 const RecordDecl *RD = RT->getDecl();
6584 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006585 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006586
6587 // The structure is passed as an unextended integer, a float, or a double.
6588 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006589 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006590 assert(Size == 32 || Size == 64);
6591 if (Size == 32)
6592 PassTy = llvm::Type::getFloatTy(getVMContext());
6593 else
6594 PassTy = llvm::Type::getDoubleTy(getVMContext());
6595 } else
6596 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6597 return ABIArgInfo::getDirect(PassTy);
6598 }
6599
6600 // Non-structure compounds are passed indirectly.
6601 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006602 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006603
Craig Topper8a13c412014-05-21 05:09:00 +00006604 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006605}
6606
6607//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006608// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006609//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006610
6611namespace {
6612
6613class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6614public:
Chris Lattner2b037972010-07-29 02:01:43 +00006615 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6616 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006617 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006618 CodeGen::CodeGenModule &M,
6619 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006620};
6621
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006622}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006623
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006624void MSP430TargetCodeGenInfo::setTargetAttributes(
6625 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6626 ForDefinition_t IsForDefinition) const {
6627 if (!IsForDefinition)
6628 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006629 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006630 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6631 // Handle 'interrupt' attribute:
6632 llvm::Function *F = cast<llvm::Function>(GV);
6633
6634 // Step 1: Set ISR calling convention.
6635 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6636
6637 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006638 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006639
6640 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006641 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006642 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6643 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006644 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006645 }
6646}
6647
Chris Lattner0cf24192010-06-28 20:05:43 +00006648//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006649// MIPS ABI Implementation. This works for both little-endian and
6650// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006651//===----------------------------------------------------------------------===//
6652
John McCall943fae92010-05-27 06:19:26 +00006653namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006654class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006655 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006656 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6657 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006658 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006659 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006660 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006661 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006662public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006663 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006664 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006665 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006666
6667 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006668 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006669 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006670 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6671 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006672 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006673};
6674
John McCall943fae92010-05-27 06:19:26 +00006675class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006676 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006677public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006678 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6679 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006680 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006681
Craig Topper4f12f102014-03-12 06:41:41 +00006682 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006683 return 29;
6684 }
6685
Eric Christopher162c91c2015-06-05 22:03:00 +00006686 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006687 CodeGen::CodeGenModule &CGM,
6688 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006689 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006690 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006691 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006692
6693 if (FD->hasAttr<MipsLongCallAttr>())
6694 Fn->addFnAttr("long-call");
6695 else if (FD->hasAttr<MipsShortCallAttr>())
6696 Fn->addFnAttr("short-call");
6697
6698 // Other attributes do not have a meaning for declarations.
6699 if (!IsForDefinition)
6700 return;
6701
Reed Kotler3d5966f2013-03-13 20:40:30 +00006702 if (FD->hasAttr<Mips16Attr>()) {
6703 Fn->addFnAttr("mips16");
6704 }
6705 else if (FD->hasAttr<NoMips16Attr>()) {
6706 Fn->addFnAttr("nomips16");
6707 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006708
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006709 if (FD->hasAttr<MicroMipsAttr>())
6710 Fn->addFnAttr("micromips");
6711 else if (FD->hasAttr<NoMicroMipsAttr>())
6712 Fn->addFnAttr("nomicromips");
6713
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006714 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6715 if (!Attr)
6716 return;
6717
6718 const char *Kind;
6719 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006720 case MipsInterruptAttr::eic: Kind = "eic"; break;
6721 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6722 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6723 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6724 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6725 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6726 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6727 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6728 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6729 }
6730
6731 Fn->addFnAttr("interrupt", Kind);
6732
Reed Kotler373feca2013-01-16 17:10:28 +00006733 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006734
John McCall943fae92010-05-27 06:19:26 +00006735 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006736 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006737
Craig Topper4f12f102014-03-12 06:41:41 +00006738 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006739 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006740 }
John McCall943fae92010-05-27 06:19:26 +00006741};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006742}
John McCall943fae92010-05-27 06:19:26 +00006743
Eric Christopher7565e0d2015-05-29 23:09:49 +00006744void MipsABIInfo::CoerceToIntArgs(
6745 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006746 llvm::IntegerType *IntTy =
6747 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006748
6749 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6750 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6751 ArgList.push_back(IntTy);
6752
6753 // If necessary, add one more integer type to ArgList.
6754 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6755
6756 if (R)
6757 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006758}
6759
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006760// In N32/64, an aligned double precision floating point field is passed in
6761// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006762llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006763 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6764
6765 if (IsO32) {
6766 CoerceToIntArgs(TySize, ArgList);
6767 return llvm::StructType::get(getVMContext(), ArgList);
6768 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006769
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006770 if (Ty->isComplexType())
6771 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006772
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006773 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006774
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006775 // Unions/vectors are passed in integer registers.
6776 if (!RT || !RT->isStructureOrClassType()) {
6777 CoerceToIntArgs(TySize, ArgList);
6778 return llvm::StructType::get(getVMContext(), ArgList);
6779 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006780
6781 const RecordDecl *RD = RT->getDecl();
6782 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006783 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006784
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006785 uint64_t LastOffset = 0;
6786 unsigned idx = 0;
6787 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6788
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006789 // Iterate over fields in the struct/class and check if there are any aligned
6790 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006791 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6792 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006793 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006794 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6795
6796 if (!BT || BT->getKind() != BuiltinType::Double)
6797 continue;
6798
6799 uint64_t Offset = Layout.getFieldOffset(idx);
6800 if (Offset % 64) // Ignore doubles that are not aligned.
6801 continue;
6802
6803 // Add ((Offset - LastOffset) / 64) args of type i64.
6804 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6805 ArgList.push_back(I64);
6806
6807 // Add double type.
6808 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6809 LastOffset = Offset + 64;
6810 }
6811
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006812 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6813 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006814
6815 return llvm::StructType::get(getVMContext(), ArgList);
6816}
6817
Akira Hatanakaddd66342013-10-29 18:41:15 +00006818llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6819 uint64_t Offset) const {
6820 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006821 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006822
Akira Hatanakaddd66342013-10-29 18:41:15 +00006823 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006824}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006825
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006826ABIArgInfo
6827MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006828 Ty = useFirstFieldIfTransparentUnion(Ty);
6829
Akira Hatanaka1632af62012-01-09 19:31:25 +00006830 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006831 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006832 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006833
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006834 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6835 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006836 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6837 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006838
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006839 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006840 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006841 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006842 return ABIArgInfo::getIgnore();
6843
Mark Lacey3825e832013-10-06 01:33:34 +00006844 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006845 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006846 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006847 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006848
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006849 // If we have reached here, aggregates are passed directly by coercing to
6850 // another structure type. Padding is inserted if the offset of the
6851 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006852 ABIArgInfo ArgInfo =
6853 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6854 getPaddingType(OrigOffset, CurrOffset));
6855 ArgInfo.setInReg(true);
6856 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006857 }
6858
6859 // Treat an enum type as its underlying type.
6860 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6861 Ty = EnumTy->getDecl()->getIntegerType();
6862
Daniel Sanders5b445b32014-10-24 14:42:42 +00006863 // All integral types are promoted to the GPR width.
6864 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006865 return ABIArgInfo::getExtend();
6866
Akira Hatanakaddd66342013-10-29 18:41:15 +00006867 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006868 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006869}
6870
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006871llvm::Type*
6872MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006873 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006874 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006875
Akira Hatanakab6f74432012-02-09 18:49:26 +00006876 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006877 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006878 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6879 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006880
Akira Hatanakab6f74432012-02-09 18:49:26 +00006881 // N32/64 returns struct/classes in floating point registers if the
6882 // following conditions are met:
6883 // 1. The size of the struct/class is no larger than 128-bit.
6884 // 2. The struct/class has one or two fields all of which are floating
6885 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006886 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006887 //
6888 // Any other composite results are returned in integer registers.
6889 //
6890 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6891 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6892 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006893 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006894
Akira Hatanakab6f74432012-02-09 18:49:26 +00006895 if (!BT || !BT->isFloatingPoint())
6896 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006897
David Blaikie2d7c57e2012-04-30 02:36:29 +00006898 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006899 }
6900
6901 if (b == e)
6902 return llvm::StructType::get(getVMContext(), RTList,
6903 RD->hasAttr<PackedAttr>());
6904
6905 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006906 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006907 }
6908
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006909 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006910 return llvm::StructType::get(getVMContext(), RTList);
6911}
6912
Akira Hatanakab579fe52011-06-02 00:09:17 +00006913ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006914 uint64_t Size = getContext().getTypeSize(RetTy);
6915
Daniel Sandersed39f582014-09-04 13:28:14 +00006916 if (RetTy->isVoidType())
6917 return ABIArgInfo::getIgnore();
6918
6919 // O32 doesn't treat zero-sized structs differently from other structs.
6920 // However, N32/N64 ignores zero sized return values.
6921 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006922 return ABIArgInfo::getIgnore();
6923
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006924 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006925 if (Size <= 128) {
6926 if (RetTy->isAnyComplexType())
6927 return ABIArgInfo::getDirect();
6928
Daniel Sanderse5018b62014-09-04 15:05:39 +00006929 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006930 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006931 if (!IsO32 ||
6932 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6933 ABIArgInfo ArgInfo =
6934 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6935 ArgInfo.setInReg(true);
6936 return ArgInfo;
6937 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006938 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006939
John McCall7f416cc2015-09-08 08:05:57 +00006940 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006941 }
6942
6943 // Treat an enum type as its underlying type.
6944 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6945 RetTy = EnumTy->getDecl()->getIntegerType();
6946
6947 return (RetTy->isPromotableIntegerType() ?
6948 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6949}
6950
6951void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006952 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006953 if (!getCXXABI().classifyReturnType(FI))
6954 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006955
Eric Christopher7565e0d2015-05-29 23:09:49 +00006956 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006957 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006958
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006959 for (auto &I : FI.arguments())
6960 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006961}
6962
John McCall7f416cc2015-09-08 08:05:57 +00006963Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6964 QualType OrigTy) const {
6965 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006966
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006967 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6968 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006969 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006970 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006971 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006972 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006973 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006974 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006975 DidPromote = true;
6976 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6977 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006978 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006979
John McCall7f416cc2015-09-08 08:05:57 +00006980 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006981
John McCall7f416cc2015-09-08 08:05:57 +00006982 // The alignment of things in the argument area is never larger than
6983 // StackAlignInBytes.
6984 TyInfo.second =
6985 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6986
6987 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6988 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6989
6990 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6991 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6992
6993
6994 // If there was a promotion, "unpromote" into a temporary.
6995 // TODO: can we just use a pointer into a subset of the original slot?
6996 if (DidPromote) {
6997 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6998 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6999
7000 // Truncate down to the right width.
7001 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7002 : CGF.IntPtrTy);
7003 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7004 if (OrigTy->isPointerType())
7005 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7006
7007 CGF.Builder.CreateStore(V, Temp);
7008 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007009 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007010
John McCall7f416cc2015-09-08 08:05:57 +00007011 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007012}
7013
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007014bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
7015 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007016
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007017 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7018 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7019 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00007020
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007021 return false;
7022}
7023
John McCall943fae92010-05-27 06:19:26 +00007024bool
7025MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7026 llvm::Value *Address) const {
7027 // This information comes from gcc's implementation, which seems to
7028 // as canonical as it gets.
7029
John McCall943fae92010-05-27 06:19:26 +00007030 // Everything on MIPS is 4 bytes. Double-precision FP registers
7031 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007032 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007033
7034 // 0-31 are the general purpose registers, $0 - $31.
7035 // 32-63 are the floating-point registers, $f0 - $f31.
7036 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7037 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007038 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007039
7040 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7041 // They are one bit wide and ignored here.
7042
7043 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7044 // (coprocessor 1 is the FP unit)
7045 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7046 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7047 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007048 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007049 return false;
7050}
7051
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007052//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007053// AVR ABI Implementation.
7054//===----------------------------------------------------------------------===//
7055
7056namespace {
7057class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7058public:
7059 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7060 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7061
7062 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007063 CodeGen::CodeGenModule &CGM,
7064 ForDefinition_t IsForDefinition) const override {
7065 if (!IsForDefinition)
7066 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007067 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7068 if (!FD) return;
7069 auto *Fn = cast<llvm::Function>(GV);
7070
7071 if (FD->getAttr<AVRInterruptAttr>())
7072 Fn->addFnAttr("interrupt");
7073
7074 if (FD->getAttr<AVRSignalAttr>())
7075 Fn->addFnAttr("signal");
7076 }
7077};
7078}
7079
7080//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007081// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007082// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007083// handling.
7084//===----------------------------------------------------------------------===//
7085
7086namespace {
7087
7088class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7089public:
7090 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7091 : DefaultTargetCodeGenInfo(CGT) {}
7092
Eric Christopher162c91c2015-06-05 22:03:00 +00007093 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007094 CodeGen::CodeGenModule &M,
7095 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007096};
7097
Eric Christopher162c91c2015-06-05 22:03:00 +00007098void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007099 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7100 ForDefinition_t IsForDefinition) const {
7101 if (!IsForDefinition)
7102 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007103 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007104 if (!FD) return;
7105
7106 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007107
David Blaikiebbafb8a2012-03-11 07:00:24 +00007108 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007109 if (FD->hasAttr<OpenCLKernelAttr>()) {
7110 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007111 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007112 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7113 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007114 // Convert the reqd_work_group_size() attributes to metadata.
7115 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007116 llvm::NamedMDNode *OpenCLMetadata =
7117 M.getModule().getOrInsertNamedMetadata(
7118 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007119
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007120 SmallVector<llvm::Metadata *, 5> Operands;
7121 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007122
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007123 Operands.push_back(
7124 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7125 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7126 Operands.push_back(
7127 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7128 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7129 Operands.push_back(
7130 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7131 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007132
Eric Christopher7565e0d2015-05-29 23:09:49 +00007133 // Add a boolean constant operand for "required" (true) or "hint"
7134 // (false) for implementing the work_group_size_hint attr later.
7135 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007136 Operands.push_back(
7137 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007138 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7139 }
7140 }
7141 }
7142}
7143
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007144}
John McCall943fae92010-05-27 06:19:26 +00007145
Tony Linthicum76329bf2011-12-12 21:14:55 +00007146//===----------------------------------------------------------------------===//
7147// Hexagon ABI Implementation
7148//===----------------------------------------------------------------------===//
7149
7150namespace {
7151
7152class HexagonABIInfo : public ABIInfo {
7153
7154
7155public:
7156 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7157
7158private:
7159
7160 ABIArgInfo classifyReturnType(QualType RetTy) const;
7161 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7162
Craig Topper4f12f102014-03-12 06:41:41 +00007163 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007164
John McCall7f416cc2015-09-08 08:05:57 +00007165 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7166 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007167};
7168
7169class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7170public:
7171 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7172 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7173
Craig Topper4f12f102014-03-12 06:41:41 +00007174 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007175 return 29;
7176 }
7177};
7178
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007179}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007180
7181void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007182 if (!getCXXABI().classifyReturnType(FI))
7183 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007184 for (auto &I : FI.arguments())
7185 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007186}
7187
7188ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7189 if (!isAggregateTypeForABI(Ty)) {
7190 // Treat an enum type as its underlying type.
7191 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7192 Ty = EnumTy->getDecl()->getIntegerType();
7193
7194 return (Ty->isPromotableIntegerType() ?
7195 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7196 }
7197
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007198 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7199 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7200
Tony Linthicum76329bf2011-12-12 21:14:55 +00007201 // Ignore empty records.
7202 if (isEmptyRecord(getContext(), Ty, true))
7203 return ABIArgInfo::getIgnore();
7204
Tony Linthicum76329bf2011-12-12 21:14:55 +00007205 uint64_t Size = getContext().getTypeSize(Ty);
7206 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007207 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007208 // Pass in the smallest viable integer type.
7209 else if (Size > 32)
7210 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7211 else if (Size > 16)
7212 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7213 else if (Size > 8)
7214 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7215 else
7216 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7217}
7218
7219ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7220 if (RetTy->isVoidType())
7221 return ABIArgInfo::getIgnore();
7222
7223 // Large vector types should be returned via memory.
7224 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007225 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007226
7227 if (!isAggregateTypeForABI(RetTy)) {
7228 // Treat an enum type as its underlying type.
7229 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7230 RetTy = EnumTy->getDecl()->getIntegerType();
7231
7232 return (RetTy->isPromotableIntegerType() ?
7233 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7234 }
7235
Tony Linthicum76329bf2011-12-12 21:14:55 +00007236 if (isEmptyRecord(getContext(), RetTy, true))
7237 return ABIArgInfo::getIgnore();
7238
7239 // Aggregates <= 8 bytes are returned in r0; other aggregates
7240 // are returned indirectly.
7241 uint64_t Size = getContext().getTypeSize(RetTy);
7242 if (Size <= 64) {
7243 // Return in the smallest viable integer type.
7244 if (Size <= 8)
7245 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7246 if (Size <= 16)
7247 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7248 if (Size <= 32)
7249 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7250 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7251 }
7252
John McCall7f416cc2015-09-08 08:05:57 +00007253 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007254}
7255
John McCall7f416cc2015-09-08 08:05:57 +00007256Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7257 QualType Ty) const {
7258 // FIXME: Someone needs to audit that this handle alignment correctly.
7259 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7260 getContext().getTypeInfoInChars(Ty),
7261 CharUnits::fromQuantity(4),
7262 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007263}
7264
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007265//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007266// Lanai ABI Implementation
7267//===----------------------------------------------------------------------===//
7268
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007269namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007270class LanaiABIInfo : public DefaultABIInfo {
7271public:
7272 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7273
7274 bool shouldUseInReg(QualType Ty, CCState &State) const;
7275
7276 void computeInfo(CGFunctionInfo &FI) const override {
7277 CCState State(FI.getCallingConvention());
7278 // Lanai uses 4 registers to pass arguments unless the function has the
7279 // regparm attribute set.
7280 if (FI.getHasRegParm()) {
7281 State.FreeRegs = FI.getRegParm();
7282 } else {
7283 State.FreeRegs = 4;
7284 }
7285
7286 if (!getCXXABI().classifyReturnType(FI))
7287 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7288 for (auto &I : FI.arguments())
7289 I.info = classifyArgumentType(I.type, State);
7290 }
7291
Jacques Pienaare74d9132016-04-26 00:09:29 +00007292 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007293 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7294};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007295} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007296
7297bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7298 unsigned Size = getContext().getTypeSize(Ty);
7299 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7300
7301 if (SizeInRegs == 0)
7302 return false;
7303
7304 if (SizeInRegs > State.FreeRegs) {
7305 State.FreeRegs = 0;
7306 return false;
7307 }
7308
7309 State.FreeRegs -= SizeInRegs;
7310
7311 return true;
7312}
7313
Jacques Pienaare74d9132016-04-26 00:09:29 +00007314ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7315 CCState &State) const {
7316 if (!ByVal) {
7317 if (State.FreeRegs) {
7318 --State.FreeRegs; // Non-byval indirects just use one pointer.
7319 return getNaturalAlignIndirectInReg(Ty);
7320 }
7321 return getNaturalAlignIndirect(Ty, false);
7322 }
7323
7324 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007325 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007326 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7327 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7328 /*Realign=*/TypeAlign >
7329 MinABIStackAlignInBytes);
7330}
7331
Jacques Pienaard964cc22016-03-28 21:02:54 +00007332ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7333 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007334 // Check with the C++ ABI first.
7335 const RecordType *RT = Ty->getAs<RecordType>();
7336 if (RT) {
7337 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7338 if (RAA == CGCXXABI::RAA_Indirect) {
7339 return getIndirectResult(Ty, /*ByVal=*/false, State);
7340 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7341 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7342 }
7343 }
7344
7345 if (isAggregateTypeForABI(Ty)) {
7346 // Structures with flexible arrays are always indirect.
7347 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7348 return getIndirectResult(Ty, /*ByVal=*/true, State);
7349
7350 // Ignore empty structs/unions.
7351 if (isEmptyRecord(getContext(), Ty, true))
7352 return ABIArgInfo::getIgnore();
7353
7354 llvm::LLVMContext &LLVMContext = getVMContext();
7355 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7356 if (SizeInRegs <= State.FreeRegs) {
7357 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7358 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7359 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7360 State.FreeRegs -= SizeInRegs;
7361 return ABIArgInfo::getDirectInReg(Result);
7362 } else {
7363 State.FreeRegs = 0;
7364 }
7365 return getIndirectResult(Ty, true, State);
7366 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007367
7368 // Treat an enum type as its underlying type.
7369 if (const auto *EnumTy = Ty->getAs<EnumType>())
7370 Ty = EnumTy->getDecl()->getIntegerType();
7371
Jacques Pienaare74d9132016-04-26 00:09:29 +00007372 bool InReg = shouldUseInReg(Ty, State);
7373 if (Ty->isPromotableIntegerType()) {
7374 if (InReg)
7375 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007376 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007377 }
7378 if (InReg)
7379 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007380 return ABIArgInfo::getDirect();
7381}
7382
7383namespace {
7384class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7385public:
7386 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7387 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7388};
7389}
7390
7391//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007392// AMDGPU ABI Implementation
7393//===----------------------------------------------------------------------===//
7394
7395namespace {
7396
Matt Arsenault88d7da02016-08-22 19:25:59 +00007397class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007398private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007399 static const unsigned MaxNumRegsForArgsRet = 16;
7400
Matt Arsenault3fe73952017-08-09 21:44:58 +00007401 unsigned numRegsForType(QualType Ty) const;
7402
7403 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7404 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7405 uint64_t Members) const override;
7406
7407public:
7408 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7409 DefaultABIInfo(CGT) {}
7410
7411 ABIArgInfo classifyReturnType(QualType RetTy) const;
7412 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7413 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007414
7415 void computeInfo(CGFunctionInfo &FI) const override;
7416};
7417
Matt Arsenault3fe73952017-08-09 21:44:58 +00007418bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7419 return true;
7420}
7421
7422bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7423 const Type *Base, uint64_t Members) const {
7424 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7425
7426 // Homogeneous Aggregates may occupy at most 16 registers.
7427 return Members * NumRegs <= MaxNumRegsForArgsRet;
7428}
7429
Matt Arsenault3fe73952017-08-09 21:44:58 +00007430/// Estimate number of registers the type will use when passed in registers.
7431unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7432 unsigned NumRegs = 0;
7433
7434 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7435 // Compute from the number of elements. The reported size is based on the
7436 // in-memory size, which includes the padding 4th element for 3-vectors.
7437 QualType EltTy = VT->getElementType();
7438 unsigned EltSize = getContext().getTypeSize(EltTy);
7439
7440 // 16-bit element vectors should be passed as packed.
7441 if (EltSize == 16)
7442 return (VT->getNumElements() + 1) / 2;
7443
7444 unsigned EltNumRegs = (EltSize + 31) / 32;
7445 return EltNumRegs * VT->getNumElements();
7446 }
7447
7448 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7449 const RecordDecl *RD = RT->getDecl();
7450 assert(!RD->hasFlexibleArrayMember());
7451
7452 for (const FieldDecl *Field : RD->fields()) {
7453 QualType FieldTy = Field->getType();
7454 NumRegs += numRegsForType(FieldTy);
7455 }
7456
7457 return NumRegs;
7458 }
7459
7460 return (getContext().getTypeSize(Ty) + 31) / 32;
7461}
7462
Matt Arsenault88d7da02016-08-22 19:25:59 +00007463void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007464 llvm::CallingConv::ID CC = FI.getCallingConvention();
7465
Matt Arsenault88d7da02016-08-22 19:25:59 +00007466 if (!getCXXABI().classifyReturnType(FI))
7467 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7468
Matt Arsenault3fe73952017-08-09 21:44:58 +00007469 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7470 for (auto &Arg : FI.arguments()) {
7471 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7472 Arg.info = classifyKernelArgumentType(Arg.type);
7473 } else {
7474 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7475 }
7476 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007477}
7478
Matt Arsenault3fe73952017-08-09 21:44:58 +00007479ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7480 if (isAggregateTypeForABI(RetTy)) {
7481 // Records with non-trivial destructors/copy-constructors should not be
7482 // returned by value.
7483 if (!getRecordArgABI(RetTy, getCXXABI())) {
7484 // Ignore empty structs/unions.
7485 if (isEmptyRecord(getContext(), RetTy, true))
7486 return ABIArgInfo::getIgnore();
7487
7488 // Lower single-element structs to just return a regular value.
7489 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7490 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7491
7492 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7493 const RecordDecl *RD = RT->getDecl();
7494 if (RD->hasFlexibleArrayMember())
7495 return DefaultABIInfo::classifyReturnType(RetTy);
7496 }
7497
7498 // Pack aggregates <= 4 bytes into single VGPR or pair.
7499 uint64_t Size = getContext().getTypeSize(RetTy);
7500 if (Size <= 16)
7501 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7502
7503 if (Size <= 32)
7504 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7505
7506 if (Size <= 64) {
7507 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7508 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7509 }
7510
7511 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7512 return ABIArgInfo::getDirect();
7513 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007514 }
7515
Matt Arsenault3fe73952017-08-09 21:44:58 +00007516 // Otherwise just do the default thing.
7517 return DefaultABIInfo::classifyReturnType(RetTy);
7518}
7519
7520/// For kernels all parameters are really passed in a special buffer. It doesn't
7521/// make sense to pass anything byval, so everything must be direct.
7522ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7523 Ty = useFirstFieldIfTransparentUnion(Ty);
7524
7525 // TODO: Can we omit empty structs?
7526
Matt Arsenault88d7da02016-08-22 19:25:59 +00007527 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007528 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7529 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007530
7531 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7532 // individual elements, which confuses the Clover OpenCL backend; therefore we
7533 // have to set it to false here. Other args of getDirect() are just defaults.
7534 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7535}
7536
Matt Arsenault3fe73952017-08-09 21:44:58 +00007537ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7538 unsigned &NumRegsLeft) const {
7539 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7540
7541 Ty = useFirstFieldIfTransparentUnion(Ty);
7542
7543 if (isAggregateTypeForABI(Ty)) {
7544 // Records with non-trivial destructors/copy-constructors should not be
7545 // passed by value.
7546 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7547 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7548
7549 // Ignore empty structs/unions.
7550 if (isEmptyRecord(getContext(), Ty, true))
7551 return ABIArgInfo::getIgnore();
7552
7553 // Lower single-element structs to just pass a regular value. TODO: We
7554 // could do reasonable-size multiple-element structs too, using getExpand(),
7555 // though watch out for things like bitfields.
7556 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7557 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7558
7559 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7560 const RecordDecl *RD = RT->getDecl();
7561 if (RD->hasFlexibleArrayMember())
7562 return DefaultABIInfo::classifyArgumentType(Ty);
7563 }
7564
7565 // Pack aggregates <= 8 bytes into single VGPR or pair.
7566 uint64_t Size = getContext().getTypeSize(Ty);
7567 if (Size <= 64) {
7568 unsigned NumRegs = (Size + 31) / 32;
7569 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7570
7571 if (Size <= 16)
7572 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7573
7574 if (Size <= 32)
7575 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7576
7577 // XXX: Should this be i64 instead, and should the limit increase?
7578 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7579 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7580 }
7581
7582 if (NumRegsLeft > 0) {
7583 unsigned NumRegs = numRegsForType(Ty);
7584 if (NumRegsLeft >= NumRegs) {
7585 NumRegsLeft -= NumRegs;
7586 return ABIArgInfo::getDirect();
7587 }
7588 }
7589 }
7590
7591 // Otherwise just do the default thing.
7592 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7593 if (!ArgInfo.isIndirect()) {
7594 unsigned NumRegs = numRegsForType(Ty);
7595 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7596 }
7597
7598 return ArgInfo;
7599}
7600
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007601class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7602public:
7603 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007604 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007605 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007606 CodeGen::CodeGenModule &M,
7607 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007608 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007609
Yaxun Liu402804b2016-12-15 08:09:08 +00007610 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7611 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007612
7613 unsigned getASTAllocaAddressSpace() const override {
7614 return LangAS::FirstTargetAddressSpace +
7615 getABIInfo().getDataLayout().getAllocaAddrSpace();
7616 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00007617 unsigned getGlobalVarAddressSpace(CodeGenModule &CGM,
7618 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007619 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7620 llvm::LLVMContext &C) const override;
Yaxun Liuc2a87a02017-10-14 12:23:50 +00007621 llvm::Function *
7622 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7623 llvm::Function *BlockInvokeFunc,
7624 llvm::Value *BlockLiteral) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007625};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007626}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007627
Eric Christopher162c91c2015-06-05 22:03:00 +00007628void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007629 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7630 ForDefinition_t IsForDefinition) const {
7631 if (!IsForDefinition)
7632 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007633 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007634 if (!FD)
7635 return;
7636
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007637 llvm::Function *F = cast<llvm::Function>(GV);
7638
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007639 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7640 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7641 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7642 if (ReqdWGS || FlatWGS) {
7643 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7644 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7645 if (ReqdWGS && Min == 0 && Max == 0)
7646 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007647
7648 if (Min != 0) {
7649 assert(Min <= Max && "Min must be less than or equal Max");
7650
7651 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7652 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7653 } else
7654 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007655 }
7656
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007657 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7658 unsigned Min = Attr->getMin();
7659 unsigned Max = Attr->getMax();
7660
7661 if (Min != 0) {
7662 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7663
7664 std::string AttrVal = llvm::utostr(Min);
7665 if (Max != 0)
7666 AttrVal = AttrVal + "," + llvm::utostr(Max);
7667 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7668 } else
7669 assert(Max == 0 && "Max must be zero");
7670 }
7671
7672 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007673 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007674
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007675 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007676 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7677 }
7678
7679 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7680 uint32_t NumVGPR = Attr->getNumVGPR();
7681
7682 if (NumVGPR != 0)
7683 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007684 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007685}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007686
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007687unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7688 return llvm::CallingConv::AMDGPU_KERNEL;
7689}
7690
Yaxun Liu402804b2016-12-15 08:09:08 +00007691// Currently LLVM assumes null pointers always have value 0,
7692// which results in incorrectly transformed IR. Therefore, instead of
7693// emitting null pointers in private and local address spaces, a null
7694// pointer in generic address space is emitted which is casted to a
7695// pointer in local or private address space.
7696llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7697 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7698 QualType QT) const {
7699 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7700 return llvm::ConstantPointerNull::get(PT);
7701
7702 auto &Ctx = CGM.getContext();
7703 auto NPT = llvm::PointerType::get(PT->getElementType(),
7704 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7705 return llvm::ConstantExpr::getAddrSpaceCast(
7706 llvm::ConstantPointerNull::get(NPT), PT);
7707}
7708
Yaxun Liucbf647c2017-07-08 13:24:52 +00007709unsigned
7710AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7711 const VarDecl *D) const {
7712 assert(!CGM.getLangOpts().OpenCL &&
7713 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7714 "Address space agnostic languages only");
7715 unsigned DefaultGlobalAS =
7716 LangAS::FirstTargetAddressSpace +
7717 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
7718 if (!D)
7719 return DefaultGlobalAS;
7720
7721 unsigned AddrSpace = D->getType().getAddressSpace();
7722 assert(AddrSpace == LangAS::Default ||
7723 AddrSpace >= LangAS::FirstTargetAddressSpace);
7724 if (AddrSpace != LangAS::Default)
7725 return AddrSpace;
7726
7727 if (CGM.isTypeConstant(D->getType(), false)) {
7728 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7729 return ConstAS.getValue();
7730 }
7731 return DefaultGlobalAS;
7732}
7733
Yaxun Liu39195062017-08-04 18:16:31 +00007734llvm::SyncScope::ID
7735AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7736 llvm::LLVMContext &C) const {
7737 StringRef Name;
7738 switch (S) {
7739 case SyncScope::OpenCLWorkGroup:
7740 Name = "workgroup";
7741 break;
7742 case SyncScope::OpenCLDevice:
7743 Name = "agent";
7744 break;
7745 case SyncScope::OpenCLAllSVMDevices:
7746 Name = "";
7747 break;
7748 case SyncScope::OpenCLSubGroup:
7749 Name = "subgroup";
7750 }
7751 return C.getOrInsertSyncScopeID(Name);
7752}
7753
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007754//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007755// SPARC v8 ABI Implementation.
7756// Based on the SPARC Compliance Definition version 2.4.1.
7757//
7758// Ensures that complex values are passed in registers.
7759//
7760namespace {
7761class SparcV8ABIInfo : public DefaultABIInfo {
7762public:
7763 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7764
7765private:
7766 ABIArgInfo classifyReturnType(QualType RetTy) const;
7767 void computeInfo(CGFunctionInfo &FI) const override;
7768};
7769} // end anonymous namespace
7770
7771
7772ABIArgInfo
7773SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7774 if (Ty->isAnyComplexType()) {
7775 return ABIArgInfo::getDirect();
7776 }
7777 else {
7778 return DefaultABIInfo::classifyReturnType(Ty);
7779 }
7780}
7781
7782void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7783
7784 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7785 for (auto &Arg : FI.arguments())
7786 Arg.info = classifyArgumentType(Arg.type);
7787}
7788
7789namespace {
7790class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7791public:
7792 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7793 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7794};
7795} // end anonymous namespace
7796
7797//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007798// SPARC v9 ABI Implementation.
7799// Based on the SPARC Compliance Definition version 2.4.1.
7800//
7801// Function arguments a mapped to a nominal "parameter array" and promoted to
7802// registers depending on their type. Each argument occupies 8 or 16 bytes in
7803// the array, structs larger than 16 bytes are passed indirectly.
7804//
7805// One case requires special care:
7806//
7807// struct mixed {
7808// int i;
7809// float f;
7810// };
7811//
7812// When a struct mixed is passed by value, it only occupies 8 bytes in the
7813// parameter array, but the int is passed in an integer register, and the float
7814// is passed in a floating point register. This is represented as two arguments
7815// with the LLVM IR inreg attribute:
7816//
7817// declare void f(i32 inreg %i, float inreg %f)
7818//
7819// The code generator will only allocate 4 bytes from the parameter array for
7820// the inreg arguments. All other arguments are allocated a multiple of 8
7821// bytes.
7822//
7823namespace {
7824class SparcV9ABIInfo : public ABIInfo {
7825public:
7826 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7827
7828private:
7829 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007830 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007831 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7832 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007833
7834 // Coercion type builder for structs passed in registers. The coercion type
7835 // serves two purposes:
7836 //
7837 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7838 // in registers.
7839 // 2. Expose aligned floating point elements as first-level elements, so the
7840 // code generator knows to pass them in floating point registers.
7841 //
7842 // We also compute the InReg flag which indicates that the struct contains
7843 // aligned 32-bit floats.
7844 //
7845 struct CoerceBuilder {
7846 llvm::LLVMContext &Context;
7847 const llvm::DataLayout &DL;
7848 SmallVector<llvm::Type*, 8> Elems;
7849 uint64_t Size;
7850 bool InReg;
7851
7852 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7853 : Context(c), DL(dl), Size(0), InReg(false) {}
7854
7855 // Pad Elems with integers until Size is ToSize.
7856 void pad(uint64_t ToSize) {
7857 assert(ToSize >= Size && "Cannot remove elements");
7858 if (ToSize == Size)
7859 return;
7860
7861 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007862 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007863 if (Aligned > Size && Aligned <= ToSize) {
7864 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7865 Size = Aligned;
7866 }
7867
7868 // Add whole 64-bit words.
7869 while (Size + 64 <= ToSize) {
7870 Elems.push_back(llvm::Type::getInt64Ty(Context));
7871 Size += 64;
7872 }
7873
7874 // Final in-word padding.
7875 if (Size < ToSize) {
7876 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7877 Size = ToSize;
7878 }
7879 }
7880
7881 // Add a floating point element at Offset.
7882 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7883 // Unaligned floats are treated as integers.
7884 if (Offset % Bits)
7885 return;
7886 // The InReg flag is only required if there are any floats < 64 bits.
7887 if (Bits < 64)
7888 InReg = true;
7889 pad(Offset);
7890 Elems.push_back(Ty);
7891 Size = Offset + Bits;
7892 }
7893
7894 // Add a struct type to the coercion type, starting at Offset (in bits).
7895 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7896 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7897 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7898 llvm::Type *ElemTy = StrTy->getElementType(i);
7899 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7900 switch (ElemTy->getTypeID()) {
7901 case llvm::Type::StructTyID:
7902 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7903 break;
7904 case llvm::Type::FloatTyID:
7905 addFloat(ElemOffset, ElemTy, 32);
7906 break;
7907 case llvm::Type::DoubleTyID:
7908 addFloat(ElemOffset, ElemTy, 64);
7909 break;
7910 case llvm::Type::FP128TyID:
7911 addFloat(ElemOffset, ElemTy, 128);
7912 break;
7913 case llvm::Type::PointerTyID:
7914 if (ElemOffset % 64 == 0) {
7915 pad(ElemOffset);
7916 Elems.push_back(ElemTy);
7917 Size += 64;
7918 }
7919 break;
7920 default:
7921 break;
7922 }
7923 }
7924 }
7925
7926 // Check if Ty is a usable substitute for the coercion type.
7927 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007928 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007929 }
7930
7931 // Get the coercion type as a literal struct type.
7932 llvm::Type *getType() const {
7933 if (Elems.size() == 1)
7934 return Elems.front();
7935 else
7936 return llvm::StructType::get(Context, Elems);
7937 }
7938 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007939};
7940} // end anonymous namespace
7941
7942ABIArgInfo
7943SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7944 if (Ty->isVoidType())
7945 return ABIArgInfo::getIgnore();
7946
7947 uint64_t Size = getContext().getTypeSize(Ty);
7948
7949 // Anything too big to fit in registers is passed with an explicit indirect
7950 // pointer / sret pointer.
7951 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007952 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007953
7954 // Treat an enum type as its underlying type.
7955 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7956 Ty = EnumTy->getDecl()->getIntegerType();
7957
7958 // Integer types smaller than a register are extended.
7959 if (Size < 64 && Ty->isIntegerType())
7960 return ABIArgInfo::getExtend();
7961
7962 // Other non-aggregates go in registers.
7963 if (!isAggregateTypeForABI(Ty))
7964 return ABIArgInfo::getDirect();
7965
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007966 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7967 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7968 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007969 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007970
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007971 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007972 // Build a coercion type from the LLVM struct type.
7973 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7974 if (!StrTy)
7975 return ABIArgInfo::getDirect();
7976
7977 CoerceBuilder CB(getVMContext(), getDataLayout());
7978 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007979 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007980
7981 // Try to use the original type for coercion.
7982 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7983
7984 if (CB.InReg)
7985 return ABIArgInfo::getDirectInReg(CoerceTy);
7986 else
7987 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007988}
7989
John McCall7f416cc2015-09-08 08:05:57 +00007990Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7991 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007992 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7993 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7994 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7995 AI.setCoerceToType(ArgTy);
7996
John McCall7f416cc2015-09-08 08:05:57 +00007997 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007998
John McCall7f416cc2015-09-08 08:05:57 +00007999 CGBuilderTy &Builder = CGF.Builder;
8000 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8001 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8002
8003 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8004
8005 Address ArgAddr = Address::invalid();
8006 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008007 switch (AI.getKind()) {
8008 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008009 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008010 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008011 llvm_unreachable("Unsupported ABI kind for va_arg");
8012
John McCall7f416cc2015-09-08 08:05:57 +00008013 case ABIArgInfo::Extend: {
8014 Stride = SlotSize;
8015 CharUnits Offset = SlotSize - TypeInfo.first;
8016 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008017 break;
John McCall7f416cc2015-09-08 08:05:57 +00008018 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008019
John McCall7f416cc2015-09-08 08:05:57 +00008020 case ABIArgInfo::Direct: {
8021 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008022 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008023 ArgAddr = Addr;
8024 break;
John McCall7f416cc2015-09-08 08:05:57 +00008025 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008026
8027 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008028 Stride = SlotSize;
8029 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8030 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8031 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008032 break;
8033
8034 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008035 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008036 }
8037
8038 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008039 llvm::Value *NextPtr =
8040 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8041 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008042
John McCall7f416cc2015-09-08 08:05:57 +00008043 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008044}
8045
8046void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8047 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008048 for (auto &I : FI.arguments())
8049 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008050}
8051
8052namespace {
8053class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8054public:
8055 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8056 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008057
Craig Topper4f12f102014-03-12 06:41:41 +00008058 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008059 return 14;
8060 }
8061
8062 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008063 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008064};
8065} // end anonymous namespace
8066
Roman Divackyf02c9942014-02-24 18:46:27 +00008067bool
8068SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8069 llvm::Value *Address) const {
8070 // This is calculated from the LLVM and GCC tables and verified
8071 // against gcc output. AFAIK all ABIs use the same encoding.
8072
8073 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8074
8075 llvm::IntegerType *i8 = CGF.Int8Ty;
8076 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8077 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8078
8079 // 0-31: the 8-byte general-purpose registers
8080 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8081
8082 // 32-63: f0-31, the 4-byte floating-point registers
8083 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8084
8085 // Y = 64
8086 // PSR = 65
8087 // WIM = 66
8088 // TBR = 67
8089 // PC = 68
8090 // NPC = 69
8091 // FSR = 70
8092 // CSR = 71
8093 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008094
Roman Divackyf02c9942014-02-24 18:46:27 +00008095 // 72-87: d0-15, the 8-byte floating-point registers
8096 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8097
8098 return false;
8099}
8100
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008101
Robert Lytton0e076492013-08-13 09:43:10 +00008102//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008103// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008104//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008105
Robert Lytton0e076492013-08-13 09:43:10 +00008106namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008107
8108/// A SmallStringEnc instance is used to build up the TypeString by passing
8109/// it by reference between functions that append to it.
8110typedef llvm::SmallString<128> SmallStringEnc;
8111
8112/// TypeStringCache caches the meta encodings of Types.
8113///
8114/// The reason for caching TypeStrings is two fold:
8115/// 1. To cache a type's encoding for later uses;
8116/// 2. As a means to break recursive member type inclusion.
8117///
8118/// A cache Entry can have a Status of:
8119/// NonRecursive: The type encoding is not recursive;
8120/// Recursive: The type encoding is recursive;
8121/// Incomplete: An incomplete TypeString;
8122/// IncompleteUsed: An incomplete TypeString that has been used in a
8123/// Recursive type encoding.
8124///
8125/// A NonRecursive entry will have all of its sub-members expanded as fully
8126/// as possible. Whilst it may contain types which are recursive, the type
8127/// itself is not recursive and thus its encoding may be safely used whenever
8128/// the type is encountered.
8129///
8130/// A Recursive entry will have all of its sub-members expanded as fully as
8131/// possible. The type itself is recursive and it may contain other types which
8132/// are recursive. The Recursive encoding must not be used during the expansion
8133/// of a recursive type's recursive branch. For simplicity the code uses
8134/// IncompleteCount to reject all usage of Recursive encodings for member types.
8135///
8136/// An Incomplete entry is always a RecordType and only encodes its
8137/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8138/// are placed into the cache during type expansion as a means to identify and
8139/// handle recursive inclusion of types as sub-members. If there is recursion
8140/// the entry becomes IncompleteUsed.
8141///
8142/// During the expansion of a RecordType's members:
8143///
8144/// If the cache contains a NonRecursive encoding for the member type, the
8145/// cached encoding is used;
8146///
8147/// If the cache contains a Recursive encoding for the member type, the
8148/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8149///
8150/// If the member is a RecordType, an Incomplete encoding is placed into the
8151/// cache to break potential recursive inclusion of itself as a sub-member;
8152///
8153/// Once a member RecordType has been expanded, its temporary incomplete
8154/// entry is removed from the cache. If a Recursive encoding was swapped out
8155/// it is swapped back in;
8156///
8157/// If an incomplete entry is used to expand a sub-member, the incomplete
8158/// entry is marked as IncompleteUsed. The cache keeps count of how many
8159/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8160///
8161/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8162/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8163/// Else the member is part of a recursive type and thus the recursion has
8164/// been exited too soon for the encoding to be correct for the member.
8165///
8166class TypeStringCache {
8167 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8168 struct Entry {
8169 std::string Str; // The encoded TypeString for the type.
8170 enum Status State; // Information about the encoding in 'Str'.
8171 std::string Swapped; // A temporary place holder for a Recursive encoding
8172 // during the expansion of RecordType's members.
8173 };
8174 std::map<const IdentifierInfo *, struct Entry> Map;
8175 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8176 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8177public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008178 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008179 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8180 bool removeIncomplete(const IdentifierInfo *ID);
8181 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8182 bool IsRecursive);
8183 StringRef lookupStr(const IdentifierInfo *ID);
8184};
8185
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008186/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008187/// FieldEncoding is a helper for this ordering process.
8188class FieldEncoding {
8189 bool HasName;
8190 std::string Enc;
8191public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008192 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008193 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008194 bool operator<(const FieldEncoding &rhs) const {
8195 if (HasName != rhs.HasName) return HasName;
8196 return Enc < rhs.Enc;
8197 }
8198};
8199
Robert Lytton7d1db152013-08-19 09:46:39 +00008200class XCoreABIInfo : public DefaultABIInfo {
8201public:
8202 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008203 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8204 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008205};
8206
Robert Lyttond21e2d72014-03-03 13:45:29 +00008207class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008208 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008209public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008210 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008211 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008212 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8213 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008214};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008215
Robert Lytton2d196952013-10-11 10:29:34 +00008216} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008217
James Y Knight29b5f082016-02-24 02:59:33 +00008218// TODO: this implementation is likely now redundant with the default
8219// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008220Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8221 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008222 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008223
Robert Lytton2d196952013-10-11 10:29:34 +00008224 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008225 CharUnits SlotSize = CharUnits::fromQuantity(4);
8226 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008227
Robert Lytton2d196952013-10-11 10:29:34 +00008228 // Handle the argument.
8229 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008230 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008231 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8232 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8233 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008234 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008235
8236 Address Val = Address::invalid();
8237 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008238 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008239 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008240 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008241 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008242 llvm_unreachable("Unsupported ABI kind for va_arg");
8243 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008244 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8245 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008246 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008247 case ABIArgInfo::Extend:
8248 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008249 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8250 ArgSize = CharUnits::fromQuantity(
8251 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008252 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008253 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008254 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008255 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8256 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8257 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008258 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008259 }
Robert Lytton2d196952013-10-11 10:29:34 +00008260
8261 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008262 if (!ArgSize.isZero()) {
8263 llvm::Value *APN =
8264 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8265 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008266 }
John McCall7f416cc2015-09-08 08:05:57 +00008267
Robert Lytton2d196952013-10-11 10:29:34 +00008268 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008269}
Robert Lytton0e076492013-08-13 09:43:10 +00008270
Robert Lytton844aeeb2014-05-02 09:33:20 +00008271/// During the expansion of a RecordType, an incomplete TypeString is placed
8272/// into the cache as a means to identify and break recursion.
8273/// If there is a Recursive encoding in the cache, it is swapped out and will
8274/// be reinserted by removeIncomplete().
8275/// All other types of encoding should have been used rather than arriving here.
8276void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8277 std::string StubEnc) {
8278 if (!ID)
8279 return;
8280 Entry &E = Map[ID];
8281 assert( (E.Str.empty() || E.State == Recursive) &&
8282 "Incorrectly use of addIncomplete");
8283 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8284 E.Swapped.swap(E.Str); // swap out the Recursive
8285 E.Str.swap(StubEnc);
8286 E.State = Incomplete;
8287 ++IncompleteCount;
8288}
8289
8290/// Once the RecordType has been expanded, the temporary incomplete TypeString
8291/// must be removed from the cache.
8292/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8293/// Returns true if the RecordType was defined recursively.
8294bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8295 if (!ID)
8296 return false;
8297 auto I = Map.find(ID);
8298 assert(I != Map.end() && "Entry not present");
8299 Entry &E = I->second;
8300 assert( (E.State == Incomplete ||
8301 E.State == IncompleteUsed) &&
8302 "Entry must be an incomplete type");
8303 bool IsRecursive = false;
8304 if (E.State == IncompleteUsed) {
8305 // We made use of our Incomplete encoding, thus we are recursive.
8306 IsRecursive = true;
8307 --IncompleteUsedCount;
8308 }
8309 if (E.Swapped.empty())
8310 Map.erase(I);
8311 else {
8312 // Swap the Recursive back.
8313 E.Swapped.swap(E.Str);
8314 E.Swapped.clear();
8315 E.State = Recursive;
8316 }
8317 --IncompleteCount;
8318 return IsRecursive;
8319}
8320
8321/// Add the encoded TypeString to the cache only if it is NonRecursive or
8322/// Recursive (viz: all sub-members were expanded as fully as possible).
8323void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8324 bool IsRecursive) {
8325 if (!ID || IncompleteUsedCount)
8326 return; // No key or it is is an incomplete sub-type so don't add.
8327 Entry &E = Map[ID];
8328 if (IsRecursive && !E.Str.empty()) {
8329 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8330 "This is not the same Recursive entry");
8331 // The parent container was not recursive after all, so we could have used
8332 // this Recursive sub-member entry after all, but we assumed the worse when
8333 // we started viz: IncompleteCount!=0.
8334 return;
8335 }
8336 assert(E.Str.empty() && "Entry already present");
8337 E.Str = Str.str();
8338 E.State = IsRecursive? Recursive : NonRecursive;
8339}
8340
8341/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8342/// are recursively expanding a type (IncompleteCount != 0) and the cached
8343/// encoding is Recursive, return an empty StringRef.
8344StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8345 if (!ID)
8346 return StringRef(); // We have no key.
8347 auto I = Map.find(ID);
8348 if (I == Map.end())
8349 return StringRef(); // We have no encoding.
8350 Entry &E = I->second;
8351 if (E.State == Recursive && IncompleteCount)
8352 return StringRef(); // We don't use Recursive encodings for member types.
8353
8354 if (E.State == Incomplete) {
8355 // The incomplete type is being used to break out of recursion.
8356 E.State = IncompleteUsed;
8357 ++IncompleteUsedCount;
8358 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008359 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008360}
8361
8362/// The XCore ABI includes a type information section that communicates symbol
8363/// type information to the linker. The linker uses this information to verify
8364/// safety/correctness of things such as array bound and pointers et al.
8365/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8366/// This type information (TypeString) is emitted into meta data for all global
8367/// symbols: definitions, declarations, functions & variables.
8368///
8369/// The TypeString carries type, qualifier, name, size & value details.
8370/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008371/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008372/// The output is tested by test/CodeGen/xcore-stringtype.c.
8373///
8374static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8375 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8376
8377/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8378void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8379 CodeGen::CodeGenModule &CGM) const {
8380 SmallStringEnc Enc;
8381 if (getTypeString(Enc, D, CGM, TSC)) {
8382 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008383 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8384 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008385 llvm::NamedMDNode *MD =
8386 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8387 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8388 }
8389}
8390
Xiuli Pan972bea82016-03-24 03:57:17 +00008391//===----------------------------------------------------------------------===//
8392// SPIR ABI Implementation
8393//===----------------------------------------------------------------------===//
8394
8395namespace {
8396class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8397public:
8398 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8399 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008400 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008401};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008402
Xiuli Pan972bea82016-03-24 03:57:17 +00008403} // End anonymous namespace.
8404
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008405namespace clang {
8406namespace CodeGen {
8407void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8408 DefaultABIInfo SPIRABI(CGM.getTypes());
8409 SPIRABI.computeInfo(FI);
8410}
8411}
8412}
8413
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008414unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8415 return llvm::CallingConv::SPIR_KERNEL;
8416}
8417
Robert Lytton844aeeb2014-05-02 09:33:20 +00008418static bool appendType(SmallStringEnc &Enc, QualType QType,
8419 const CodeGen::CodeGenModule &CGM,
8420 TypeStringCache &TSC);
8421
8422/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008423/// Builds a SmallVector containing the encoded field types in declaration
8424/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008425static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8426 const RecordDecl *RD,
8427 const CodeGen::CodeGenModule &CGM,
8428 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008429 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008430 SmallStringEnc Enc;
8431 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008432 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008433 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008434 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008435 Enc += "b(";
8436 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008437 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008438 Enc += ':';
8439 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008440 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008441 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008442 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008443 Enc += ')';
8444 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008445 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008446 }
8447 return true;
8448}
8449
8450/// Appends structure and union types to Enc and adds encoding to cache.
8451/// Recursively calls appendType (via extractFieldType) for each field.
8452/// Union types have their fields ordered according to the ABI.
8453static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8454 const CodeGen::CodeGenModule &CGM,
8455 TypeStringCache &TSC, const IdentifierInfo *ID) {
8456 // Append the cached TypeString if we have one.
8457 StringRef TypeString = TSC.lookupStr(ID);
8458 if (!TypeString.empty()) {
8459 Enc += TypeString;
8460 return true;
8461 }
8462
8463 // Start to emit an incomplete TypeString.
8464 size_t Start = Enc.size();
8465 Enc += (RT->isUnionType()? 'u' : 's');
8466 Enc += '(';
8467 if (ID)
8468 Enc += ID->getName();
8469 Enc += "){";
8470
8471 // We collect all encoded fields and order as necessary.
8472 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008473 const RecordDecl *RD = RT->getDecl()->getDefinition();
8474 if (RD && !RD->field_empty()) {
8475 // An incomplete TypeString stub is placed in the cache for this RecordType
8476 // so that recursive calls to this RecordType will use it whilst building a
8477 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008478 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008479 std::string StubEnc(Enc.substr(Start).str());
8480 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8481 TSC.addIncomplete(ID, std::move(StubEnc));
8482 if (!extractFieldType(FE, RD, CGM, TSC)) {
8483 (void) TSC.removeIncomplete(ID);
8484 return false;
8485 }
8486 IsRecursive = TSC.removeIncomplete(ID);
8487 // The ABI requires unions to be sorted but not structures.
8488 // See FieldEncoding::operator< for sort algorithm.
8489 if (RT->isUnionType())
8490 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008491 // We can now complete the TypeString.
8492 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008493 for (unsigned I = 0; I != E; ++I) {
8494 if (I)
8495 Enc += ',';
8496 Enc += FE[I].str();
8497 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008498 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008499 Enc += '}';
8500 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8501 return true;
8502}
8503
8504/// Appends enum types to Enc and adds the encoding to the cache.
8505static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8506 TypeStringCache &TSC,
8507 const IdentifierInfo *ID) {
8508 // Append the cached TypeString if we have one.
8509 StringRef TypeString = TSC.lookupStr(ID);
8510 if (!TypeString.empty()) {
8511 Enc += TypeString;
8512 return true;
8513 }
8514
8515 size_t Start = Enc.size();
8516 Enc += "e(";
8517 if (ID)
8518 Enc += ID->getName();
8519 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008520
8521 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008522 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008523 SmallVector<FieldEncoding, 16> FE;
8524 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8525 ++I) {
8526 SmallStringEnc EnumEnc;
8527 EnumEnc += "m(";
8528 EnumEnc += I->getName();
8529 EnumEnc += "){";
8530 I->getInitVal().toString(EnumEnc);
8531 EnumEnc += '}';
8532 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8533 }
8534 std::sort(FE.begin(), FE.end());
8535 unsigned E = FE.size();
8536 for (unsigned I = 0; I != E; ++I) {
8537 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008538 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008539 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008540 }
8541 }
8542 Enc += '}';
8543 TSC.addIfComplete(ID, Enc.substr(Start), false);
8544 return true;
8545}
8546
8547/// Appends type's qualifier to Enc.
8548/// This is done prior to appending the type's encoding.
8549static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8550 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008551 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008552 int Lookup = 0;
8553 if (QT.isConstQualified())
8554 Lookup += 1<<0;
8555 if (QT.isRestrictQualified())
8556 Lookup += 1<<1;
8557 if (QT.isVolatileQualified())
8558 Lookup += 1<<2;
8559 Enc += Table[Lookup];
8560}
8561
8562/// Appends built-in types to Enc.
8563static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8564 const char *EncType;
8565 switch (BT->getKind()) {
8566 case BuiltinType::Void:
8567 EncType = "0";
8568 break;
8569 case BuiltinType::Bool:
8570 EncType = "b";
8571 break;
8572 case BuiltinType::Char_U:
8573 EncType = "uc";
8574 break;
8575 case BuiltinType::UChar:
8576 EncType = "uc";
8577 break;
8578 case BuiltinType::SChar:
8579 EncType = "sc";
8580 break;
8581 case BuiltinType::UShort:
8582 EncType = "us";
8583 break;
8584 case BuiltinType::Short:
8585 EncType = "ss";
8586 break;
8587 case BuiltinType::UInt:
8588 EncType = "ui";
8589 break;
8590 case BuiltinType::Int:
8591 EncType = "si";
8592 break;
8593 case BuiltinType::ULong:
8594 EncType = "ul";
8595 break;
8596 case BuiltinType::Long:
8597 EncType = "sl";
8598 break;
8599 case BuiltinType::ULongLong:
8600 EncType = "ull";
8601 break;
8602 case BuiltinType::LongLong:
8603 EncType = "sll";
8604 break;
8605 case BuiltinType::Float:
8606 EncType = "ft";
8607 break;
8608 case BuiltinType::Double:
8609 EncType = "d";
8610 break;
8611 case BuiltinType::LongDouble:
8612 EncType = "ld";
8613 break;
8614 default:
8615 return false;
8616 }
8617 Enc += EncType;
8618 return true;
8619}
8620
8621/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8622static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8623 const CodeGen::CodeGenModule &CGM,
8624 TypeStringCache &TSC) {
8625 Enc += "p(";
8626 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8627 return false;
8628 Enc += ')';
8629 return true;
8630}
8631
8632/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008633static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8634 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008635 const CodeGen::CodeGenModule &CGM,
8636 TypeStringCache &TSC, StringRef NoSizeEnc) {
8637 if (AT->getSizeModifier() != ArrayType::Normal)
8638 return false;
8639 Enc += "a(";
8640 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8641 CAT->getSize().toStringUnsigned(Enc);
8642 else
8643 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8644 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008645 // The Qualifiers should be attached to the type rather than the array.
8646 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008647 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8648 return false;
8649 Enc += ')';
8650 return true;
8651}
8652
8653/// Appends a function encoding to Enc, calling appendType for the return type
8654/// and the arguments.
8655static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8656 const CodeGen::CodeGenModule &CGM,
8657 TypeStringCache &TSC) {
8658 Enc += "f{";
8659 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8660 return false;
8661 Enc += "}(";
8662 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8663 // N.B. we are only interested in the adjusted param types.
8664 auto I = FPT->param_type_begin();
8665 auto E = FPT->param_type_end();
8666 if (I != E) {
8667 do {
8668 if (!appendType(Enc, *I, CGM, TSC))
8669 return false;
8670 ++I;
8671 if (I != E)
8672 Enc += ',';
8673 } while (I != E);
8674 if (FPT->isVariadic())
8675 Enc += ",va";
8676 } else {
8677 if (FPT->isVariadic())
8678 Enc += "va";
8679 else
8680 Enc += '0';
8681 }
8682 }
8683 Enc += ')';
8684 return true;
8685}
8686
8687/// Handles the type's qualifier before dispatching a call to handle specific
8688/// type encodings.
8689static bool appendType(SmallStringEnc &Enc, QualType QType,
8690 const CodeGen::CodeGenModule &CGM,
8691 TypeStringCache &TSC) {
8692
8693 QualType QT = QType.getCanonicalType();
8694
Robert Lytton6adb20f2014-06-05 09:06:21 +00008695 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8696 // The Qualifiers should be attached to the type rather than the array.
8697 // Thus we don't call appendQualifier() here.
8698 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8699
Robert Lytton844aeeb2014-05-02 09:33:20 +00008700 appendQualifier(Enc, QT);
8701
8702 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8703 return appendBuiltinType(Enc, BT);
8704
Robert Lytton844aeeb2014-05-02 09:33:20 +00008705 if (const PointerType *PT = QT->getAs<PointerType>())
8706 return appendPointerType(Enc, PT, CGM, TSC);
8707
8708 if (const EnumType *ET = QT->getAs<EnumType>())
8709 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8710
8711 if (const RecordType *RT = QT->getAsStructureType())
8712 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8713
8714 if (const RecordType *RT = QT->getAsUnionType())
8715 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8716
8717 if (const FunctionType *FT = QT->getAs<FunctionType>())
8718 return appendFunctionType(Enc, FT, CGM, TSC);
8719
8720 return false;
8721}
8722
8723static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8724 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8725 if (!D)
8726 return false;
8727
8728 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8729 if (FD->getLanguageLinkage() != CLanguageLinkage)
8730 return false;
8731 return appendType(Enc, FD->getType(), CGM, TSC);
8732 }
8733
8734 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8735 if (VD->getLanguageLinkage() != CLanguageLinkage)
8736 return false;
8737 QualType QT = VD->getType().getCanonicalType();
8738 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8739 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008740 // The Qualifiers should be attached to the type rather than the array.
8741 // Thus we don't call appendQualifier() here.
8742 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008743 }
8744 return appendType(Enc, QT, CGM, TSC);
8745 }
8746 return false;
8747}
8748
8749
Robert Lytton0e076492013-08-13 09:43:10 +00008750//===----------------------------------------------------------------------===//
8751// Driver code
8752//===----------------------------------------------------------------------===//
8753
Rafael Espindola9f834732014-09-19 01:54:22 +00008754bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008755 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008756}
8757
Chris Lattner2b037972010-07-29 02:01:43 +00008758const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008759 if (TheTargetCodeGenInfo)
8760 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008761
Reid Kleckner9305fd12016-04-13 23:37:17 +00008762 // Helper to set the unique_ptr while still keeping the return value.
8763 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8764 this->TheTargetCodeGenInfo.reset(P);
8765 return *P;
8766 };
8767
John McCallc8e01702013-04-16 22:48:15 +00008768 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008769 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008770 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008771 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008772
Derek Schuff09338a22012-09-06 17:37:28 +00008773 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008774 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008775 case llvm::Triple::mips:
8776 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008777 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008778 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8779 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008780
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008781 case llvm::Triple::mips64:
8782 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008783 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008784
Dylan McKaye8232d72017-02-08 05:09:26 +00008785 case llvm::Triple::avr:
8786 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8787
Tim Northover25e8a672014-05-24 12:51:25 +00008788 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008789 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008790 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008791 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008792 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008793 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008794 return SetCGInfo(
8795 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008796
Reid Kleckner9305fd12016-04-13 23:37:17 +00008797 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008798 }
8799
Dan Gohmanc2853072015-09-03 22:51:53 +00008800 case llvm::Triple::wasm32:
8801 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008802 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008803
Daniel Dunbard59655c2009-09-12 00:59:49 +00008804 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008805 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008806 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008807 case llvm::Triple::thumbeb: {
8808 if (Triple.getOS() == llvm::Triple::Win32) {
8809 return SetCGInfo(
8810 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008811 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008812
Reid Kleckner9305fd12016-04-13 23:37:17 +00008813 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8814 StringRef ABIStr = getTarget().getABI();
8815 if (ABIStr == "apcs-gnu")
8816 Kind = ARMABIInfo::APCS;
8817 else if (ABIStr == "aapcs16")
8818 Kind = ARMABIInfo::AAPCS16_VFP;
8819 else if (CodeGenOpts.FloatABI == "hard" ||
8820 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008821 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008822 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008823 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008824 Kind = ARMABIInfo::AAPCS_VFP;
8825
8826 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8827 }
8828
John McCallea8d8bb2010-03-11 00:10:12 +00008829 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008830 return SetCGInfo(
8831 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008832 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008833 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008834 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008835 if (getTarget().getABI() == "elfv2")
8836 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008837 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008838 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008839
Hal Finkel415c2a32016-10-02 02:10:45 +00008840 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8841 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008842 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008843 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008844 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008845 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008846 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008847 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008848 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008849 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008850 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008851
Hal Finkel415c2a32016-10-02 02:10:45 +00008852 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8853 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008854 }
John McCallea8d8bb2010-03-11 00:10:12 +00008855
Peter Collingbournec947aae2012-05-20 23:28:41 +00008856 case llvm::Triple::nvptx:
8857 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008858 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008859
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008860 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008861 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008862
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008863 case llvm::Triple::systemz: {
8864 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008865 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008866 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008867
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008868 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008869 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008870 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008871
Eli Friedman33465822011-07-08 23:31:17 +00008872 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008873 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008874 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008875 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008876 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008877
John McCall1fe2a8c2013-06-18 02:46:29 +00008878 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008879 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8880 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8881 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008882 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008883 return SetCGInfo(new X86_32TargetCodeGenInfo(
8884 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8885 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8886 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008887 }
Eli Friedman33465822011-07-08 23:31:17 +00008888 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008889
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008890 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008891 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008892 X86AVXABILevel AVXLevel =
8893 (ABI == "avx512"
8894 ? X86AVXABILevel::AVX512
8895 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008896
Chris Lattner04dc9572010-08-31 16:44:54 +00008897 switch (Triple.getOS()) {
8898 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008899 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008900 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008901 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008902 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008903 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008904 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008905 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008906 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008907 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008908 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008909 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008910 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008911 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008912 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008913 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008914 case llvm::Triple::sparc:
8915 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008916 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008917 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008918 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008919 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008920 case llvm::Triple::spir:
8921 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008922 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008923 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008924}
Yaxun Liuc2a87a02017-10-14 12:23:50 +00008925
8926/// Create an OpenCL kernel for an enqueued block.
8927///
8928/// The kernel has the same function type as the block invoke function. Its
8929/// name is the name of the block invoke function postfixed with "_kernel".
8930/// It simply calls the block invoke function then returns.
8931llvm::Function *
8932TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
8933 llvm::Function *Invoke,
8934 llvm::Value *BlockLiteral) const {
8935 auto *InvokeFT = Invoke->getFunctionType();
8936 llvm::SmallVector<llvm::Type *, 2> ArgTys;
8937 for (auto &P : InvokeFT->params())
8938 ArgTys.push_back(P);
8939 auto &C = CGF.getLLVMContext();
8940 std::string Name = Invoke->getName().str() + "_kernel";
8941 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
8942 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
8943 &CGF.CGM.getModule());
8944 auto IP = CGF.Builder.saveIP();
8945 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
8946 auto &Builder = CGF.Builder;
8947 Builder.SetInsertPoint(BB);
8948 llvm::SmallVector<llvm::Value *, 2> Args;
8949 for (auto &A : F->args())
8950 Args.push_back(&A);
8951 Builder.CreateCall(Invoke, Args);
8952 Builder.CreateRetVoid();
8953 Builder.restoreIP(IP);
8954 return F;
8955}
8956
8957/// Create an OpenCL kernel for an enqueued block.
8958///
8959/// The type of the first argument (the block literal) is the struct type
8960/// of the block literal instead of a pointer type. The first argument
8961/// (block literal) is passed directly by value to the kernel. The kernel
8962/// allocates the same type of struct on stack and stores the block literal
8963/// to it and passes its pointer to the block invoke function. The kernel
8964/// has "enqueued-block" function attribute and kernel argument metadata.
8965llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
8966 CodeGenFunction &CGF, llvm::Function *Invoke,
8967 llvm::Value *BlockLiteral) const {
8968 auto &Builder = CGF.Builder;
8969 auto &C = CGF.getLLVMContext();
8970
8971 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
8972 auto *InvokeFT = Invoke->getFunctionType();
8973 llvm::SmallVector<llvm::Type *, 2> ArgTys;
8974 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
8975 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
8976 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
8977 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
8978 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
8979 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
8980
8981 ArgTys.push_back(BlockTy);
8982 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
8983 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
8984 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
8985 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
8986 AccessQuals.push_back(llvm::MDString::get(C, "none"));
8987 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
8988 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
8989 ArgTys.push_back(InvokeFT->getParamType(I));
8990 ArgTys.push_back(BlockTy);
8991 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
8992 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
8993 AccessQuals.push_back(llvm::MDString::get(C, "none"));
8994 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
8995 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
8996 ArgNames.push_back(
8997 llvm::MDString::get(C, std::string("local_arg") + std::to_string(I)));
8998 }
8999 std::string Name = Invoke->getName().str() + "_kernel";
9000 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9001 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9002 &CGF.CGM.getModule());
9003 F->addFnAttr("enqueued-block");
9004 auto IP = CGF.Builder.saveIP();
9005 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9006 Builder.SetInsertPoint(BB);
9007 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9008 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9009 BlockPtr->setAlignment(BlockAlign);
9010 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9011 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9012 llvm::SmallVector<llvm::Value *, 2> Args;
9013 Args.push_back(Cast);
9014 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9015 Args.push_back(I);
9016 Builder.CreateCall(Invoke, Args);
9017 Builder.CreateRetVoid();
9018 Builder.restoreIP(IP);
9019
9020 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9021 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9022 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9023 F->setMetadata("kernel_arg_base_type",
9024 llvm::MDNode::get(C, ArgBaseTypeNames));
9025 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9026 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9027 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));
9028
9029 return F;
9030}