blob: 10fa2ea322c907bd8cbc9d8d83416ccf9f964f09 [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
John McCall12f23522016-04-04 18:33:08 +000022#include "clang/CodeGen/SwiftCallingConv.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000023#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000024#include "llvm/ADT/StringExtras.h"
Coby Tayree7b49dc92017-08-24 09:07:34 +000025#include "llvm/ADT/StringSwitch.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000026#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000029#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000030#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000031
Anton Korobeynikov244360d2009-06-05 22:08:42 +000032using namespace clang;
33using namespace CodeGen;
34
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000035// Helper for coercing an aggregate argument or return value into an integer
36// array of the same size (including padding) and alignment. This alternate
37// coercion happens only for the RenderScript ABI and can be removed after
38// runtimes that rely on it are no longer supported.
39//
40// RenderScript assumes that the size of the argument / return value in the IR
41// is the same as the size of the corresponding qualified type. This helper
42// coerces the aggregate type into an array of the same size (including
43// padding). This coercion is used in lieu of expansion of struct members or
44// other canonical coercions that return a coerced-type of larger size.
45//
46// Ty - The argument / return value type
47// Context - The associated ASTContext
48// LLVMContext - The associated LLVMContext
49static ABIArgInfo coerceToIntArray(QualType Ty,
50 ASTContext &Context,
51 llvm::LLVMContext &LLVMContext) {
52 // Alignment and Size are measured in bits.
53 const uint64_t Size = Context.getTypeSize(Ty);
54 const uint64_t Alignment = Context.getTypeAlign(Ty);
55 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
56 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
57 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
58}
59
John McCall943fae92010-05-27 06:19:26 +000060static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
61 llvm::Value *Array,
62 llvm::Value *Value,
63 unsigned FirstIndex,
64 unsigned LastIndex) {
65 // Alternatively, we could emit this as a loop in the source.
66 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000067 llvm::Value *Cell =
68 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000069 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000070 }
71}
72
John McCalla1dee5302010-08-22 10:59:02 +000073static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000074 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000075 T->isMemberFunctionPointerType();
76}
77
John McCall7f416cc2015-09-08 08:05:57 +000078ABIArgInfo
79ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
80 llvm::Type *Padding) const {
81 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
82 ByRef, Realign, Padding);
83}
84
85ABIArgInfo
86ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
87 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
88 /*ByRef*/ false, Realign);
89}
90
Charles Davisc7d5c942015-09-17 20:55:33 +000091Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
92 QualType Ty) const {
93 return Address::invalid();
94}
95
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000096ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000097
John McCall12f23522016-04-04 18:33:08 +000098/// Does the given lowering require more than the given number of
99/// registers when expanded?
100///
101/// This is intended to be the basis of a reasonable basic implementation
102/// of should{Pass,Return}IndirectlyForSwift.
103///
104/// For most targets, a limit of four total registers is reasonable; this
105/// limits the amount of code required in order to move around the value
106/// in case it wasn't produced immediately prior to the call by the caller
107/// (or wasn't produced in exactly the right registers) or isn't used
108/// immediately within the callee. But some targets may need to further
109/// limit the register count due to an inability to support that many
110/// return registers.
111static bool occupiesMoreThan(CodeGenTypes &cgt,
112 ArrayRef<llvm::Type*> scalarTypes,
113 unsigned maxAllRegisters) {
114 unsigned intCount = 0, fpCount = 0;
115 for (llvm::Type *type : scalarTypes) {
116 if (type->isPointerTy()) {
117 intCount++;
118 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
119 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
120 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
121 } else {
122 assert(type->isVectorTy() || type->isFloatingPointTy());
123 fpCount++;
124 }
125 }
126
127 return (intCount + fpCount > maxAllRegisters);
128}
129
130bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
131 llvm::Type *eltTy,
132 unsigned numElts) const {
133 // The default implementation of this assumes that the target guarantees
134 // 128-bit SIMD support but nothing more.
135 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
136}
137
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000138static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000139 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000140 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
141 if (!RD)
142 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000143 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000144}
145
146static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000147 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000148 const RecordType *RT = T->getAs<RecordType>();
149 if (!RT)
150 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000151 return getRecordArgABI(RT, CXXABI);
152}
153
Reid Klecknerb1be6832014-11-15 01:41:41 +0000154/// Pass transparent unions as if they were the type of the first element. Sema
155/// should ensure that all elements of the union have the same "machine type".
156static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
157 if (const RecordType *UT = Ty->getAsUnionType()) {
158 const RecordDecl *UD = UT->getDecl();
159 if (UD->hasAttr<TransparentUnionAttr>()) {
160 assert(!UD->field_empty() && "sema created an empty transparent union");
161 return UD->field_begin()->getType();
162 }
163 }
164 return Ty;
165}
166
Mark Lacey3825e832013-10-06 01:33:34 +0000167CGCXXABI &ABIInfo::getCXXABI() const {
168 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000169}
170
Chris Lattner2b037972010-07-29 02:01:43 +0000171ASTContext &ABIInfo::getContext() const {
172 return CGT.getContext();
173}
174
175llvm::LLVMContext &ABIInfo::getVMContext() const {
176 return CGT.getLLVMContext();
177}
178
Micah Villmowdd31ca12012-10-08 16:25:52 +0000179const llvm::DataLayout &ABIInfo::getDataLayout() const {
180 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000181}
182
John McCallc8e01702013-04-16 22:48:15 +0000183const TargetInfo &ABIInfo::getTarget() const {
184 return CGT.getTarget();
185}
Chris Lattner2b037972010-07-29 02:01:43 +0000186
Richard Smithf667ad52017-08-26 01:04:35 +0000187const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
188 return CGT.getCodeGenOpts();
189}
190
191bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000192
Reid Klecknere9f6a712014-10-31 17:10:41 +0000193bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
194 return false;
195}
196
197bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
198 uint64_t Members) const {
199 return false;
200}
201
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000202bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
203 return false;
204}
205
Yaron Kerencdae9412016-01-29 19:38:18 +0000206LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000207 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000208 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000209 switch (TheKind) {
210 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000211 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000212 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000213 Ty->print(OS);
214 else
215 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000216 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000217 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000218 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000219 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000220 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000221 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000222 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000223 case InAlloca:
224 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
225 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000226 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000227 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000228 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000229 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000230 break;
231 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000232 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 break;
John McCallf26e73d2016-03-11 04:30:43 +0000234 case CoerceAndExpand:
235 OS << "CoerceAndExpand Type=";
236 getCoerceAndExpandType()->print(OS);
237 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000238 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000239 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000240}
241
Petar Jovanovic402257b2015-12-04 00:26:47 +0000242// Dynamically round a pointer up to a multiple of the given alignment.
243static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
244 llvm::Value *Ptr,
245 CharUnits Align) {
246 llvm::Value *PtrAsInt = Ptr;
247 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
248 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
249 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
250 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
251 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
252 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
253 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
254 Ptr->getType(),
255 Ptr->getName() + ".aligned");
256 return PtrAsInt;
257}
258
John McCall7f416cc2015-09-08 08:05:57 +0000259/// Emit va_arg for a platform using the common void* representation,
260/// where arguments are simply emitted in an array of slots on the stack.
261///
262/// This version implements the core direct-value passing rules.
263///
264/// \param SlotSize - The size and alignment of a stack slot.
265/// Each argument will be allocated to a multiple of this number of
266/// slots, and all the slots will be aligned to this value.
267/// \param AllowHigherAlign - The slot alignment is not a cap;
268/// an argument type with an alignment greater than the slot size
269/// will be emitted on a higher-alignment address, potentially
270/// leaving one or more empty slots behind as padding. If this
271/// is false, the returned address might be less-aligned than
272/// DirectAlign.
273static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
274 Address VAListAddr,
275 llvm::Type *DirectTy,
276 CharUnits DirectSize,
277 CharUnits DirectAlign,
278 CharUnits SlotSize,
279 bool AllowHigherAlign) {
280 // Cast the element type to i8* if necessary. Some platforms define
281 // va_list as a struct containing an i8* instead of just an i8*.
282 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
283 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
284
285 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
286
287 // If the CC aligns values higher than the slot size, do so if needed.
288 Address Addr = Address::invalid();
289 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000290 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
291 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000292 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000293 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000294 }
295
296 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000297 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000298 llvm::Value *NextPtr =
299 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
300 "argp.next");
301 CGF.Builder.CreateStore(NextPtr, VAListAddr);
302
303 // If the argument is smaller than a slot, and this is a big-endian
304 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000305 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
306 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000307 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
308 }
309
310 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
311 return Addr;
312}
313
314/// Emit va_arg for a platform using the common void* representation,
315/// where arguments are simply emitted in an array of slots on the stack.
316///
317/// \param IsIndirect - Values of this type are passed indirectly.
318/// \param ValueInfo - The size and alignment of this type, generally
319/// computed with getContext().getTypeInfoInChars(ValueTy).
320/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
321/// Each argument will be allocated to a multiple of this number of
322/// slots, and all the slots will be aligned to this value.
323/// \param AllowHigherAlign - The slot alignment is not a cap;
324/// an argument type with an alignment greater than the slot size
325/// will be emitted on a higher-alignment address, potentially
326/// leaving one or more empty slots behind as padding.
327static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
328 QualType ValueTy, bool IsIndirect,
329 std::pair<CharUnits, CharUnits> ValueInfo,
330 CharUnits SlotSizeAndAlign,
331 bool AllowHigherAlign) {
332 // The size and alignment of the value that was passed directly.
333 CharUnits DirectSize, DirectAlign;
334 if (IsIndirect) {
335 DirectSize = CGF.getPointerSize();
336 DirectAlign = CGF.getPointerAlign();
337 } else {
338 DirectSize = ValueInfo.first;
339 DirectAlign = ValueInfo.second;
340 }
341
342 // Cast the address we've calculated to the right type.
343 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
344 if (IsIndirect)
345 DirectTy = DirectTy->getPointerTo(0);
346
347 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
348 DirectSize, DirectAlign,
349 SlotSizeAndAlign,
350 AllowHigherAlign);
351
352 if (IsIndirect) {
353 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
354 }
355
356 return Addr;
357
358}
359
360static Address emitMergePHI(CodeGenFunction &CGF,
361 Address Addr1, llvm::BasicBlock *Block1,
362 Address Addr2, llvm::BasicBlock *Block2,
363 const llvm::Twine &Name = "") {
364 assert(Addr1.getType() == Addr2.getType());
365 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
366 PHI->addIncoming(Addr1.getPointer(), Block1);
367 PHI->addIncoming(Addr2.getPointer(), Block2);
368 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
369 return Address(PHI, Align);
370}
371
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000372TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
373
John McCall3480ef22011-08-30 01:42:09 +0000374// If someone can figure out a general rule for this, that would be great.
375// It's probably just doomed to be platform-dependent, though.
376unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
377 // Verified for:
378 // x86-64 FreeBSD, Linux, Darwin
379 // x86-32 FreeBSD, Linux, Darwin
380 // PowerPC Linux, Darwin
381 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000382 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000383 return 32;
384}
385
John McCalla729c622012-02-17 03:33:10 +0000386bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
387 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000388 // The following conventions are known to require this to be false:
389 // x86_stdcall
390 // MIPS
391 // For everything else, we just prefer false unless we opt out.
392 return false;
393}
394
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000395void
396TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
397 llvm::SmallString<24> &Opt) const {
398 // This assumes the user is passing a library name like "rt" instead of a
399 // filename like "librt.a/so", and that they don't care whether it's static or
400 // dynamic.
401 Opt = "-l";
402 Opt += Lib;
403}
404
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000405unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000406 // OpenCL kernels are called via an explicit runtime API with arguments
407 // set with clSetKernelArg(), not as normal sub-functions.
408 // Return SPIR_KERNEL by default as the kernel calling convention to
409 // ensure the fingerprint is fixed such way that each OpenCL argument
410 // gets one matching argument in the produced kernel function argument
411 // list to enable feasible implementation of clSetKernelArg() with
412 // aggregates etc. In case we would use the default C calling conv here,
413 // clSetKernelArg() might break depending on the target-specific
414 // conventions; different targets might split structs passed as values
415 // to multiple function arguments etc.
416 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000417}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000418
Yaxun Liu402804b2016-12-15 08:09:08 +0000419llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
420 llvm::PointerType *T, QualType QT) const {
421 return llvm::ConstantPointerNull::get(T);
422}
423
Yaxun Liucbf647c2017-07-08 13:24:52 +0000424unsigned TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
425 const VarDecl *D) const {
426 assert(!CGM.getLangOpts().OpenCL &&
427 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
428 "Address space agnostic languages only");
Yaxun Liu7bce6422017-07-08 19:13:41 +0000429 return D ? D->getType().getAddressSpace()
430 : static_cast<unsigned>(LangAS::Default);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000431}
432
Yaxun Liu402804b2016-12-15 08:09:08 +0000433llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000434 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
435 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000436 // Since target may map different address spaces in AST to the same address
437 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000438 if (auto *C = dyn_cast<llvm::Constant>(Src))
439 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000440 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000441}
442
Yaxun Liucbf647c2017-07-08 13:24:52 +0000443llvm::Constant *
444TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
445 unsigned SrcAddr, unsigned DestAddr,
446 llvm::Type *DestTy) const {
447 // Since target may map different address spaces in AST to the same address
448 // space, an address space conversion may end up as a bitcast.
449 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
450}
451
Yaxun Liu39195062017-08-04 18:16:31 +0000452llvm::SyncScope::ID
453TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
454 return C.getOrInsertSyncScopeID(""); /* default sync scope */
455}
456
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000457static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000458
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000459/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000460/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000461static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
462 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000463 if (FD->isUnnamedBitfield())
464 return true;
465
466 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000467
Eli Friedman0b3f2012011-11-18 03:47:20 +0000468 // Constant arrays of empty records count as empty, strip them off.
469 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000470 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000471 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
472 if (AT->getSize() == 0)
473 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000474 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000475 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000476
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000477 const RecordType *RT = FT->getAs<RecordType>();
478 if (!RT)
479 return false;
480
481 // C++ record fields are never empty, at least in the Itanium ABI.
482 //
483 // FIXME: We should use a predicate for whether this behavior is true in the
484 // current ABI.
485 if (isa<CXXRecordDecl>(RT->getDecl()))
486 return false;
487
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000488 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000489}
490
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000491/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000492/// fields. Note that a structure with a flexible array member is not
493/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000494static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000495 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000496 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000497 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000498 const RecordDecl *RD = RT->getDecl();
499 if (RD->hasFlexibleArrayMember())
500 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000501
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000502 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000503 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000504 for (const auto &I : CXXRD->bases())
505 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000506 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000507
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000508 for (const auto *I : RD->fields())
509 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000510 return false;
511 return true;
512}
513
514/// isSingleElementStruct - Determine if a structure is a "single
515/// element struct", i.e. it has exactly one non-empty field or
516/// exactly one field which is itself a single element
517/// struct. Structures with flexible array members are never
518/// considered single element structs.
519///
520/// \return The field declaration for the single non-empty field, if
521/// it exists.
522static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000523 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000524 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000525 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000526
527 const RecordDecl *RD = RT->getDecl();
528 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000529 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000530
Craig Topper8a13c412014-05-21 05:09:00 +0000531 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000532
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000533 // If this is a C++ record, check the bases first.
534 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000535 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000536 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000537 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000538 continue;
539
540 // If we already found an element then this isn't a single-element struct.
541 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000542 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000543
544 // If this is non-empty and not a single element struct, the composite
545 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000546 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000547 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000548 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000549 }
550 }
551
552 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000553 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000554 QualType FT = FD->getType();
555
556 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000557 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000558 continue;
559
560 // If we already found an element then this isn't a single-element
561 // struct.
562 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000563 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000564
565 // Treat single element arrays as the element.
566 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
567 if (AT->getSize().getZExtValue() != 1)
568 break;
569 FT = AT->getElementType();
570 }
571
John McCalla1dee5302010-08-22 10:59:02 +0000572 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000573 Found = FT.getTypePtr();
574 } else {
575 Found = isSingleElementStruct(FT, Context);
576 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000577 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000578 }
579 }
580
Eli Friedmanee945342011-11-18 01:25:50 +0000581 // We don't consider a struct a single-element struct if it has
582 // padding beyond the element type.
583 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000584 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000585
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000586 return Found;
587}
588
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000589namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000590Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
591 const ABIArgInfo &AI) {
592 // This default implementation defers to the llvm backend's va_arg
593 // instruction. It can handle only passing arguments directly
594 // (typically only handled in the backend for primitive types), or
595 // aggregates passed indirectly by pointer (NOTE: if the "byval"
596 // flag has ABI impact in the callee, this implementation cannot
597 // work.)
598
599 // Only a few cases are covered here at the moment -- those needed
600 // by the default abi.
601 llvm::Value *Val;
602
603 if (AI.isIndirect()) {
604 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000605 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000606 assert(
607 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000608 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000609
610 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
611 CharUnits TyAlignForABI = TyInfo.second;
612
613 llvm::Type *BaseTy =
614 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
615 llvm::Value *Addr =
616 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
617 return Address(Addr, TyAlignForABI);
618 } else {
619 assert((AI.isDirect() || AI.isExtend()) &&
620 "Unexpected ArgInfo Kind in generic VAArg emitter!");
621
622 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000623 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000624 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000625 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000626 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000627 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000628 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000629 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000630
631 Address Temp = CGF.CreateMemTemp(Ty, "varet");
632 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
633 CGF.Builder.CreateStore(Val, Temp);
634 return Temp;
635 }
636}
637
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000638/// DefaultABIInfo - The default implementation for ABI specific
639/// details. This implementation provides information which results in
640/// self-consistent and sensible LLVM IR generation, but does not
641/// conform to any particular ABI.
642class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000643public:
644 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000645
Chris Lattner458b2aa2010-07-29 02:16:43 +0000646 ABIArgInfo classifyReturnType(QualType RetTy) const;
647 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000648
Craig Topper4f12f102014-03-12 06:41:41 +0000649 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000650 if (!getCXXABI().classifyReturnType(FI))
651 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000652 for (auto &I : FI.arguments())
653 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000654 }
655
John McCall7f416cc2015-09-08 08:05:57 +0000656 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000657 QualType Ty) const override {
658 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
659 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000660};
661
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000662class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
663public:
Chris Lattner2b037972010-07-29 02:01:43 +0000664 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
665 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000666};
667
Chris Lattner458b2aa2010-07-29 02:16:43 +0000668ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000669 Ty = useFirstFieldIfTransparentUnion(Ty);
670
671 if (isAggregateTypeForABI(Ty)) {
672 // Records with non-trivial destructors/copy-constructors should not be
673 // passed by value.
674 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000675 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000676
John McCall7f416cc2015-09-08 08:05:57 +0000677 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000678 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000679
Chris Lattner9723d6c2010-03-11 18:19:55 +0000680 // Treat an enum type as its underlying type.
681 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
682 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000683
Chris Lattner9723d6c2010-03-11 18:19:55 +0000684 return (Ty->isPromotableIntegerType() ?
685 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000686}
687
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000688ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
689 if (RetTy->isVoidType())
690 return ABIArgInfo::getIgnore();
691
692 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000693 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000694
695 // Treat an enum type as its underlying type.
696 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
697 RetTy = EnumTy->getDecl()->getIntegerType();
698
699 return (RetTy->isPromotableIntegerType() ?
700 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
701}
702
Derek Schuff09338a22012-09-06 17:37:28 +0000703//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000704// WebAssembly ABI Implementation
705//
706// This is a very simple ABI that relies a lot on DefaultABIInfo.
707//===----------------------------------------------------------------------===//
708
709class WebAssemblyABIInfo final : public DefaultABIInfo {
710public:
711 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
712 : DefaultABIInfo(CGT) {}
713
714private:
715 ABIArgInfo classifyReturnType(QualType RetTy) const;
716 ABIArgInfo classifyArgumentType(QualType Ty) const;
717
718 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000719 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000720 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000721 void computeInfo(CGFunctionInfo &FI) const override {
722 if (!getCXXABI().classifyReturnType(FI))
723 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
724 for (auto &Arg : FI.arguments())
725 Arg.info = classifyArgumentType(Arg.type);
726 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000727
728 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
729 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000730};
731
732class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
733public:
734 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
735 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
736};
737
738/// \brief Classify argument of given type \p Ty.
739ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
740 Ty = useFirstFieldIfTransparentUnion(Ty);
741
742 if (isAggregateTypeForABI(Ty)) {
743 // Records with non-trivial destructors/copy-constructors should not be
744 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000745 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000746 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000747 // Ignore empty structs/unions.
748 if (isEmptyRecord(getContext(), Ty, true))
749 return ABIArgInfo::getIgnore();
750 // Lower single-element structs to just pass a regular value. TODO: We
751 // could do reasonable-size multiple-element structs too, using getExpand(),
752 // though watch out for things like bitfields.
753 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
754 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000755 }
756
757 // Otherwise just do the default thing.
758 return DefaultABIInfo::classifyArgumentType(Ty);
759}
760
761ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
762 if (isAggregateTypeForABI(RetTy)) {
763 // Records with non-trivial destructors/copy-constructors should not be
764 // returned by value.
765 if (!getRecordArgABI(RetTy, getCXXABI())) {
766 // Ignore empty structs/unions.
767 if (isEmptyRecord(getContext(), RetTy, true))
768 return ABIArgInfo::getIgnore();
769 // Lower single-element structs to just return a regular value. TODO: We
770 // could do reasonable-size multiple-element structs too, using
771 // ABIArgInfo::getDirect().
772 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
773 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
774 }
775 }
776
777 // Otherwise just do the default thing.
778 return DefaultABIInfo::classifyReturnType(RetTy);
779}
780
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000781Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
782 QualType Ty) const {
783 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
784 getContext().getTypeInfoInChars(Ty),
785 CharUnits::fromQuantity(4),
786 /*AllowHigherAlign=*/ true);
787}
788
Dan Gohmanc2853072015-09-03 22:51:53 +0000789//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000790// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000791//
792// This is a simplified version of the x86_32 ABI. Arguments and return values
793// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000794//===----------------------------------------------------------------------===//
795
796class PNaClABIInfo : public ABIInfo {
797 public:
798 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
799
800 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000801 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000802
Craig Topper4f12f102014-03-12 06:41:41 +0000803 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000804 Address EmitVAArg(CodeGenFunction &CGF,
805 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000806};
807
808class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
809 public:
810 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
811 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
812};
813
814void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000815 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000816 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
817
Reid Kleckner40ca9132014-05-13 22:05:45 +0000818 for (auto &I : FI.arguments())
819 I.info = classifyArgumentType(I.type);
820}
Derek Schuff09338a22012-09-06 17:37:28 +0000821
John McCall7f416cc2015-09-08 08:05:57 +0000822Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
823 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000824 // The PNaCL ABI is a bit odd, in that varargs don't use normal
825 // function classification. Structs get passed directly for varargs
826 // functions, through a rewriting transform in
827 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
828 // this target to actually support a va_arg instructions with an
829 // aggregate type, unlike other targets.
830 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000831}
832
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000833/// \brief Classify argument of given type \p Ty.
834ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000835 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000836 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000837 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
838 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000839 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
840 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000841 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000842 } else if (Ty->isFloatingType()) {
843 // Floating-point types don't go inreg.
844 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000845 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000846
847 return (Ty->isPromotableIntegerType() ?
848 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000849}
850
851ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
852 if (RetTy->isVoidType())
853 return ABIArgInfo::getIgnore();
854
Eli Benderskye20dad62013-04-04 22:49:35 +0000855 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000856 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000857 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000858
859 // Treat an enum type as its underlying type.
860 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
861 RetTy = EnumTy->getDecl()->getIntegerType();
862
863 return (RetTy->isPromotableIntegerType() ?
864 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
865}
866
Chad Rosier651c1832013-03-25 21:00:27 +0000867/// IsX86_MMXType - Return true if this is an MMX type.
868bool IsX86_MMXType(llvm::Type *IRType) {
869 // 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 +0000870 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
871 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
872 IRType->getScalarSizeInBits() != 64;
873}
874
Jay Foad7c57be32011-07-11 09:56:20 +0000875static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000876 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000877 llvm::Type* Ty) {
Coby Tayree7b49dc92017-08-24 09:07:34 +0000878 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
879 .Cases("y", "&y", "^Ym", true)
880 .Default(false);
881 if (IsMMXCons && Ty->isVectorTy()) {
Tim Northover0ae93912013-06-07 00:04:50 +0000882 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
883 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000884 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000885 }
886
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000887 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000888 }
889
890 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000891 return Ty;
892}
893
Reid Kleckner80944df2014-10-31 22:00:51 +0000894/// Returns true if this type can be passed in SSE registers with the
895/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
896static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
897 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000898 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
899 if (BT->getKind() == BuiltinType::LongDouble) {
900 if (&Context.getTargetInfo().getLongDoubleFormat() ==
901 &llvm::APFloat::x87DoubleExtended())
902 return false;
903 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000904 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000905 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000906 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
907 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
908 // registers specially.
909 unsigned VecSize = Context.getTypeSize(VT);
910 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
911 return true;
912 }
913 return false;
914}
915
916/// Returns true if this aggregate is small enough to be passed in SSE registers
917/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
918static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
919 return NumMembers <= 4;
920}
921
Erich Keane521ed962017-01-05 00:20:51 +0000922/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
923static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
924 auto AI = ABIArgInfo::getDirect(T);
925 AI.setInReg(true);
926 AI.setCanBeFlattened(false);
927 return AI;
928}
929
Chris Lattner0cf24192010-06-28 20:05:43 +0000930//===----------------------------------------------------------------------===//
931// X86-32 ABI Implementation
932//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000933
Reid Kleckner661f35b2014-01-18 01:12:41 +0000934/// \brief Similar to llvm::CCState, but for Clang.
935struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000936 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000937
938 unsigned CC;
939 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000940 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000941};
942
Erich Keane521ed962017-01-05 00:20:51 +0000943enum {
944 // Vectorcall only allows the first 6 parameters to be passed in registers.
945 VectorcallMaxParamNumAsReg = 6
946};
947
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000948/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000949class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000950 enum Class {
951 Integer,
952 Float
953 };
954
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000955 static const unsigned MinABIStackAlignInBytes = 4;
956
David Chisnallde3a0692009-08-17 23:08:21 +0000957 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000958 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000959 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000960 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000961 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000962 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000963
964 static bool isRegisterSize(unsigned Size) {
965 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
966 }
967
Reid Kleckner80944df2014-10-31 22:00:51 +0000968 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
969 // FIXME: Assumes vectorcall is in use.
970 return isX86VectorTypeForVectorCall(getContext(), Ty);
971 }
972
973 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
974 uint64_t NumMembers) const override {
975 // FIXME: Assumes vectorcall is in use.
976 return isX86VectorCallAggregateSmallEnough(NumMembers);
977 }
978
Reid Kleckner40ca9132014-05-13 22:05:45 +0000979 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980
Daniel Dunbar557893d2010-04-21 19:10:51 +0000981 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
982 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000983 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
984
John McCall7f416cc2015-09-08 08:05:57 +0000985 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000986
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000987 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000988 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000989
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000990 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000991 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000992 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +0000993
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000994 /// \brief Updates the number of available free registers, returns
995 /// true if any registers were allocated.
996 bool updateFreeRegs(QualType Ty, CCState &State) const;
997
998 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
999 bool &NeedsPadding) const;
1000 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001001
Reid Kleckner04046052016-05-02 17:41:07 +00001002 bool canExpandIndirectArgument(QualType Ty) const;
1003
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001004 /// \brief Rewrite the function info so that all memory arguments use
1005 /// inalloca.
1006 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1007
1008 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001009 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001010 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +00001011 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1012 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001013
Rafael Espindola75419dc2012-07-23 23:30:29 +00001014public:
1015
Craig Topper4f12f102014-03-12 06:41:41 +00001016 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001017 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1018 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001019
Michael Kupersteindc745202015-10-19 07:52:25 +00001020 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1021 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001022 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001023 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001024 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1025 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001026 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001027 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001028 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001029
1030 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1031 ArrayRef<llvm::Type*> scalars,
1032 bool asReturnValue) const override {
1033 // LLVM's x86-32 lowering currently only assigns up to three
1034 // integer registers and three fp registers. Oddly, it'll use up to
1035 // four vector registers for vectors, but those can overlap with the
1036 // scalar registers.
1037 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1038 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001039
1040 bool isSwiftErrorInRegister() const override {
1041 // x86-32 lowering does not support passing swifterror in a register.
1042 return false;
1043 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001044};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001045
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001046class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1047public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001048 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1049 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001050 unsigned NumRegisterParameters, bool SoftFloatABI)
1051 : TargetCodeGenInfo(new X86_32ABIInfo(
1052 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1053 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001054
John McCall1fe2a8c2013-06-18 02:46:29 +00001055 static bool isStructReturnInRegABI(
1056 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1057
Eric Christopher162c91c2015-06-05 22:03:00 +00001058 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001059 CodeGen::CodeGenModule &CGM,
1060 ForDefinition_t IsForDefinition) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001061
Craig Topper4f12f102014-03-12 06:41:41 +00001062 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001063 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001064 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001065 return 4;
1066 }
1067
1068 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001069 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001070
Jay Foad7c57be32011-07-11 09:56:20 +00001071 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001072 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001073 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001074 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1075 }
1076
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001077 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1078 std::string &Constraints,
1079 std::vector<llvm::Type *> &ResultRegTypes,
1080 std::vector<llvm::Type *> &ResultTruncRegTypes,
1081 std::vector<LValue> &ResultRegDests,
1082 std::string &AsmString,
1083 unsigned NumOutputs) const override;
1084
Craig Topper4f12f102014-03-12 06:41:41 +00001085 llvm::Constant *
1086 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001087 unsigned Sig = (0xeb << 0) | // jmp rel8
1088 (0x06 << 8) | // .+0x08
1089 ('F' << 16) |
1090 ('T' << 24);
1091 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1092 }
John McCall01391782016-02-05 21:37:38 +00001093
1094 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1095 return "movl\t%ebp, %ebp"
Oliver Stannard7f188642017-08-21 09:54:46 +00001096 "\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall01391782016-02-05 21:37:38 +00001097 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001098};
1099
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001100}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001102/// Rewrite input constraint references after adding some output constraints.
1103/// In the case where there is one output and one input and we add one output,
1104/// we need to replace all operand references greater than or equal to 1:
1105/// mov $0, $1
1106/// mov eax, $1
1107/// The result will be:
1108/// mov $0, $2
1109/// mov eax, $2
1110static void rewriteInputConstraintReferences(unsigned FirstIn,
1111 unsigned NumNewOuts,
1112 std::string &AsmString) {
1113 std::string Buf;
1114 llvm::raw_string_ostream OS(Buf);
1115 size_t Pos = 0;
1116 while (Pos < AsmString.size()) {
1117 size_t DollarStart = AsmString.find('$', Pos);
1118 if (DollarStart == std::string::npos)
1119 DollarStart = AsmString.size();
1120 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1121 if (DollarEnd == std::string::npos)
1122 DollarEnd = AsmString.size();
1123 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1124 Pos = DollarEnd;
1125 size_t NumDollars = DollarEnd - DollarStart;
1126 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1127 // We have an operand reference.
1128 size_t DigitStart = Pos;
1129 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1130 if (DigitEnd == std::string::npos)
1131 DigitEnd = AsmString.size();
1132 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1133 unsigned OperandIndex;
1134 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1135 if (OperandIndex >= FirstIn)
1136 OperandIndex += NumNewOuts;
1137 OS << OperandIndex;
1138 } else {
1139 OS << OperandStr;
1140 }
1141 Pos = DigitEnd;
1142 }
1143 }
1144 AsmString = std::move(OS.str());
1145}
1146
1147/// Add output constraints for EAX:EDX because they are return registers.
1148void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1149 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1150 std::vector<llvm::Type *> &ResultRegTypes,
1151 std::vector<llvm::Type *> &ResultTruncRegTypes,
1152 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1153 unsigned NumOutputs) const {
1154 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1155
1156 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1157 // larger.
1158 if (!Constraints.empty())
1159 Constraints += ',';
1160 if (RetWidth <= 32) {
1161 Constraints += "={eax}";
1162 ResultRegTypes.push_back(CGF.Int32Ty);
1163 } else {
1164 // Use the 'A' constraint for EAX:EDX.
1165 Constraints += "=A";
1166 ResultRegTypes.push_back(CGF.Int64Ty);
1167 }
1168
1169 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1170 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1171 ResultTruncRegTypes.push_back(CoerceTy);
1172
1173 // Coerce the integer by bitcasting the return slot pointer.
1174 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1175 CoerceTy->getPointerTo()));
1176 ResultRegDests.push_back(ReturnSlot);
1177
1178 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1179}
1180
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001182/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001183bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1184 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001185 uint64_t Size = Context.getTypeSize(Ty);
1186
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001187 // For i386, type must be register sized.
1188 // For the MCU ABI, it only needs to be <= 8-byte
1189 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1190 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001191
1192 if (Ty->isVectorType()) {
1193 // 64- and 128- bit vectors inside structures are not returned in
1194 // registers.
1195 if (Size == 64 || Size == 128)
1196 return false;
1197
1198 return true;
1199 }
1200
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001201 // If this is a builtin, pointer, enum, complex type, member pointer, or
1202 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001203 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001204 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001205 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001206 return true;
1207
1208 // Arrays are treated like records.
1209 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001210 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001211
1212 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001213 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001214 if (!RT) return false;
1215
Anders Carlsson40446e82010-01-27 03:25:19 +00001216 // FIXME: Traverse bases here too.
1217
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001218 // Structure types are passed in register if all fields would be
1219 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001220 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001221 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001222 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001223 continue;
1224
1225 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001226 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001227 return false;
1228 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001229 return true;
1230}
1231
Reid Kleckner04046052016-05-02 17:41:07 +00001232static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1233 // Treat complex types as the element type.
1234 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1235 Ty = CTy->getElementType();
1236
1237 // Check for a type which we know has a simple scalar argument-passing
1238 // convention without any padding. (We're specifically looking for 32
1239 // and 64-bit integer and integer-equivalents, float, and double.)
1240 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1241 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1242 return false;
1243
1244 uint64_t Size = Context.getTypeSize(Ty);
1245 return Size == 32 || Size == 64;
1246}
1247
Reid Kleckner791bbf62017-01-13 17:18:19 +00001248static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1249 uint64_t &Size) {
1250 for (const auto *FD : RD->fields()) {
1251 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1252 // argument is smaller than 32-bits, expanding the struct will create
1253 // alignment padding.
1254 if (!is32Or64BitBasicType(FD->getType(), Context))
1255 return false;
1256
1257 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1258 // how to expand them yet, and the predicate for telling if a bitfield still
1259 // counts as "basic" is more complicated than what we were doing previously.
1260 if (FD->isBitField())
1261 return false;
1262
1263 Size += Context.getTypeSize(FD->getType());
1264 }
1265 return true;
1266}
1267
1268static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1269 uint64_t &Size) {
1270 // Don't do this if there are any non-empty bases.
1271 for (const CXXBaseSpecifier &Base : RD->bases()) {
1272 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1273 Size))
1274 return false;
1275 }
1276 if (!addFieldSizes(Context, RD, Size))
1277 return false;
1278 return true;
1279}
1280
Reid Kleckner04046052016-05-02 17:41:07 +00001281/// Test whether an argument type which is to be passed indirectly (on the
1282/// stack) would have the equivalent layout if it was expanded into separate
1283/// arguments. If so, we prefer to do the latter to avoid inhibiting
1284/// optimizations.
1285bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1286 // We can only expand structure types.
1287 const RecordType *RT = Ty->getAs<RecordType>();
1288 if (!RT)
1289 return false;
1290 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001291 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001292 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001293 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001294 // On non-Windows, we have to conservatively match our old bitcode
1295 // prototypes in order to be ABI-compatible at the bitcode level.
1296 if (!CXXRD->isCLike())
1297 return false;
1298 } else {
1299 // Don't do this for dynamic classes.
1300 if (CXXRD->isDynamicClass())
1301 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001302 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001303 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001304 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001305 } else {
1306 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001307 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001308 }
1309
1310 // We can do this if there was no alignment padding.
1311 return Size == getContext().getTypeSize(Ty);
1312}
1313
John McCall7f416cc2015-09-08 08:05:57 +00001314ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001315 // If the return value is indirect, then the hidden argument is consuming one
1316 // integer register.
1317 if (State.FreeRegs) {
1318 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001319 if (!IsMCUABI)
1320 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001321 }
John McCall7f416cc2015-09-08 08:05:57 +00001322 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001323}
1324
Eric Christopher7565e0d2015-05-29 23:09:49 +00001325ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1326 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001327 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001328 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001329
Reid Kleckner80944df2014-10-31 22:00:51 +00001330 const Type *Base = nullptr;
1331 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001332 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1333 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001334 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1335 // The LLVM struct type for such an aggregate should lower properly.
1336 return ABIArgInfo::getDirect();
1337 }
1338
Chris Lattner458b2aa2010-07-29 02:16:43 +00001339 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001340 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001341 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001342 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001343
1344 // 128-bit vectors are a special case; they are returned in
1345 // registers and we need to make sure to pick a type the LLVM
1346 // backend will like.
1347 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001348 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001349 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001350
1351 // Always return in register if it fits in a general purpose
1352 // register, or if it is 64 bits and has a single element.
1353 if ((Size == 8 || Size == 16 || Size == 32) ||
1354 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001355 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001356 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001357
John McCall7f416cc2015-09-08 08:05:57 +00001358 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001359 }
1360
1361 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001362 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001363
John McCalla1dee5302010-08-22 10:59:02 +00001364 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001365 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001366 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001367 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001368 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001369 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001370
David Chisnallde3a0692009-08-17 23:08:21 +00001371 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001372 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001373 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001374
Denis Zobnin380b2242016-02-11 11:26:03 +00001375 // Ignore empty structs/unions.
1376 if (isEmptyRecord(getContext(), RetTy, true))
1377 return ABIArgInfo::getIgnore();
1378
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001379 // Small structures which are register sized are generally returned
1380 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001381 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001382 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001383
1384 // As a special-case, if the struct is a "single-element" struct, and
1385 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001386 // floating-point register. (MSVC does not apply this special case.)
1387 // We apply a similar transformation for pointer types to improve the
1388 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001389 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001390 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001391 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001392 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1393
1394 // FIXME: We should be able to narrow this integer in cases with dead
1395 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001396 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001397 }
1398
John McCall7f416cc2015-09-08 08:05:57 +00001399 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001400 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001401
Chris Lattner458b2aa2010-07-29 02:16:43 +00001402 // Treat an enum type as its underlying type.
1403 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1404 RetTy = EnumTy->getDecl()->getIntegerType();
1405
1406 return (RetTy->isPromotableIntegerType() ?
1407 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001408}
1409
Eli Friedman7919bea2012-06-05 19:40:46 +00001410static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1411 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1412}
1413
Daniel Dunbared23de32010-09-16 20:42:00 +00001414static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1415 const RecordType *RT = Ty->getAs<RecordType>();
1416 if (!RT)
1417 return 0;
1418 const RecordDecl *RD = RT->getDecl();
1419
1420 // If this is a C++ record, check the bases first.
1421 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001422 for (const auto &I : CXXRD->bases())
1423 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001424 return false;
1425
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001426 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001427 QualType FT = i->getType();
1428
Eli Friedman7919bea2012-06-05 19:40:46 +00001429 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001430 return true;
1431
1432 if (isRecordWithSSEVectorType(Context, FT))
1433 return true;
1434 }
1435
1436 return false;
1437}
1438
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001439unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1440 unsigned Align) const {
1441 // Otherwise, if the alignment is less than or equal to the minimum ABI
1442 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001443 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001444 return 0; // Use default alignment.
1445
1446 // On non-Darwin, the stack type alignment is always 4.
1447 if (!IsDarwinVectorABI) {
1448 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001449 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001450 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001451
Daniel Dunbared23de32010-09-16 20:42:00 +00001452 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001453 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1454 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001455 return 16;
1456
1457 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001458}
1459
Rafael Espindola703c47f2012-10-19 05:04:37 +00001460ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001461 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001462 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001463 if (State.FreeRegs) {
1464 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001465 if (!IsMCUABI)
1466 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001467 }
John McCall7f416cc2015-09-08 08:05:57 +00001468 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001469 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001470
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001471 // Compute the byval alignment.
1472 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1473 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1474 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001475 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001476
1477 // If the stack alignment is less than the type alignment, realign the
1478 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001479 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001480 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1481 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001482}
1483
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001484X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1485 const Type *T = isSingleElementStruct(Ty, getContext());
1486 if (!T)
1487 T = Ty.getTypePtr();
1488
1489 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1490 BuiltinType::Kind K = BT->getKind();
1491 if (K == BuiltinType::Float || K == BuiltinType::Double)
1492 return Float;
1493 }
1494 return Integer;
1495}
1496
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001497bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001498 if (!IsSoftFloatABI) {
1499 Class C = classify(Ty);
1500 if (C == Float)
1501 return false;
1502 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001503
Rafael Espindola077dd592012-10-24 01:58:58 +00001504 unsigned Size = getContext().getTypeSize(Ty);
1505 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001506
1507 if (SizeInRegs == 0)
1508 return false;
1509
Michael Kuperstein68901882015-10-25 08:18:20 +00001510 if (!IsMCUABI) {
1511 if (SizeInRegs > State.FreeRegs) {
1512 State.FreeRegs = 0;
1513 return false;
1514 }
1515 } else {
1516 // The MCU psABI allows passing parameters in-reg even if there are
1517 // earlier parameters that are passed on the stack. Also,
1518 // it does not allow passing >8-byte structs in-register,
1519 // even if there are 3 free registers available.
1520 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1521 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001522 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001523
Reid Kleckner661f35b2014-01-18 01:12:41 +00001524 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001525 return true;
1526}
1527
1528bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1529 bool &InReg,
1530 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001531 // On Windows, aggregates other than HFAs are never passed in registers, and
1532 // they do not consume register slots. Homogenous floating-point aggregates
1533 // (HFAs) have already been dealt with at this point.
1534 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1535 return false;
1536
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001537 NeedsPadding = false;
1538 InReg = !IsMCUABI;
1539
1540 if (!updateFreeRegs(Ty, State))
1541 return false;
1542
1543 if (IsMCUABI)
1544 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001545
Reid Kleckner80944df2014-10-31 22:00:51 +00001546 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001547 State.CC == llvm::CallingConv::X86_VectorCall ||
1548 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001549 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001550 NeedsPadding = true;
1551
Rafael Espindola077dd592012-10-24 01:58:58 +00001552 return false;
1553 }
1554
Rafael Espindola703c47f2012-10-19 05:04:37 +00001555 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001556}
1557
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001558bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1559 if (!updateFreeRegs(Ty, State))
1560 return false;
1561
1562 if (IsMCUABI)
1563 return false;
1564
1565 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001566 State.CC == llvm::CallingConv::X86_VectorCall ||
1567 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001568 if (getContext().getTypeSize(Ty) > 32)
1569 return false;
1570
1571 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1572 Ty->isReferenceType());
1573 }
1574
1575 return true;
1576}
1577
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001578ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1579 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001580 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001581
Reid Klecknerb1be6832014-11-15 01:41:41 +00001582 Ty = useFirstFieldIfTransparentUnion(Ty);
1583
Reid Kleckner80944df2014-10-31 22:00:51 +00001584 // Check with the C++ ABI first.
1585 const RecordType *RT = Ty->getAs<RecordType>();
1586 if (RT) {
1587 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1588 if (RAA == CGCXXABI::RAA_Indirect) {
1589 return getIndirectResult(Ty, false, State);
1590 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1591 // The field index doesn't matter, we'll fix it up later.
1592 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1593 }
1594 }
1595
Erich Keane4bd39302017-06-21 16:37:22 +00001596 // Regcall uses the concept of a homogenous vector aggregate, similar
1597 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001598 const Type *Base = nullptr;
1599 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001600 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001601 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001602
Erich Keane4bd39302017-06-21 16:37:22 +00001603 if (State.FreeSSERegs >= NumElts) {
1604 State.FreeSSERegs -= NumElts;
1605 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001606 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001607 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001608 }
Erich Keane4bd39302017-06-21 16:37:22 +00001609 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001610 }
1611
1612 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001613 // Structures with flexible arrays are always indirect.
1614 // FIXME: This should not be byval!
1615 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1616 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001617
Reid Kleckner04046052016-05-02 17:41:07 +00001618 // Ignore empty structs/unions on non-Windows.
1619 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001620 return ABIArgInfo::getIgnore();
1621
Rafael Espindolafad28de2012-10-24 01:59:00 +00001622 llvm::LLVMContext &LLVMContext = getVMContext();
1623 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001624 bool NeedsPadding = false;
1625 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001626 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001627 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001628 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001629 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001630 if (InReg)
1631 return ABIArgInfo::getDirectInReg(Result);
1632 else
1633 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001634 }
Craig Topper8a13c412014-05-21 05:09:00 +00001635 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001636
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001637 // Expand small (<= 128-bit) record types when we know that the stack layout
1638 // of those arguments will match the struct. This is important because the
1639 // LLVM backend isn't smart enough to remove byval, which inhibits many
1640 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001641 // Don't do this for the MCU if there are still free integer registers
1642 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001643 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1644 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001645 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001646 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001647 State.CC == llvm::CallingConv::X86_VectorCall ||
1648 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001649 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001650
Reid Kleckner661f35b2014-01-18 01:12:41 +00001651 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001652 }
1653
Chris Lattnerd774ae92010-08-26 20:05:13 +00001654 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001655 // On Darwin, some vectors are passed in memory, we handle this by passing
1656 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001657 if (IsDarwinVectorABI) {
1658 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001659 if ((Size == 8 || Size == 16 || Size == 32) ||
1660 (Size == 64 && VT->getNumElements() == 1))
1661 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1662 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001663 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001664
Chad Rosier651c1832013-03-25 21:00:27 +00001665 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1666 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001667
Chris Lattnerd774ae92010-08-26 20:05:13 +00001668 return ABIArgInfo::getDirect();
1669 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001670
1671
Chris Lattner458b2aa2010-07-29 02:16:43 +00001672 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1673 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001674
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001675 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001676
1677 if (Ty->isPromotableIntegerType()) {
1678 if (InReg)
1679 return ABIArgInfo::getExtendInReg();
1680 return ABIArgInfo::getExtend();
1681 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001682
Rafael Espindola703c47f2012-10-19 05:04:37 +00001683 if (InReg)
1684 return ABIArgInfo::getDirectInReg();
1685 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001686}
1687
Erich Keane521ed962017-01-05 00:20:51 +00001688void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1689 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001690 // Vectorcall x86 works subtly different than in x64, so the format is
1691 // a bit different than the x64 version. First, all vector types (not HVAs)
1692 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1693 // This differs from the x64 implementation, where the first 6 by INDEX get
1694 // registers.
1695 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1696 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1697 // first take up the remaining YMM/XMM registers. If insufficient registers
1698 // remain but an integer register (ECX/EDX) is available, it will be passed
1699 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001700 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001701 // First pass do all the vector types.
1702 const Type *Base = nullptr;
1703 uint64_t NumElts = 0;
1704 const QualType& Ty = I.type;
1705 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1706 isHomogeneousAggregate(Ty, Base, NumElts)) {
1707 if (State.FreeSSERegs >= NumElts) {
1708 State.FreeSSERegs -= NumElts;
1709 I.info = ABIArgInfo::getDirect();
1710 } else {
1711 I.info = classifyArgumentType(Ty, State);
1712 }
1713 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1714 }
Erich Keane521ed962017-01-05 00:20:51 +00001715 }
Erich Keane4bd39302017-06-21 16:37:22 +00001716
Erich Keane521ed962017-01-05 00:20:51 +00001717 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001718 // Second pass, do the rest!
1719 const Type *Base = nullptr;
1720 uint64_t NumElts = 0;
1721 const QualType& Ty = I.type;
1722 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1723
1724 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1725 // Assign true HVAs (non vector/native FP types).
1726 if (State.FreeSSERegs >= NumElts) {
1727 State.FreeSSERegs -= NumElts;
1728 I.info = getDirectX86Hva();
1729 } else {
1730 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1731 }
1732 } else if (!IsHva) {
1733 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1734 I.info = classifyArgumentType(Ty, State);
1735 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1736 }
Erich Keane521ed962017-01-05 00:20:51 +00001737 }
1738}
1739
Rafael Espindolaa6472962012-07-24 00:01:07 +00001740void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001741 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001742 if (IsMCUABI)
1743 State.FreeRegs = 3;
1744 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001745 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001746 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1747 State.FreeRegs = 2;
1748 State.FreeSSERegs = 6;
1749 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001750 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001751 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1752 State.FreeRegs = 5;
1753 State.FreeSSERegs = 8;
1754 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001755 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001756
Reid Kleckner677539d2014-07-10 01:58:55 +00001757 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001758 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001759 } else if (FI.getReturnInfo().isIndirect()) {
1760 // The C++ ABI is not aware of register usage, so we have to check if the
1761 // return value was sret and put it in a register ourselves if appropriate.
1762 if (State.FreeRegs) {
1763 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001764 if (!IsMCUABI)
1765 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001766 }
1767 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001768
Peter Collingbournef7706832014-12-12 23:41:25 +00001769 // The chain argument effectively gives us another free register.
1770 if (FI.isChainCall())
1771 ++State.FreeRegs;
1772
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001773 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001774 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1775 computeVectorCallArgs(FI, State, UsedInAlloca);
1776 } else {
1777 // If not vectorcall, revert to normal behavior.
1778 for (auto &I : FI.arguments()) {
1779 I.info = classifyArgumentType(I.type, State);
1780 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1781 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001782 }
1783
1784 // If we needed to use inalloca for any argument, do a second pass and rewrite
1785 // all the memory arguments to use inalloca.
1786 if (UsedInAlloca)
1787 rewriteWithInAlloca(FI);
1788}
1789
1790void
1791X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001792 CharUnits &StackOffset, ABIArgInfo &Info,
1793 QualType Type) const {
1794 // Arguments are always 4-byte-aligned.
1795 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1796
1797 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001798 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1799 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001800 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001801
John McCall7f416cc2015-09-08 08:05:57 +00001802 // Insert padding bytes to respect alignment.
1803 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001804 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001805 if (StackOffset != FieldEnd) {
1806 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001807 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001808 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001809 FrameFields.push_back(Ty);
1810 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001811}
1812
Reid Kleckner852361d2014-07-26 00:12:26 +00001813static bool isArgInAlloca(const ABIArgInfo &Info) {
1814 // Leave ignored and inreg arguments alone.
1815 switch (Info.getKind()) {
1816 case ABIArgInfo::InAlloca:
1817 return true;
1818 case ABIArgInfo::Indirect:
1819 assert(Info.getIndirectByVal());
1820 return true;
1821 case ABIArgInfo::Ignore:
1822 return false;
1823 case ABIArgInfo::Direct:
1824 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001825 if (Info.getInReg())
1826 return false;
1827 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001828 case ABIArgInfo::Expand:
1829 case ABIArgInfo::CoerceAndExpand:
1830 // These are aggregate types which are never passed in registers when
1831 // inalloca is involved.
1832 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001833 }
1834 llvm_unreachable("invalid enum");
1835}
1836
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001837void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1838 assert(IsWin32StructABI && "inalloca only supported on win32");
1839
1840 // Build a packed struct type for all of the arguments in memory.
1841 SmallVector<llvm::Type *, 6> FrameFields;
1842
John McCall7f416cc2015-09-08 08:05:57 +00001843 // The stack alignment is always 4.
1844 CharUnits StackAlign = CharUnits::fromQuantity(4);
1845
1846 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001847 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1848
1849 // Put 'this' into the struct before 'sret', if necessary.
1850 bool IsThisCall =
1851 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1852 ABIArgInfo &Ret = FI.getReturnInfo();
1853 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1854 isArgInAlloca(I->info)) {
1855 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1856 ++I;
1857 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001858
1859 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001860 if (Ret.isIndirect() && !Ret.getInReg()) {
1861 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1862 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001863 // On Windows, the hidden sret parameter is always returned in eax.
1864 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001865 }
1866
1867 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001868 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001869 ++I;
1870
1871 // Put arguments passed in memory into the struct.
1872 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001873 if (isArgInAlloca(I->info))
1874 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001875 }
1876
1877 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001878 /*isPacked=*/true),
1879 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001880}
1881
John McCall7f416cc2015-09-08 08:05:57 +00001882Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1883 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884
John McCall7f416cc2015-09-08 08:05:57 +00001885 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001886
John McCall7f416cc2015-09-08 08:05:57 +00001887 // x86-32 changes the alignment of certain arguments on the stack.
1888 //
1889 // Just messing with TypeInfo like this works because we never pass
1890 // anything indirectly.
1891 TypeInfo.second = CharUnits::fromQuantity(
1892 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001893
John McCall7f416cc2015-09-08 08:05:57 +00001894 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1895 TypeInfo, CharUnits::fromQuantity(4),
1896 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001897}
1898
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001899bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1900 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1901 assert(Triple.getArch() == llvm::Triple::x86);
1902
1903 switch (Opts.getStructReturnConvention()) {
1904 case CodeGenOptions::SRCK_Default:
1905 break;
1906 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1907 return false;
1908 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1909 return true;
1910 }
1911
Michael Kupersteind749f232015-10-27 07:46:22 +00001912 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001913 return true;
1914
1915 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001916 case llvm::Triple::DragonFly:
1917 case llvm::Triple::FreeBSD:
1918 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001919 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001920 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001921 default:
1922 return false;
1923 }
1924}
1925
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001926void X86_32TargetCodeGenInfo::setTargetAttributes(
1927 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
1928 ForDefinition_t IsForDefinition) const {
1929 if (!IsForDefinition)
1930 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001931 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001932 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1933 // Get the LLVM function.
1934 llvm::Function *Fn = cast<llvm::Function>(GV);
1935
1936 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001937 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001938 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001939 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001940 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001941 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1942 llvm::Function *Fn = cast<llvm::Function>(GV);
1943 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1944 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001945 }
1946}
1947
John McCallbeec5a02010-03-06 00:35:14 +00001948bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1949 CodeGen::CodeGenFunction &CGF,
1950 llvm::Value *Address) const {
1951 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001952
Chris Lattnerece04092012-02-07 00:39:47 +00001953 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001954
John McCallbeec5a02010-03-06 00:35:14 +00001955 // 0-7 are the eight integer registers; the order is different
1956 // on Darwin (for EH), but the range is the same.
1957 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001958 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001959
John McCallc8e01702013-04-16 22:48:15 +00001960 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001961 // 12-16 are st(0..4). Not sure why we stop at 4.
1962 // These have size 16, which is sizeof(long double) on
1963 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001964 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001965 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001966
John McCallbeec5a02010-03-06 00:35:14 +00001967 } else {
1968 // 9 is %eflags, which doesn't get a size on Darwin for some
1969 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001970 Builder.CreateAlignedStore(
1971 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1972 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001973
1974 // 11-16 are st(0..5). Not sure why we stop at 5.
1975 // These have size 12, which is sizeof(long double) on
1976 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001977 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001978 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1979 }
John McCallbeec5a02010-03-06 00:35:14 +00001980
1981 return false;
1982}
1983
Chris Lattner0cf24192010-06-28 20:05:43 +00001984//===----------------------------------------------------------------------===//
1985// X86-64 ABI Implementation
1986//===----------------------------------------------------------------------===//
1987
1988
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001989namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001990/// The AVX ABI level for X86 targets.
1991enum class X86AVXABILevel {
1992 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001993 AVX,
1994 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001995};
1996
1997/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1998static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1999 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002000 case X86AVXABILevel::AVX512:
2001 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002002 case X86AVXABILevel::AVX:
2003 return 256;
2004 case X86AVXABILevel::None:
2005 return 128;
2006 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00002007 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002008}
2009
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002010/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00002011class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002012 enum Class {
2013 Integer = 0,
2014 SSE,
2015 SSEUp,
2016 X87,
2017 X87Up,
2018 ComplexX87,
2019 NoClass,
2020 Memory
2021 };
2022
2023 /// merge - Implement the X86_64 ABI merging algorithm.
2024 ///
2025 /// Merge an accumulating classification \arg Accum with a field
2026 /// classification \arg Field.
2027 ///
2028 /// \param Accum - The accumulating classification. This should
2029 /// always be either NoClass or the result of a previous merge
2030 /// call. In addition, this should never be Memory (the caller
2031 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002032 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002033
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002034 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2035 ///
2036 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2037 /// final MEMORY or SSE classes when necessary.
2038 ///
2039 /// \param AggregateSize - The size of the current aggregate in
2040 /// the classification process.
2041 ///
2042 /// \param Lo - The classification for the parts of the type
2043 /// residing in the low word of the containing object.
2044 ///
2045 /// \param Hi - The classification for the parts of the type
2046 /// residing in the higher words of the containing object.
2047 ///
2048 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2049
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002050 /// classify - Determine the x86_64 register classes in which the
2051 /// given type T should be passed.
2052 ///
2053 /// \param Lo - The classification for the parts of the type
2054 /// residing in the low word of the containing object.
2055 ///
2056 /// \param Hi - The classification for the parts of the type
2057 /// residing in the high word of the containing object.
2058 ///
2059 /// \param OffsetBase - The bit offset of this type in the
2060 /// containing object. Some parameters are classified different
2061 /// depending on whether they straddle an eightbyte boundary.
2062 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002063 /// \param isNamedArg - Whether the argument in question is a "named"
2064 /// argument, as used in AMD64-ABI 3.5.7.
2065 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002066 /// If a word is unused its result will be NoClass; if a type should
2067 /// be passed in Memory then at least the classification of \arg Lo
2068 /// will be Memory.
2069 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002070 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002071 ///
2072 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2073 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002074 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2075 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002077 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002078 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2079 unsigned IROffset, QualType SourceTy,
2080 unsigned SourceOffset) const;
2081 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2082 unsigned IROffset, QualType SourceTy,
2083 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002084
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002085 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002086 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002087 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002088
2089 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002090 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002091 ///
2092 /// \param freeIntRegs - The number of free integer registers remaining
2093 /// available.
2094 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002095
Chris Lattner458b2aa2010-07-29 02:16:43 +00002096 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002097
Erich Keane757d3172016-11-02 18:29:35 +00002098 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2099 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002100 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002101
Erich Keane757d3172016-11-02 18:29:35 +00002102 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2103 unsigned &NeededSSE) const;
2104
2105 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2106 unsigned &NeededSSE) const;
2107
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002108 bool IsIllegalVectorType(QualType Ty) const;
2109
John McCalle0fda732011-04-21 01:20:55 +00002110 /// The 0.98 ABI revision clarified a lot of ambiguities,
2111 /// unfortunately in ways that were not always consistent with
2112 /// certain previous compilers. In particular, platforms which
2113 /// required strict binary compatibility with older versions of GCC
2114 /// may need to exempt themselves.
2115 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002116 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002117 }
2118
Richard Smithf667ad52017-08-26 01:04:35 +00002119 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2120 /// classify it as INTEGER (for compatibility with older clang compilers).
David Majnemere2ae2282016-03-04 05:26:16 +00002121 bool classifyIntegerMMXAsSSE() const {
Richard Smithf667ad52017-08-26 01:04:35 +00002122 // Clang <= 3.8 did not do this.
2123 if (getCodeGenOpts().getClangABICompat() <=
2124 CodeGenOptions::ClangABI::Ver3_8)
2125 return false;
2126
David Majnemere2ae2282016-03-04 05:26:16 +00002127 const llvm::Triple &Triple = getTarget().getTriple();
2128 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2129 return false;
2130 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2131 return false;
2132 return true;
2133 }
2134
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002135 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002136 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2137 // 64-bit hardware.
2138 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002139
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002140public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002141 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002142 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002143 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002144 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002145
John McCalla729c622012-02-17 03:33:10 +00002146 bool isPassedUsingAVXType(QualType type) const {
2147 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002148 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002149 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2150 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002151 if (info.isDirect()) {
2152 llvm::Type *ty = info.getCoerceToType();
2153 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2154 return (vectorTy->getBitWidth() > 128);
2155 }
2156 return false;
2157 }
2158
Craig Topper4f12f102014-03-12 06:41:41 +00002159 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002160
John McCall7f416cc2015-09-08 08:05:57 +00002161 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2162 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002163 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2164 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002165
2166 bool has64BitPointers() const {
2167 return Has64BitPointers;
2168 }
John McCall12f23522016-04-04 18:33:08 +00002169
2170 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2171 ArrayRef<llvm::Type*> scalars,
2172 bool asReturnValue) const override {
2173 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2174 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002175 bool isSwiftErrorInRegister() const override {
2176 return true;
2177 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002178};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002179
Chris Lattner04dc9572010-08-31 16:44:54 +00002180/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002181class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002182public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002183 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002184 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002185 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002186
Craig Topper4f12f102014-03-12 06:41:41 +00002187 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002188
John McCall7f416cc2015-09-08 08:05:57 +00002189 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2190 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002191
2192 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2193 // FIXME: Assumes vectorcall is in use.
2194 return isX86VectorTypeForVectorCall(getContext(), Ty);
2195 }
2196
2197 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2198 uint64_t NumMembers) const override {
2199 // FIXME: Assumes vectorcall is in use.
2200 return isX86VectorCallAggregateSmallEnough(NumMembers);
2201 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002202
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002203 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2204 ArrayRef<llvm::Type *> scalars,
2205 bool asReturnValue) const override {
2206 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2207 }
2208
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002209 bool isSwiftErrorInRegister() const override {
2210 return true;
2211 }
2212
Reid Kleckner11a17192015-10-28 22:29:52 +00002213private:
Erich Keane521ed962017-01-05 00:20:51 +00002214 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2215 bool IsVectorCall, bool IsRegCall) const;
2216 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2217 const ABIArgInfo &current) const;
2218 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2219 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002220
Erich Keane521ed962017-01-05 00:20:51 +00002221 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002222};
2223
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002224class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2225public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002226 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002227 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002228
John McCalla729c622012-02-17 03:33:10 +00002229 const X86_64ABIInfo &getABIInfo() const {
2230 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2231 }
2232
Craig Topper4f12f102014-03-12 06:41:41 +00002233 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002234 return 7;
2235 }
2236
2237 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002238 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002239 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002240
John McCall943fae92010-05-27 06:19:26 +00002241 // 0-15 are the 16 integer registers.
2242 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002243 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002244 return false;
2245 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002246
Jay Foad7c57be32011-07-11 09:56:20 +00002247 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002248 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002249 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002250 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2251 }
2252
John McCalla729c622012-02-17 03:33:10 +00002253 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002254 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002255 // The default CC on x86-64 sets %al to the number of SSA
2256 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002257 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002258 // that when AVX types are involved: the ABI explicitly states it is
2259 // undefined, and it doesn't work in practice because of how the ABI
2260 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002261 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002262 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002263 for (CallArgList::const_iterator
2264 it = args.begin(), ie = args.end(); it != ie; ++it) {
2265 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2266 HasAVXType = true;
2267 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002268 }
2269 }
John McCalla729c622012-02-17 03:33:10 +00002270
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002271 if (!HasAVXType)
2272 return true;
2273 }
John McCallcbc038a2011-09-21 08:08:30 +00002274
John McCalla729c622012-02-17 03:33:10 +00002275 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002276 }
2277
Craig Topper4f12f102014-03-12 06:41:41 +00002278 llvm::Constant *
2279 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002280 unsigned Sig;
2281 if (getABIInfo().has64BitPointers())
2282 Sig = (0xeb << 0) | // jmp rel8
2283 (0x0a << 8) | // .+0x0c
2284 ('F' << 16) |
2285 ('T' << 24);
2286 else
2287 Sig = (0xeb << 0) | // jmp rel8
2288 (0x06 << 8) | // .+0x08
2289 ('F' << 16) |
2290 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002291 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2292 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002293
2294 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002295 CodeGen::CodeGenModule &CGM,
2296 ForDefinition_t IsForDefinition) const override {
2297 if (!IsForDefinition)
2298 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002299 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002300 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2301 // Get the LLVM function.
2302 auto *Fn = cast<llvm::Function>(GV);
2303
2304 // Now add the 'alignstack' attribute with a value of 16.
2305 llvm::AttrBuilder B;
2306 B.addStackAlignmentAttr(16);
2307 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2308 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002309 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2310 llvm::Function *Fn = cast<llvm::Function>(GV);
2311 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2312 }
2313 }
2314 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002315};
2316
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002317class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2318public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002319 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2320 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002321
2322 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002323 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002324 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002325 // If the argument contains a space, enclose it in quotes.
2326 if (Lib.find(" ") != StringRef::npos)
2327 Opt += "\"" + Lib.str() + "\"";
2328 else
2329 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002330 }
2331};
2332
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002333static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002334 // If the argument does not end in .lib, automatically add the suffix.
2335 // If the argument contains a space, enclose it in quotes.
2336 // This matches the behavior of MSVC.
2337 bool Quote = (Lib.find(" ") != StringRef::npos);
2338 std::string ArgStr = Quote ? "\"" : "";
2339 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002340 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002341 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002342 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002343 return ArgStr;
2344}
2345
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002346class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2347public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002348 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002349 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2350 unsigned NumRegisterParameters)
2351 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002352 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002353
Eric Christopher162c91c2015-06-05 22:03:00 +00002354 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002355 CodeGen::CodeGenModule &CGM,
2356 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002357
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002358 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002359 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002360 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002361 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002362 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002363
2364 void getDetectMismatchOption(llvm::StringRef Name,
2365 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002366 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002367 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002368 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002369};
2370
Hans Wennborg77dc2362015-01-20 19:45:50 +00002371static void addStackProbeSizeTargetAttribute(const Decl *D,
2372 llvm::GlobalValue *GV,
2373 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002374 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002375 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2376 llvm::Function *Fn = cast<llvm::Function>(GV);
2377
Eric Christopher7565e0d2015-05-29 23:09:49 +00002378 Fn->addFnAttr("stack-probe-size",
2379 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002380 }
2381 }
2382}
2383
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002384void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2385 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2386 ForDefinition_t IsForDefinition) const {
2387 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2388 if (!IsForDefinition)
2389 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002390 addStackProbeSizeTargetAttribute(D, GV, CGM);
2391}
2392
Chris Lattner04dc9572010-08-31 16:44:54 +00002393class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2394public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002395 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2396 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002397 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002398
Eric Christopher162c91c2015-06-05 22:03:00 +00002399 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002400 CodeGen::CodeGenModule &CGM,
2401 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002402
Craig Topper4f12f102014-03-12 06:41:41 +00002403 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002404 return 7;
2405 }
2406
2407 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002408 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002409 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002410
Chris Lattner04dc9572010-08-31 16:44:54 +00002411 // 0-15 are the 16 integer registers.
2412 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002413 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002414 return false;
2415 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002416
2417 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002418 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002419 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002420 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002421 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002422
2423 void getDetectMismatchOption(llvm::StringRef Name,
2424 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002425 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002426 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002427 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002428};
2429
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002430void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2431 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2432 ForDefinition_t IsForDefinition) const {
2433 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2434 if (!IsForDefinition)
2435 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002436 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Erich Keanebb9c7042017-08-30 21:17:40 +00002437 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2438 // Get the LLVM function.
2439 auto *Fn = cast<llvm::Function>(GV);
2440
2441 // Now add the 'alignstack' attribute with a value of 16.
2442 llvm::AttrBuilder B;
2443 B.addStackAlignmentAttr(16);
2444 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
2445 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002446 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2447 llvm::Function *Fn = cast<llvm::Function>(GV);
2448 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2449 }
2450 }
2451
Hans Wennborg77dc2362015-01-20 19:45:50 +00002452 addStackProbeSizeTargetAttribute(D, GV, CGM);
2453}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002454}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002455
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002456void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2457 Class &Hi) const {
2458 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2459 //
2460 // (a) If one of the classes is Memory, the whole argument is passed in
2461 // memory.
2462 //
2463 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2464 // memory.
2465 //
2466 // (c) If the size of the aggregate exceeds two eightbytes and the first
2467 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2468 // argument is passed in memory. NOTE: This is necessary to keep the
2469 // ABI working for processors that don't support the __m256 type.
2470 //
2471 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2472 //
2473 // Some of these are enforced by the merging logic. Others can arise
2474 // only with unions; for example:
2475 // union { _Complex double; unsigned; }
2476 //
2477 // Note that clauses (b) and (c) were added in 0.98.
2478 //
2479 if (Hi == Memory)
2480 Lo = Memory;
2481 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2482 Lo = Memory;
2483 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2484 Lo = Memory;
2485 if (Hi == SSEUp && Lo != SSE)
2486 Hi = SSE;
2487}
2488
Chris Lattnerd776fb12010-06-28 21:43:59 +00002489X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002490 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2491 // classified recursively so that always two fields are
2492 // considered. The resulting class is calculated according to
2493 // the classes of the fields in the eightbyte:
2494 //
2495 // (a) If both classes are equal, this is the resulting class.
2496 //
2497 // (b) If one of the classes is NO_CLASS, the resulting class is
2498 // the other class.
2499 //
2500 // (c) If one of the classes is MEMORY, the result is the MEMORY
2501 // class.
2502 //
2503 // (d) If one of the classes is INTEGER, the result is the
2504 // INTEGER.
2505 //
2506 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2507 // MEMORY is used as class.
2508 //
2509 // (f) Otherwise class SSE is used.
2510
2511 // Accum should never be memory (we should have returned) or
2512 // ComplexX87 (because this cannot be passed in a structure).
2513 assert((Accum != Memory && Accum != ComplexX87) &&
2514 "Invalid accumulated classification during merge.");
2515 if (Accum == Field || Field == NoClass)
2516 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002517 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002519 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002520 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002521 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002522 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002523 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2524 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002525 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002526 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527}
2528
Chris Lattner5c740f12010-06-30 19:14:05 +00002529void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002530 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002531 // FIXME: This code can be simplified by introducing a simple value class for
2532 // Class pairs with appropriate constructor methods for the various
2533 // situations.
2534
2535 // FIXME: Some of the split computations are wrong; unaligned vectors
2536 // shouldn't be passed in registers for example, so there is no chance they
2537 // can straddle an eightbyte. Verify & simplify.
2538
2539 Lo = Hi = NoClass;
2540
2541 Class &Current = OffsetBase < 64 ? Lo : Hi;
2542 Current = Memory;
2543
John McCall9dd450b2009-09-21 23:43:11 +00002544 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002545 BuiltinType::Kind k = BT->getKind();
2546
2547 if (k == BuiltinType::Void) {
2548 Current = NoClass;
2549 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2550 Lo = Integer;
2551 Hi = Integer;
2552 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2553 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002554 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002555 Current = SSE;
2556 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002557 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002558 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002559 Lo = SSE;
2560 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002561 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002562 Lo = X87;
2563 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002564 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002565 Current = SSE;
2566 } else
2567 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002568 }
2569 // FIXME: _Decimal32 and _Decimal64 are SSE.
2570 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
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 (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002575 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002576 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002577 return;
2578 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002579
Chris Lattnerd776fb12010-06-28 21:43:59 +00002580 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002581 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002582 return;
2583 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002584
Chris Lattnerd776fb12010-06-28 21:43:59 +00002585 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002586 if (Ty->isMemberFunctionPointerType()) {
2587 if (Has64BitPointers) {
2588 // If Has64BitPointers, this is an {i64, i64}, so classify both
2589 // Lo and Hi now.
2590 Lo = Hi = Integer;
2591 } else {
2592 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2593 // straddles an eightbyte boundary, Hi should be classified as well.
2594 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2595 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2596 if (EB_FuncPtr != EB_ThisAdj) {
2597 Lo = Hi = Integer;
2598 } else {
2599 Current = Integer;
2600 }
2601 }
2602 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002603 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002604 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002605 return;
2606 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002607
Chris Lattnerd776fb12010-06-28 21:43:59 +00002608 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002609 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002610 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2611 // gcc passes the following as integer:
2612 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2613 // 2 bytes - <2 x char>, <1 x short>
2614 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002615 Current = Integer;
2616
2617 // If this type crosses an eightbyte boundary, it should be
2618 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002619 uint64_t EB_Lo = (OffsetBase) / 64;
2620 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2621 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002622 Hi = Lo;
2623 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002624 QualType ElementType = VT->getElementType();
2625
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002626 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002627 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002628 return;
2629
David Majnemere2ae2282016-03-04 05:26:16 +00002630 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2631 // pass them as integer. For platforms where clang is the de facto
2632 // platform compiler, we must continue to use integer.
2633 if (!classifyIntegerMMXAsSSE() &&
2634 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2635 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2636 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2637 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002638 Current = Integer;
2639 else
2640 Current = SSE;
2641
2642 // If this type crosses an eightbyte boundary, it should be
2643 // split.
2644 if (OffsetBase && OffsetBase != 64)
2645 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002646 } else if (Size == 128 ||
2647 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002648 // Arguments of 256-bits are split into four eightbyte chunks. The
2649 // least significant one belongs to class SSE and all the others to class
2650 // SSEUP. The original Lo and Hi design considers that types can't be
2651 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2652 // This design isn't correct for 256-bits, but since there're no cases
2653 // where the upper parts would need to be inspected, avoid adding
2654 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002655 //
2656 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2657 // registers if they are "named", i.e. not part of the "..." of a
2658 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002659 //
2660 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2661 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002662 Lo = SSE;
2663 Hi = SSEUp;
2664 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002665 return;
2666 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002667
Chris Lattnerd776fb12010-06-28 21:43:59 +00002668 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002669 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002670
Chris Lattner2b037972010-07-29 02:01:43 +00002671 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002672 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002673 if (Size <= 64)
2674 Current = Integer;
2675 else if (Size <= 128)
2676 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002677 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002678 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002679 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002680 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002681 } else if (ET == getContext().LongDoubleTy) {
2682 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002683 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002684 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002685 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002686 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002687 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002688 Lo = Hi = SSE;
2689 else
2690 llvm_unreachable("unexpected long double representation!");
2691 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692
2693 // If this complex type crosses an eightbyte boundary then it
2694 // should be split.
2695 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002696 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002697 if (Hi == NoClass && EB_Real != EB_Imag)
2698 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002699
Chris Lattnerd776fb12010-06-28 21:43:59 +00002700 return;
2701 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002702
Chris Lattner2b037972010-07-29 02:01:43 +00002703 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002704 // Arrays are treated like structures.
2705
Chris Lattner2b037972010-07-29 02:01:43 +00002706 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707
2708 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002709 // than eight eightbytes, ..., it has class MEMORY.
2710 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002711 return;
2712
2713 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2714 // fields, it has class MEMORY.
2715 //
2716 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002717 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002718 return;
2719
2720 // Otherwise implement simplified merge. We could be smarter about
2721 // this, but it isn't worth it and would be harder to verify.
2722 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002723 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002724 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002725
2726 // The only case a 256-bit wide vector could be used is when the array
2727 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2728 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002729 //
2730 if (Size > 128 &&
2731 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002732 return;
2733
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002734 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2735 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002736 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002737 Lo = merge(Lo, FieldLo);
2738 Hi = merge(Hi, FieldHi);
2739 if (Lo == Memory || Hi == Memory)
2740 break;
2741 }
2742
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002743 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002745 return;
2746 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002747
Chris Lattnerd776fb12010-06-28 21:43:59 +00002748 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002749 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750
2751 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002752 // than eight eightbytes, ..., it has class MEMORY.
2753 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002754 return;
2755
Anders Carlsson20759ad2009-09-16 15:53:40 +00002756 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2757 // copy constructor or a non-trivial destructor, it is passed by invisible
2758 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002759 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002760 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002761
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002762 const RecordDecl *RD = RT->getDecl();
2763
2764 // Assume variable sized types are passed in memory.
2765 if (RD->hasFlexibleArrayMember())
2766 return;
2767
Chris Lattner2b037972010-07-29 02:01:43 +00002768 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002769
2770 // Reset Lo class, this will be recomputed.
2771 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002772
2773 // If this is a C++ record, classify the bases first.
2774 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002775 for (const auto &I : CXXRD->bases()) {
2776 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002777 "Unexpected base class!");
2778 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002779 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002780
2781 // Classify this field.
2782 //
2783 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2784 // single eightbyte, each is classified separately. Each eightbyte gets
2785 // initialized to class NO_CLASS.
2786 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002787 uint64_t Offset =
2788 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002789 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002790 Lo = merge(Lo, FieldLo);
2791 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002792 if (Lo == Memory || Hi == Memory) {
2793 postMerge(Size, Lo, Hi);
2794 return;
2795 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002796 }
2797 }
2798
2799 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002800 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002801 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002802 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002803 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2804 bool BitField = i->isBitField();
2805
David Majnemerb439dfe2016-08-15 07:20:40 +00002806 // Ignore padding bit-fields.
2807 if (BitField && i->isUnnamedBitfield())
2808 continue;
2809
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002810 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2811 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002812 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002813 // The only case a 256-bit wide vector could be used is when the struct
2814 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2815 // to work for sizes wider than 128, early check and fallback to memory.
2816 //
David Majnemerb229cb02016-08-15 06:39:18 +00002817 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2818 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002819 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002820 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002821 return;
2822 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002823 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002824 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002825 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002826 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002827 return;
2828 }
2829
2830 // Classify this field.
2831 //
2832 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2833 // exceeds a single eightbyte, each is classified
2834 // separately. Each eightbyte gets initialized to class
2835 // NO_CLASS.
2836 Class FieldLo, FieldHi;
2837
2838 // Bit-fields require special handling, they do not force the
2839 // structure to be passed in memory even if unaligned, and
2840 // therefore they can straddle an eightbyte.
2841 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002842 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002843 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002844 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002845
2846 uint64_t EB_Lo = Offset / 64;
2847 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002848
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002849 if (EB_Lo) {
2850 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2851 FieldLo = NoClass;
2852 FieldHi = Integer;
2853 } else {
2854 FieldLo = Integer;
2855 FieldHi = EB_Hi ? Integer : NoClass;
2856 }
2857 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002858 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002859 Lo = merge(Lo, FieldLo);
2860 Hi = merge(Hi, FieldHi);
2861 if (Lo == Memory || Hi == Memory)
2862 break;
2863 }
2864
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002865 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002866 }
2867}
2868
Chris Lattner22a931e2010-06-29 06:01:59 +00002869ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002870 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2871 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002872 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002873 // Treat an enum type as its underlying type.
2874 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2875 Ty = EnumTy->getDecl()->getIntegerType();
2876
2877 return (Ty->isPromotableIntegerType() ?
2878 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2879 }
2880
John McCall7f416cc2015-09-08 08:05:57 +00002881 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002882}
2883
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002884bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2885 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2886 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002887 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002888 if (Size <= 64 || Size > LargestVector)
2889 return true;
2890 }
2891
2892 return false;
2893}
2894
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002895ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2896 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002897 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2898 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002899 //
2900 // This assumption is optimistic, as there could be free registers available
2901 // when we need to pass this argument in memory, and LLVM could try to pass
2902 // the argument in the free register. This does not seem to happen currently,
2903 // but this code would be much safer if we could mark the argument with
2904 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002905 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002906 // Treat an enum type as its underlying type.
2907 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2908 Ty = EnumTy->getDecl()->getIntegerType();
2909
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002910 return (Ty->isPromotableIntegerType() ?
2911 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002912 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002913
Mark Lacey3825e832013-10-06 01:33:34 +00002914 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002915 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002916
Chris Lattner44c2b902011-05-22 23:21:23 +00002917 // Compute the byval alignment. We specify the alignment of the byval in all
2918 // cases so that the mid-level optimizer knows the alignment of the byval.
2919 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002920
2921 // Attempt to avoid passing indirect results using byval when possible. This
2922 // is important for good codegen.
2923 //
2924 // We do this by coercing the value into a scalar type which the backend can
2925 // handle naturally (i.e., without using byval).
2926 //
2927 // For simplicity, we currently only do this when we have exhausted all of the
2928 // free integer registers. Doing this when there are free integer registers
2929 // would require more care, as we would have to ensure that the coerced value
2930 // did not claim the unused register. That would require either reording the
2931 // arguments to the function (so that any subsequent inreg values came first),
2932 // or only doing this optimization when there were no following arguments that
2933 // might be inreg.
2934 //
2935 // We currently expect it to be rare (particularly in well written code) for
2936 // arguments to be passed on the stack when there are still free integer
2937 // registers available (this would typically imply large structs being passed
2938 // by value), so this seems like a fair tradeoff for now.
2939 //
2940 // We can revisit this if the backend grows support for 'onstack' parameter
2941 // attributes. See PR12193.
2942 if (freeIntRegs == 0) {
2943 uint64_t Size = getContext().getTypeSize(Ty);
2944
2945 // If this type fits in an eightbyte, coerce it into the matching integral
2946 // type, which will end up on the stack (with alignment 8).
2947 if (Align == 8 && Size <= 64)
2948 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2949 Size));
2950 }
2951
John McCall7f416cc2015-09-08 08:05:57 +00002952 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002953}
2954
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002955/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2956/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002957llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002958 // Wrapper structs/arrays that only contain vectors are passed just like
2959 // vectors; strip them off if present.
2960 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2961 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002962
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002963 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002964 if (isa<llvm::VectorType>(IRType) ||
2965 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002966 return IRType;
2967
2968 // We couldn't find the preferred IR vector type for 'Ty'.
2969 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002970 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002971
2972 // Return a LLVM IR vector type based on the size of 'Ty'.
2973 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2974 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002975}
2976
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002977/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2978/// is known to either be off the end of the specified type or being in
2979/// alignment padding. The user type specified is known to be at most 128 bits
2980/// in size, and have passed through X86_64ABIInfo::classify with a successful
2981/// classification that put one of the two halves in the INTEGER class.
2982///
2983/// It is conservatively correct to return false.
2984static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2985 unsigned EndBit, ASTContext &Context) {
2986 // If the bytes being queried are off the end of the type, there is no user
2987 // data hiding here. This handles analysis of builtins, vectors and other
2988 // types that don't contain interesting padding.
2989 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2990 if (TySize <= StartBit)
2991 return true;
2992
Chris Lattner98076a22010-07-29 07:43:55 +00002993 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2994 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2995 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2996
2997 // Check each element to see if the element overlaps with the queried range.
2998 for (unsigned i = 0; i != NumElts; ++i) {
2999 // If the element is after the span we care about, then we're done..
3000 unsigned EltOffset = i*EltSize;
3001 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003002
Chris Lattner98076a22010-07-29 07:43:55 +00003003 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3004 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3005 EndBit-EltOffset, Context))
3006 return false;
3007 }
3008 // If it overlaps no elements, then it is safe to process as padding.
3009 return true;
3010 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003011
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003012 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3013 const RecordDecl *RD = RT->getDecl();
3014 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003015
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003016 // If this is a C++ record, check the bases first.
3017 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003018 for (const auto &I : CXXRD->bases()) {
3019 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003020 "Unexpected base class!");
3021 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003022 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003023
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003024 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003025 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003026 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003027
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003028 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003029 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003030 EndBit-BaseOffset, Context))
3031 return false;
3032 }
3033 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003034
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003035 // Verify that no field has data that overlaps the region of interest. Yes
3036 // this could be sped up a lot by being smarter about queried fields,
3037 // however we're only looking at structs up to 16 bytes, so we don't care
3038 // much.
3039 unsigned idx = 0;
3040 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3041 i != e; ++i, ++idx) {
3042 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003043
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003044 // If we found a field after the region we care about, then we're done.
3045 if (FieldOffset >= EndBit) break;
3046
3047 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3048 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3049 Context))
3050 return false;
3051 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003052
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003053 // If nothing in this record overlapped the area of interest, then we're
3054 // clean.
3055 return true;
3056 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003057
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003058 return false;
3059}
3060
Chris Lattnere556a712010-07-29 18:39:32 +00003061/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3062/// float member at the specified offset. For example, {int,{float}} has a
3063/// float at offset 4. It is conservatively correct for this routine to return
3064/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003065static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003066 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003067 // Base case if we find a float.
3068 if (IROffset == 0 && IRType->isFloatTy())
3069 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003070
Chris Lattnere556a712010-07-29 18:39:32 +00003071 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003072 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003073 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3074 unsigned Elt = SL->getElementContainingOffset(IROffset);
3075 IROffset -= SL->getElementOffset(Elt);
3076 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3077 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003078
Chris Lattnere556a712010-07-29 18:39:32 +00003079 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003080 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3081 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003082 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3083 IROffset -= IROffset/EltSize*EltSize;
3084 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3085 }
3086
3087 return false;
3088}
3089
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003090
3091/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3092/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003093llvm::Type *X86_64ABIInfo::
3094GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003095 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003096 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003097 // pass as float if the last 4 bytes is just padding. This happens for
3098 // structs that contain 3 floats.
3099 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3100 SourceOffset*8+64, getContext()))
3101 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003102
Chris Lattnere556a712010-07-29 18:39:32 +00003103 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3104 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3105 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003106 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3107 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003108 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003109
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003110 return llvm::Type::getDoubleTy(getVMContext());
3111}
3112
3113
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003114/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3115/// an 8-byte GPR. This means that we either have a scalar or we are talking
3116/// about the high or low part of an up-to-16-byte struct. This routine picks
3117/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003118/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3119/// etc).
3120///
3121/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3122/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3123/// the 8-byte value references. PrefType may be null.
3124///
Alp Toker9907f082014-07-09 14:06:35 +00003125/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003126/// an offset into this that we're processing (which is always either 0 or 8).
3127///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003128llvm::Type *X86_64ABIInfo::
3129GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003130 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003131 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3132 // returning an 8-byte unit starting with it. See if we can safely use it.
3133 if (IROffset == 0) {
3134 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003135 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3136 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003137 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003138
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003139 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3140 // goodness in the source type is just tail padding. This is allowed to
3141 // kick in for struct {double,int} on the int, but not on
3142 // struct{double,int,int} because we wouldn't return the second int. We
3143 // have to do this analysis on the source type because we can't depend on
3144 // unions being lowered a specific way etc.
3145 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003146 IRType->isIntegerTy(32) ||
3147 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3148 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3149 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003150
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003151 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3152 SourceOffset*8+64, getContext()))
3153 return IRType;
3154 }
3155 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003156
Chris Lattner2192fe52011-07-18 04:24:23 +00003157 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003158 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003159 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003160 if (IROffset < SL->getSizeInBytes()) {
3161 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3162 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003163
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003164 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3165 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003166 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003167 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003168
Chris Lattner2192fe52011-07-18 04:24:23 +00003169 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003170 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003171 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003172 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003173 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3174 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003175 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003176
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003177 // Okay, we don't have any better idea of what to pass, so we pass this in an
3178 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003179 unsigned TySizeInBytes =
3180 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003181
Chris Lattner3f763422010-07-29 17:34:39 +00003182 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003183
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003184 // It is always safe to classify this as an integer type up to i64 that
3185 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003186 return llvm::IntegerType::get(getVMContext(),
3187 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003188}
3189
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003190
3191/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3192/// be used as elements of a two register pair to pass or return, return a
3193/// first class aggregate to represent them. For example, if the low part of
3194/// a by-value argument should be passed as i32* and the high part as float,
3195/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003196static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003197GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003198 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003199 // In order to correctly satisfy the ABI, we need to the high part to start
3200 // at offset 8. If the high and low parts we inferred are both 4-byte types
3201 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3202 // the second element at offset 8. Check for this:
3203 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3204 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003205 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003206 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003207
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003208 // To handle this, we have to increase the size of the low part so that the
3209 // second element will start at an 8 byte offset. We can't increase the size
3210 // of the second element because it might make us access off the end of the
3211 // struct.
3212 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003213 // There are usually two sorts of types the ABI generation code can produce
3214 // for the low part of a pair that aren't 8 bytes in size: float or
3215 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3216 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003217 // Promote these to a larger type.
3218 if (Lo->isFloatTy())
3219 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3220 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003221 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3222 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003223 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3224 }
3225 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003226
Serge Guelton1d993272017-05-09 19:31:30 +00003227 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003228
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003229 // Verify that the second element is at an 8-byte offset.
3230 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3231 "Invalid x86-64 argument pair!");
3232 return Result;
3233}
3234
Chris Lattner31faff52010-07-28 23:06:14 +00003235ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003236classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003237 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3238 // classification algorithm.
3239 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003240 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003241
3242 // Check some invariants.
3243 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003244 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3245
Craig Topper8a13c412014-05-21 05:09:00 +00003246 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003247 switch (Lo) {
3248 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003249 if (Hi == NoClass)
3250 return ABIArgInfo::getIgnore();
3251 // If the low part is just padding, it takes no register, leave ResType
3252 // null.
3253 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3254 "Unknown missing lo part");
3255 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003256
3257 case SSEUp:
3258 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003259 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003260
3261 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3262 // hidden argument.
3263 case Memory:
3264 return getIndirectReturnResult(RetTy);
3265
3266 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3267 // available register of the sequence %rax, %rdx is used.
3268 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003269 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003270
Chris Lattner1f3a0632010-07-29 21:42:50 +00003271 // If we have a sign or zero extended integer, make sure to return Extend
3272 // so that the parameter gets the right LLVM IR attributes.
3273 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3274 // Treat an enum type as its underlying type.
3275 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3276 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003277
Chris Lattner1f3a0632010-07-29 21:42:50 +00003278 if (RetTy->isIntegralOrEnumerationType() &&
3279 RetTy->isPromotableIntegerType())
3280 return ABIArgInfo::getExtend();
3281 }
Chris Lattner31faff52010-07-28 23:06:14 +00003282 break;
3283
3284 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3285 // available SSE register of the sequence %xmm0, %xmm1 is used.
3286 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003287 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003288 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003289
3290 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3291 // returned on the X87 stack in %st0 as 80-bit x87 number.
3292 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003293 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003294 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003295
3296 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3297 // part of the value is returned in %st0 and the imaginary part in
3298 // %st1.
3299 case ComplexX87:
3300 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003301 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003302 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003303 break;
3304 }
3305
Craig Topper8a13c412014-05-21 05:09:00 +00003306 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003307 switch (Hi) {
3308 // Memory was handled previously and X87 should
3309 // never occur as a hi class.
3310 case Memory:
3311 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003312 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003313
3314 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003315 case NoClass:
3316 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003317
Chris Lattner52b3c132010-09-01 00:20:33 +00003318 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003319 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003320 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3321 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003322 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003323 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003324 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003325 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3326 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003327 break;
3328
3329 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003330 // is passed in the next available eightbyte chunk if the last used
3331 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003332 //
Chris Lattner57540c52011-04-15 05:22:18 +00003333 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003334 case SSEUp:
3335 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003336 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003337 break;
3338
3339 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3340 // returned together with the previous X87 value in %st0.
3341 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003342 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003343 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003344 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003345 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003346 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003347 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003348 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3349 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003350 }
Chris Lattner31faff52010-07-28 23:06:14 +00003351 break;
3352 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003353
Chris Lattner52b3c132010-09-01 00:20:33 +00003354 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003355 // known to pass in the high eightbyte of the result. We do this by forming a
3356 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003357 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003358 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003359
Chris Lattner1f3a0632010-07-29 21:42:50 +00003360 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003361}
3362
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003363ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003364 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3365 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003366 const
3367{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003368 Ty = useFirstFieldIfTransparentUnion(Ty);
3369
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003370 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003371 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003372
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003373 // Check some invariants.
3374 // FIXME: Enforce these by construction.
3375 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003376 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3377
3378 neededInt = 0;
3379 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003380 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003381 switch (Lo) {
3382 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003383 if (Hi == NoClass)
3384 return ABIArgInfo::getIgnore();
3385 // If the low part is just padding, it takes no register, leave ResType
3386 // null.
3387 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3388 "Unknown missing lo part");
3389 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003390
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003391 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3392 // on the stack.
3393 case Memory:
3394
3395 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3396 // COMPLEX_X87, it is passed in memory.
3397 case X87:
3398 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003399 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003400 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003401 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003402
3403 case SSEUp:
3404 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003405 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003406
3407 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3408 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3409 // and %r9 is used.
3410 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003411 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003412
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003413 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003414 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003415
3416 // If we have a sign or zero extended integer, make sure to return Extend
3417 // so that the parameter gets the right LLVM IR attributes.
3418 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3419 // Treat an enum type as its underlying type.
3420 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3421 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003422
Chris Lattner1f3a0632010-07-29 21:42:50 +00003423 if (Ty->isIntegralOrEnumerationType() &&
3424 Ty->isPromotableIntegerType())
3425 return ABIArgInfo::getExtend();
3426 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003427
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003428 break;
3429
3430 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3431 // available SSE register is used, the registers are taken in the
3432 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003433 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003434 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003435 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003436 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003437 break;
3438 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003439 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003440
Craig Topper8a13c412014-05-21 05:09:00 +00003441 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003442 switch (Hi) {
3443 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003444 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003445 // which is passed in memory.
3446 case Memory:
3447 case X87:
3448 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003449 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003450
3451 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003452
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003453 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003454 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003455 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003456 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003457
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003458 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3459 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003460 break;
3461
3462 // X87Up generally doesn't occur here (long double is passed in
3463 // memory), except in situations involving unions.
3464 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003465 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003466 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003467
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003468 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3469 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003470
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003471 ++neededSSE;
3472 break;
3473
3474 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3475 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003476 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003477 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003478 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003479 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003480 break;
3481 }
3482
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003483 // If a high part was specified, merge it together with the low part. It is
3484 // known to pass in the high eightbyte of the result. We do this by forming a
3485 // first class struct aggregate with the high and low part: {low, high}
3486 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003487 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003488
Chris Lattner1f3a0632010-07-29 21:42:50 +00003489 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003490}
3491
Erich Keane757d3172016-11-02 18:29:35 +00003492ABIArgInfo
3493X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3494 unsigned &NeededSSE) const {
3495 auto RT = Ty->getAs<RecordType>();
3496 assert(RT && "classifyRegCallStructType only valid with struct types");
3497
3498 if (RT->getDecl()->hasFlexibleArrayMember())
3499 return getIndirectReturnResult(Ty);
3500
3501 // Sum up bases
3502 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3503 if (CXXRD->isDynamicClass()) {
3504 NeededInt = NeededSSE = 0;
3505 return getIndirectReturnResult(Ty);
3506 }
3507
3508 for (const auto &I : CXXRD->bases())
3509 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3510 .isIndirect()) {
3511 NeededInt = NeededSSE = 0;
3512 return getIndirectReturnResult(Ty);
3513 }
3514 }
3515
3516 // Sum up members
3517 for (const auto *FD : RT->getDecl()->fields()) {
3518 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3519 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3520 .isIndirect()) {
3521 NeededInt = NeededSSE = 0;
3522 return getIndirectReturnResult(Ty);
3523 }
3524 } else {
3525 unsigned LocalNeededInt, LocalNeededSSE;
3526 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3527 LocalNeededSSE, true)
3528 .isIndirect()) {
3529 NeededInt = NeededSSE = 0;
3530 return getIndirectReturnResult(Ty);
3531 }
3532 NeededInt += LocalNeededInt;
3533 NeededSSE += LocalNeededSSE;
3534 }
3535 }
3536
3537 return ABIArgInfo::getDirect();
3538}
3539
3540ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3541 unsigned &NeededInt,
3542 unsigned &NeededSSE) const {
3543
3544 NeededInt = 0;
3545 NeededSSE = 0;
3546
3547 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3548}
3549
Chris Lattner22326a12010-07-29 02:31:05 +00003550void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003551
Erich Keane757d3172016-11-02 18:29:35 +00003552 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003553
3554 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003555 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3556 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3557 unsigned NeededInt, NeededSSE;
3558
Erich Keanede1b2a92017-07-21 18:50:36 +00003559 if (!getCXXABI().classifyReturnType(FI)) {
3560 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3561 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3562 FI.getReturnInfo() =
3563 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3564 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3565 FreeIntRegs -= NeededInt;
3566 FreeSSERegs -= NeededSSE;
3567 } else {
3568 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3569 }
3570 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3571 // Complex Long Double Type is passed in Memory when Regcall
3572 // calling convention is used.
3573 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3574 if (getContext().getCanonicalType(CT->getElementType()) ==
3575 getContext().LongDoubleTy)
3576 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3577 } else
3578 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3579 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003580
3581 // If the return value is indirect, then the hidden argument is consuming one
3582 // integer register.
3583 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003584 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003585
Peter Collingbournef7706832014-12-12 23:41:25 +00003586 // The chain argument effectively gives us another free register.
3587 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003588 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003589
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003590 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003591 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3592 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003593 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003594 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003595 it != ie; ++it, ++ArgNo) {
3596 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003597
Erich Keane757d3172016-11-02 18:29:35 +00003598 if (IsRegCall && it->type->isStructureOrClassType())
3599 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3600 else
3601 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3602 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003603
3604 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3605 // eightbyte of an argument, the whole argument is passed on the
3606 // stack. If registers have already been assigned for some
3607 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003608 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3609 FreeIntRegs -= NeededInt;
3610 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003611 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003612 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003613 }
3614 }
3615}
3616
John McCall7f416cc2015-09-08 08:05:57 +00003617static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3618 Address VAListAddr, QualType Ty) {
3619 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3620 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003621 llvm::Value *overflow_arg_area =
3622 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3623
3624 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3625 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003626 // It isn't stated explicitly in the standard, but in practice we use
3627 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003628 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3629 if (Align > CharUnits::fromQuantity(8)) {
3630 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3631 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003632 }
3633
3634 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003635 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003636 llvm::Value *Res =
3637 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003638 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003639
3640 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3641 // l->overflow_arg_area + sizeof(type).
3642 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3643 // an 8 byte boundary.
3644
3645 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003646 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003647 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003648 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3649 "overflow_arg_area.next");
3650 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3651
3652 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003653 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003654}
3655
John McCall7f416cc2015-09-08 08:05:57 +00003656Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3657 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003658 // Assume that va_list type is correct; should be pointer to LLVM type:
3659 // struct {
3660 // i32 gp_offset;
3661 // i32 fp_offset;
3662 // i8* overflow_arg_area;
3663 // i8* reg_save_area;
3664 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003665 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003666
John McCall7f416cc2015-09-08 08:05:57 +00003667 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003668 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003669 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003670
3671 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3672 // in the registers. If not go to step 7.
3673 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003674 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003675
3676 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3677 // general purpose registers needed to pass type and num_fp to hold
3678 // the number of floating point registers needed.
3679
3680 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3681 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3682 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3683 //
3684 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3685 // register save space).
3686
Craig Topper8a13c412014-05-21 05:09:00 +00003687 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003688 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3689 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003690 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003691 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003692 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3693 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003694 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003695 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3696 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003697 }
3698
3699 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003700 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003701 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3702 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003703 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3704 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003705 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3706 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003707 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3708 }
3709
3710 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3711 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3712 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3713 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3714
3715 // Emit code to load the value if it was passed in registers.
3716
3717 CGF.EmitBlock(InRegBlock);
3718
3719 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3720 // an offset of l->gp_offset and/or l->fp_offset. This may require
3721 // copying to a temporary location in case the parameter is passed
3722 // in different register classes or requires an alignment greater
3723 // than 8 for general purpose registers and 16 for XMM registers.
3724 //
3725 // FIXME: This really results in shameful code when we end up needing to
3726 // collect arguments from different places; often what should result in a
3727 // simple assembling of a structure from scattered addresses has many more
3728 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003729 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003730 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3731 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3732 "reg_save_area");
3733
3734 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003735 if (neededInt && neededSSE) {
3736 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003737 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003738 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003739 Address Tmp = CGF.CreateMemTemp(Ty);
3740 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003741 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003742 llvm::Type *TyLo = ST->getElementType(0);
3743 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003744 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003745 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003746 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3747 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003748 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3749 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003750 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3751 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003752
John McCall7f416cc2015-09-08 08:05:57 +00003753 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003754 // FIXME: Our choice of alignment here and below is probably pessimistic.
3755 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3756 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3757 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003758 CGF.Builder.CreateStore(V,
3759 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3760
3761 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003762 V = CGF.Builder.CreateAlignedLoad(
3763 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3764 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003765 CharUnits Offset = CharUnits::fromQuantity(
3766 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3767 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3768
3769 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003770 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003771 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3772 CharUnits::fromQuantity(8));
3773 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003774
3775 // Copy to a temporary if necessary to ensure the appropriate alignment.
3776 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003777 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003778 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003779 CharUnits TyAlign = SizeAlign.second;
3780
3781 // Copy into a temporary if the type is more aligned than the
3782 // register save area.
3783 if (TyAlign.getQuantity() > 8) {
3784 Address Tmp = CGF.CreateMemTemp(Ty);
3785 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003786 RegAddr = Tmp;
3787 }
John McCall7f416cc2015-09-08 08:05:57 +00003788
Chris Lattner0cf24192010-06-28 20:05:43 +00003789 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003790 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3791 CharUnits::fromQuantity(16));
3792 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003793 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003794 assert(neededSSE == 2 && "Invalid number of needed registers!");
3795 // SSE registers are spaced 16 bytes apart in the register save
3796 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003797 // The ABI isn't explicit about this, but it seems reasonable
3798 // to assume that the slots are 16-byte aligned, since the stack is
3799 // naturally 16-byte aligned and the prologue is expected to store
3800 // all the SSE registers to the RSA.
3801 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3802 CharUnits::fromQuantity(16));
3803 Address RegAddrHi =
3804 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3805 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003806 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003807 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003808 llvm::Value *V;
3809 Address Tmp = CGF.CreateMemTemp(Ty);
3810 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3811 V = CGF.Builder.CreateLoad(
3812 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3813 CGF.Builder.CreateStore(V,
3814 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3815 V = CGF.Builder.CreateLoad(
3816 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3817 CGF.Builder.CreateStore(V,
3818 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3819
3820 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003821 }
3822
3823 // AMD64-ABI 3.5.7p5: Step 5. Set:
3824 // l->gp_offset = l->gp_offset + num_gp * 8
3825 // l->fp_offset = l->fp_offset + num_fp * 16.
3826 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003827 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003828 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3829 gp_offset_p);
3830 }
3831 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003832 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003833 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3834 fp_offset_p);
3835 }
3836 CGF.EmitBranch(ContBlock);
3837
3838 // Emit code to load the value if it was passed in memory.
3839
3840 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003841 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003842
3843 // Return the appropriate result.
3844
3845 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003846 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3847 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003848 return ResAddr;
3849}
3850
Charles Davisc7d5c942015-09-17 20:55:33 +00003851Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3852 QualType Ty) const {
3853 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3854 CGF.getContext().getTypeInfoInChars(Ty),
3855 CharUnits::fromQuantity(8),
3856 /*allowHigherAlign*/ false);
3857}
3858
Erich Keane521ed962017-01-05 00:20:51 +00003859ABIArgInfo
3860WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3861 const ABIArgInfo &current) const {
3862 // Assumes vectorCall calling convention.
3863 const Type *Base = nullptr;
3864 uint64_t NumElts = 0;
3865
3866 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3867 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3868 FreeSSERegs -= NumElts;
3869 return getDirectX86Hva();
3870 }
3871 return current;
3872}
3873
Reid Kleckner80944df2014-10-31 22:00:51 +00003874ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003875 bool IsReturnType, bool IsVectorCall,
3876 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003877
3878 if (Ty->isVoidType())
3879 return ABIArgInfo::getIgnore();
3880
3881 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3882 Ty = EnumTy->getDecl()->getIntegerType();
3883
Reid Kleckner80944df2014-10-31 22:00:51 +00003884 TypeInfo Info = getContext().getTypeInfo(Ty);
3885 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003886 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003887
Reid Kleckner9005f412014-05-02 00:51:20 +00003888 const RecordType *RT = Ty->getAs<RecordType>();
3889 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003890 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003891 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003892 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003893 }
3894
3895 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003896 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003897
Reid Kleckner9005f412014-05-02 00:51:20 +00003898 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003899
Reid Kleckner80944df2014-10-31 22:00:51 +00003900 const Type *Base = nullptr;
3901 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003902 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3903 // other targets.
3904 if ((IsVectorCall || IsRegCall) &&
3905 isHomogeneousAggregate(Ty, Base, NumElts)) {
3906 if (IsRegCall) {
3907 if (FreeSSERegs >= NumElts) {
3908 FreeSSERegs -= NumElts;
3909 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3910 return ABIArgInfo::getDirect();
3911 return ABIArgInfo::getExpand();
3912 }
3913 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3914 } else if (IsVectorCall) {
3915 if (FreeSSERegs >= NumElts &&
3916 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3917 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003918 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003919 } else if (IsReturnType) {
3920 return ABIArgInfo::getExpand();
3921 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3922 // HVAs are delayed and reclassified in the 2nd step.
3923 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3924 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003925 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003926 }
3927
Reid Klecknerec87fec2014-05-02 01:17:12 +00003928 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003929 // If the member pointer is represented by an LLVM int or ptr, pass it
3930 // directly.
3931 llvm::Type *LLTy = CGT.ConvertType(Ty);
3932 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3933 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003934 }
3935
Michael Kuperstein4f818702015-02-24 09:35:58 +00003936 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003937 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3938 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003939 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003940 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003941
Reid Kleckner9005f412014-05-02 00:51:20 +00003942 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003943 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003944 }
3945
Julien Lerouge10dcff82014-08-27 00:36:55 +00003946 // Bool type is always extended to the ABI, other builtin types are not
3947 // extended.
3948 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3949 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003950 return ABIArgInfo::getExtend();
3951
Reid Kleckner11a17192015-10-28 22:29:52 +00003952 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3953 // passes them indirectly through memory.
3954 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3955 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003956 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003957 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3958 }
3959
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003960 return ABIArgInfo::getDirect();
3961}
3962
Erich Keane521ed962017-01-05 00:20:51 +00003963void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3964 unsigned FreeSSERegs,
3965 bool IsVectorCall,
3966 bool IsRegCall) const {
3967 unsigned Count = 0;
3968 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003969 // Vectorcall in x64 only permits the first 6 arguments to be passed
3970 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003971 if (Count < VectorcallMaxParamNumAsReg)
3972 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3973 else {
3974 // Since these cannot be passed in registers, pretend no registers
3975 // are left.
3976 unsigned ZeroSSERegsAvail = 0;
3977 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3978 IsVectorCall, IsRegCall);
3979 }
3980 ++Count;
3981 }
3982
Erich Keane521ed962017-01-05 00:20:51 +00003983 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003984 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003985 }
3986}
3987
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003988void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003989 bool IsVectorCall =
3990 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003991 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003992
Erich Keane757d3172016-11-02 18:29:35 +00003993 unsigned FreeSSERegs = 0;
3994 if (IsVectorCall) {
3995 // We can use up to 4 SSE return registers with vectorcall.
3996 FreeSSERegs = 4;
3997 } else if (IsRegCall) {
3998 // RegCall gives us 16 SSE registers.
3999 FreeSSERegs = 16;
4000 }
4001
Reid Kleckner80944df2014-10-31 22:00:51 +00004002 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00004003 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4004 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00004005
Erich Keane757d3172016-11-02 18:29:35 +00004006 if (IsVectorCall) {
4007 // We can use up to 6 SSE register parameters with vectorcall.
4008 FreeSSERegs = 6;
4009 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00004010 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00004011 FreeSSERegs = 16;
4012 }
4013
Erich Keane521ed962017-01-05 00:20:51 +00004014 if (IsVectorCall) {
4015 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4016 } else {
4017 for (auto &I : FI.arguments())
4018 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4019 }
4020
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004021}
4022
John McCall7f416cc2015-09-08 08:05:57 +00004023Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4024 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004025
4026 bool IsIndirect = false;
4027
4028 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4029 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4030 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4031 uint64_t Width = getContext().getTypeSize(Ty);
4032 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4033 }
4034
4035 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004036 CGF.getContext().getTypeInfoInChars(Ty),
4037 CharUnits::fromQuantity(8),
4038 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004039}
Chris Lattner0cf24192010-06-28 20:05:43 +00004040
John McCallea8d8bb2010-03-11 00:10:12 +00004041// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004042namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004043/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4044class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004045bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00004046public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004047 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4048 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004049
John McCall7f416cc2015-09-08 08:05:57 +00004050 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4051 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004052};
4053
4054class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4055public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004056 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4057 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004058
Craig Topper4f12f102014-03-12 06:41:41 +00004059 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004060 // This is recovered from gcc output.
4061 return 1; // r1 is the dedicated stack pointer
4062 }
4063
4064 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004065 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004066};
4067
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004068}
John McCallea8d8bb2010-03-11 00:10:12 +00004069
James Y Knight29b5f082016-02-24 02:59:33 +00004070// TODO: this implementation is now likely redundant with
4071// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004072Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4073 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004074 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004075 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4076 // TODO: Implement this. For now ignore.
4077 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004078 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004079 }
4080
John McCall7f416cc2015-09-08 08:05:57 +00004081 // struct __va_list_tag {
4082 // unsigned char gpr;
4083 // unsigned char fpr;
4084 // unsigned short reserved;
4085 // void *overflow_arg_area;
4086 // void *reg_save_area;
4087 // };
4088
Roman Divacky8a12d842014-11-03 18:32:54 +00004089 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004090 bool isInt =
4091 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004092 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004093
4094 // All aggregates are passed indirectly? That doesn't seem consistent
4095 // with the argument-lowering code.
4096 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004097
4098 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004099
4100 // The calling convention either uses 1-2 GPRs or 1 FPR.
4101 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004102 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004103 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4104 } else {
4105 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004106 }
John McCall7f416cc2015-09-08 08:05:57 +00004107
4108 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4109
4110 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004111 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004112 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4113 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4114 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004115
Eric Christopher7565e0d2015-05-29 23:09:49 +00004116 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004117 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004118
4119 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4120 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4121 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4122
4123 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4124
John McCall7f416cc2015-09-08 08:05:57 +00004125 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4126 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004127
John McCall7f416cc2015-09-08 08:05:57 +00004128 // Case 1: consume registers.
4129 Address RegAddr = Address::invalid();
4130 {
4131 CGF.EmitBlock(UsingRegs);
4132
4133 Address RegSaveAreaPtr =
4134 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4135 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4136 CharUnits::fromQuantity(8));
4137 assert(RegAddr.getElementType() == CGF.Int8Ty);
4138
4139 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004140 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004141 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4142 CharUnits::fromQuantity(32));
4143 }
4144
4145 // Get the address of the saved value by scaling the number of
4146 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004147 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004148 llvm::Value *RegOffset =
4149 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4150 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4151 RegAddr.getPointer(), RegOffset),
4152 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4153 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4154
4155 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004156 NumRegs =
4157 Builder.CreateAdd(NumRegs,
4158 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004159 Builder.CreateStore(NumRegs, NumRegsAddr);
4160
4161 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004162 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004163
John McCall7f416cc2015-09-08 08:05:57 +00004164 // Case 2: consume space in the overflow area.
4165 Address MemAddr = Address::invalid();
4166 {
4167 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004168
Roman Divacky039b9702016-02-20 08:31:24 +00004169 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4170
John McCall7f416cc2015-09-08 08:05:57 +00004171 // Everything in the overflow area is rounded up to a size of at least 4.
4172 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4173
4174 CharUnits Size;
4175 if (!isIndirect) {
4176 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004177 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004178 } else {
4179 Size = CGF.getPointerSize();
4180 }
4181
4182 Address OverflowAreaAddr =
4183 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004184 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004185 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004186 // Round up address of argument to alignment
4187 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4188 if (Align > OverflowAreaAlign) {
4189 llvm::Value *Ptr = OverflowArea.getPointer();
4190 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4191 Align);
4192 }
4193
John McCall7f416cc2015-09-08 08:05:57 +00004194 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4195
4196 // Increase the overflow area.
4197 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4198 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4199 CGF.EmitBranch(Cont);
4200 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004201
4202 CGF.EmitBlock(Cont);
4203
John McCall7f416cc2015-09-08 08:05:57 +00004204 // Merge the cases with a phi.
4205 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4206 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004207
John McCall7f416cc2015-09-08 08:05:57 +00004208 // Load the pointer if the argument was passed indirectly.
4209 if (isIndirect) {
4210 Result = Address(Builder.CreateLoad(Result, "aggr"),
4211 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004212 }
4213
4214 return Result;
4215}
4216
John McCallea8d8bb2010-03-11 00:10:12 +00004217bool
4218PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4219 llvm::Value *Address) const {
4220 // This is calculated from the LLVM and GCC tables and verified
4221 // against gcc output. AFAIK all ABIs use the same encoding.
4222
4223 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004224
Chris Lattnerece04092012-02-07 00:39:47 +00004225 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004226 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4227 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4228 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4229
4230 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004231 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004232
4233 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004234 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004235
4236 // 64-76 are various 4-byte special-purpose registers:
4237 // 64: mq
4238 // 65: lr
4239 // 66: ctr
4240 // 67: ap
4241 // 68-75 cr0-7
4242 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004243 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004244
4245 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004246 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004247
4248 // 109: vrsave
4249 // 110: vscr
4250 // 111: spe_acc
4251 // 112: spefscr
4252 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004253 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004254
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004255 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004256}
4257
Roman Divackyd966e722012-05-09 18:22:46 +00004258// PowerPC-64
4259
4260namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004261/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004262class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004263public:
4264 enum ABIKind {
4265 ELFv1 = 0,
4266 ELFv2
4267 };
4268
4269private:
4270 static const unsigned GPRBits = 64;
4271 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004272 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004273 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004274
4275 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4276 // will be passed in a QPX register.
4277 bool IsQPXVectorTy(const Type *Ty) const {
4278 if (!HasQPX)
4279 return false;
4280
4281 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4282 unsigned NumElements = VT->getNumElements();
4283 if (NumElements == 1)
4284 return false;
4285
4286 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4287 if (getContext().getTypeSize(Ty) <= 256)
4288 return true;
4289 } else if (VT->getElementType()->
4290 isSpecificBuiltinType(BuiltinType::Float)) {
4291 if (getContext().getTypeSize(Ty) <= 128)
4292 return true;
4293 }
4294 }
4295
4296 return false;
4297 }
4298
4299 bool IsQPXVectorTy(QualType Ty) const {
4300 return IsQPXVectorTy(Ty.getTypePtr());
4301 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004302
4303public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004304 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4305 bool SoftFloatABI)
4306 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4307 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004308
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004309 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004310 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004311
4312 ABIArgInfo classifyReturnType(QualType RetTy) const;
4313 ABIArgInfo classifyArgumentType(QualType Ty) const;
4314
Reid Klecknere9f6a712014-10-31 17:10:41 +00004315 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4316 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4317 uint64_t Members) const override;
4318
Bill Schmidt84d37792012-10-12 19:26:17 +00004319 // TODO: We can add more logic to computeInfo to improve performance.
4320 // Example: For aggregate arguments that fit in a register, we could
4321 // use getDirectInReg (as is done below for structs containing a single
4322 // floating-point value) to avoid pushing them to memory on function
4323 // entry. This would require changing the logic in PPCISelLowering
4324 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004325 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004326 if (!getCXXABI().classifyReturnType(FI))
4327 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004328 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004329 // We rely on the default argument classification for the most part.
4330 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004331 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004332 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004333 if (T) {
4334 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004335 if (IsQPXVectorTy(T) ||
4336 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004337 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004338 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004339 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004340 continue;
4341 }
4342 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004343 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004344 }
4345 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004346
John McCall7f416cc2015-09-08 08:05:57 +00004347 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4348 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004349};
4350
4351class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004352
Bill Schmidt25cb3492012-10-03 19:18:57 +00004353public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004354 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004355 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4356 bool SoftFloatABI)
4357 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4358 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004359
Craig Topper4f12f102014-03-12 06:41:41 +00004360 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004361 // This is recovered from gcc output.
4362 return 1; // r1 is the dedicated stack pointer
4363 }
4364
4365 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004366 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004367};
4368
Roman Divackyd966e722012-05-09 18:22:46 +00004369class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4370public:
4371 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4372
Craig Topper4f12f102014-03-12 06:41:41 +00004373 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004374 // This is recovered from gcc output.
4375 return 1; // r1 is the dedicated stack pointer
4376 }
4377
4378 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004379 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004380};
4381
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004382}
Roman Divackyd966e722012-05-09 18:22:46 +00004383
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004384// Return true if the ABI requires Ty to be passed sign- or zero-
4385// extended to 64 bits.
4386bool
4387PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4388 // Treat an enum type as its underlying type.
4389 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4390 Ty = EnumTy->getDecl()->getIntegerType();
4391
4392 // Promotable integer types are required to be promoted by the ABI.
4393 if (Ty->isPromotableIntegerType())
4394 return true;
4395
4396 // In addition to the usual promotable integer types, we also need to
4397 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4398 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4399 switch (BT->getKind()) {
4400 case BuiltinType::Int:
4401 case BuiltinType::UInt:
4402 return true;
4403 default:
4404 break;
4405 }
4406
4407 return false;
4408}
4409
John McCall7f416cc2015-09-08 08:05:57 +00004410/// isAlignedParamType - Determine whether a type requires 16-byte or
4411/// higher alignment in the parameter area. Always returns at least 8.
4412CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004413 // Complex types are passed just like their elements.
4414 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4415 Ty = CTy->getElementType();
4416
4417 // Only vector types of size 16 bytes need alignment (larger types are
4418 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004419 if (IsQPXVectorTy(Ty)) {
4420 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004421 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004422
John McCall7f416cc2015-09-08 08:05:57 +00004423 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004424 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004425 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004426 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004427
4428 // For single-element float/vector structs, we consider the whole type
4429 // to have the same alignment requirements as its single element.
4430 const Type *AlignAsType = nullptr;
4431 const Type *EltType = isSingleElementStruct(Ty, getContext());
4432 if (EltType) {
4433 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004434 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004435 getContext().getTypeSize(EltType) == 128) ||
4436 (BT && BT->isFloatingPoint()))
4437 AlignAsType = EltType;
4438 }
4439
Ulrich Weigandb7122372014-07-21 00:48:09 +00004440 // Likewise for ELFv2 homogeneous aggregates.
4441 const Type *Base = nullptr;
4442 uint64_t Members = 0;
4443 if (!AlignAsType && Kind == ELFv2 &&
4444 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4445 AlignAsType = Base;
4446
Ulrich Weigand581badc2014-07-10 17:20:07 +00004447 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004448 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4449 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004450 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004451
John McCall7f416cc2015-09-08 08:05:57 +00004452 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004453 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004454 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004455 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004456
4457 // Otherwise, we only need alignment for any aggregate type that
4458 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004459 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4460 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004461 return CharUnits::fromQuantity(32);
4462 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004463 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004464
John McCall7f416cc2015-09-08 08:05:57 +00004465 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004466}
4467
Ulrich Weigandb7122372014-07-21 00:48:09 +00004468/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4469/// aggregate. Base is set to the base element type, and Members is set
4470/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004471bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4472 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004473 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4474 uint64_t NElements = AT->getSize().getZExtValue();
4475 if (NElements == 0)
4476 return false;
4477 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4478 return false;
4479 Members *= NElements;
4480 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4481 const RecordDecl *RD = RT->getDecl();
4482 if (RD->hasFlexibleArrayMember())
4483 return false;
4484
4485 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004486
4487 // If this is a C++ record, check the bases first.
4488 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4489 for (const auto &I : CXXRD->bases()) {
4490 // Ignore empty records.
4491 if (isEmptyRecord(getContext(), I.getType(), true))
4492 continue;
4493
4494 uint64_t FldMembers;
4495 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4496 return false;
4497
4498 Members += FldMembers;
4499 }
4500 }
4501
Ulrich Weigandb7122372014-07-21 00:48:09 +00004502 for (const auto *FD : RD->fields()) {
4503 // Ignore (non-zero arrays of) empty records.
4504 QualType FT = FD->getType();
4505 while (const ConstantArrayType *AT =
4506 getContext().getAsConstantArrayType(FT)) {
4507 if (AT->getSize().getZExtValue() == 0)
4508 return false;
4509 FT = AT->getElementType();
4510 }
4511 if (isEmptyRecord(getContext(), FT, true))
4512 continue;
4513
4514 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4515 if (getContext().getLangOpts().CPlusPlus &&
4516 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4517 continue;
4518
4519 uint64_t FldMembers;
4520 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4521 return false;
4522
4523 Members = (RD->isUnion() ?
4524 std::max(Members, FldMembers) : Members + FldMembers);
4525 }
4526
4527 if (!Base)
4528 return false;
4529
4530 // Ensure there is no padding.
4531 if (getContext().getTypeSize(Base) * Members !=
4532 getContext().getTypeSize(Ty))
4533 return false;
4534 } else {
4535 Members = 1;
4536 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4537 Members = 2;
4538 Ty = CT->getElementType();
4539 }
4540
Reid Klecknere9f6a712014-10-31 17:10:41 +00004541 // Most ABIs only support float, double, and some vector type widths.
4542 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004543 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004544
4545 // The base type must be the same for all members. Types that
4546 // agree in both total size and mode (float vs. vector) are
4547 // treated as being equivalent here.
4548 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004549 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004550 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004551 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4552 // so make sure to widen it explicitly.
4553 if (const VectorType *VT = Base->getAs<VectorType>()) {
4554 QualType EltTy = VT->getElementType();
4555 unsigned NumElements =
4556 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4557 Base = getContext()
4558 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4559 .getTypePtr();
4560 }
4561 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004562
4563 if (Base->isVectorType() != TyPtr->isVectorType() ||
4564 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4565 return false;
4566 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004567 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4568}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004569
Reid Klecknere9f6a712014-10-31 17:10:41 +00004570bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4571 // Homogeneous aggregates for ELFv2 must have base types of float,
4572 // double, long double, or 128-bit vectors.
4573 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4574 if (BT->getKind() == BuiltinType::Float ||
4575 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004576 BT->getKind() == BuiltinType::LongDouble) {
4577 if (IsSoftFloatABI)
4578 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004579 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004580 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004581 }
4582 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004583 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004584 return true;
4585 }
4586 return false;
4587}
4588
4589bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4590 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004591 // Vector types require one register, floating point types require one
4592 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004593 uint32_t NumRegs =
4594 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004595
4596 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004597 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004598}
4599
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004600ABIArgInfo
4601PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004602 Ty = useFirstFieldIfTransparentUnion(Ty);
4603
Bill Schmidt90b22c92012-11-27 02:46:43 +00004604 if (Ty->isAnyComplexType())
4605 return ABIArgInfo::getDirect();
4606
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004607 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4608 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004609 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004610 uint64_t Size = getContext().getTypeSize(Ty);
4611 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004612 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004613 else if (Size < 128) {
4614 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4615 return ABIArgInfo::getDirect(CoerceTy);
4616 }
4617 }
4618
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004619 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004620 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004621 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004622
John McCall7f416cc2015-09-08 08:05:57 +00004623 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4624 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004625
4626 // ELFv2 homogeneous aggregates are passed as array types.
4627 const Type *Base = nullptr;
4628 uint64_t Members = 0;
4629 if (Kind == ELFv2 &&
4630 isHomogeneousAggregate(Ty, Base, Members)) {
4631 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4632 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4633 return ABIArgInfo::getDirect(CoerceTy);
4634 }
4635
Ulrich Weigand601957f2014-07-21 00:56:36 +00004636 // If an aggregate may end up fully in registers, we do not
4637 // use the ByVal method, but pass the aggregate as array.
4638 // This is usually beneficial since we avoid forcing the
4639 // back-end to store the argument to memory.
4640 uint64_t Bits = getContext().getTypeSize(Ty);
4641 if (Bits > 0 && Bits <= 8 * GPRBits) {
4642 llvm::Type *CoerceTy;
4643
4644 // Types up to 8 bytes are passed as integer type (which will be
4645 // properly aligned in the argument save area doubleword).
4646 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004647 CoerceTy =
4648 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004649 // Larger types are passed as arrays, with the base type selected
4650 // according to the required alignment in the save area.
4651 else {
4652 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004653 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004654 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4655 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4656 }
4657
4658 return ABIArgInfo::getDirect(CoerceTy);
4659 }
4660
Ulrich Weigandb7122372014-07-21 00:48:09 +00004661 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004662 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4663 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004664 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004665 }
4666
4667 return (isPromotableTypeForABI(Ty) ?
4668 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4669}
4670
4671ABIArgInfo
4672PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4673 if (RetTy->isVoidType())
4674 return ABIArgInfo::getIgnore();
4675
Bill Schmidta3d121c2012-12-17 04:20:17 +00004676 if (RetTy->isAnyComplexType())
4677 return ABIArgInfo::getDirect();
4678
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004679 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4680 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004681 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004682 uint64_t Size = getContext().getTypeSize(RetTy);
4683 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004684 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004685 else if (Size < 128) {
4686 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4687 return ABIArgInfo::getDirect(CoerceTy);
4688 }
4689 }
4690
Ulrich Weigandb7122372014-07-21 00:48:09 +00004691 if (isAggregateTypeForABI(RetTy)) {
4692 // ELFv2 homogeneous aggregates are returned as array types.
4693 const Type *Base = nullptr;
4694 uint64_t Members = 0;
4695 if (Kind == ELFv2 &&
4696 isHomogeneousAggregate(RetTy, Base, Members)) {
4697 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4698 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4699 return ABIArgInfo::getDirect(CoerceTy);
4700 }
4701
4702 // ELFv2 small aggregates are returned in up to two registers.
4703 uint64_t Bits = getContext().getTypeSize(RetTy);
4704 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4705 if (Bits == 0)
4706 return ABIArgInfo::getIgnore();
4707
4708 llvm::Type *CoerceTy;
4709 if (Bits > GPRBits) {
4710 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004711 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004712 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004713 CoerceTy =
4714 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004715 return ABIArgInfo::getDirect(CoerceTy);
4716 }
4717
4718 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004719 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004720 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004721
4722 return (isPromotableTypeForABI(RetTy) ?
4723 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4724}
4725
Bill Schmidt25cb3492012-10-03 19:18:57 +00004726// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004727Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4728 QualType Ty) const {
4729 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4730 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004731
John McCall7f416cc2015-09-08 08:05:57 +00004732 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004733
Bill Schmidt924c4782013-01-14 17:45:36 +00004734 // If we have a complex type and the base type is smaller than 8 bytes,
4735 // the ABI calls for the real and imaginary parts to be right-adjusted
4736 // in separate doublewords. However, Clang expects us to produce a
4737 // pointer to a structure with the two parts packed tightly. So generate
4738 // loads of the real and imaginary parts relative to the va_list pointer,
4739 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004740 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4741 CharUnits EltSize = TypeInfo.first / 2;
4742 if (EltSize < SlotSize) {
4743 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4744 SlotSize * 2, SlotSize,
4745 SlotSize, /*AllowHigher*/ true);
4746
4747 Address RealAddr = Addr;
4748 Address ImagAddr = RealAddr;
4749 if (CGF.CGM.getDataLayout().isBigEndian()) {
4750 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4751 SlotSize - EltSize);
4752 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4753 2 * SlotSize - EltSize);
4754 } else {
4755 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4756 }
4757
4758 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4759 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4760 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4761 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4762 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4763
4764 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4765 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4766 /*init*/ true);
4767 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004768 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004769 }
4770
John McCall7f416cc2015-09-08 08:05:57 +00004771 // Otherwise, just use the general rule.
4772 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4773 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004774}
4775
4776static bool
4777PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4778 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004779 // This is calculated from the LLVM and GCC tables and verified
4780 // against gcc output. AFAIK all ABIs use the same encoding.
4781
4782 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4783
4784 llvm::IntegerType *i8 = CGF.Int8Ty;
4785 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4786 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4787 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4788
4789 // 0-31: r0-31, the 8-byte general-purpose registers
4790 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4791
4792 // 32-63: fp0-31, the 8-byte floating-point registers
4793 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4794
Hal Finkel84832a72016-08-30 02:38:34 +00004795 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004796 // 64: mq
4797 // 65: lr
4798 // 66: ctr
4799 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004800 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4801
4802 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004803 // 68-75 cr0-7
4804 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004805 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004806
4807 // 77-108: v0-31, the 16-byte vector registers
4808 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4809
4810 // 109: vrsave
4811 // 110: vscr
4812 // 111: spe_acc
4813 // 112: spefscr
4814 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004815 // 114: tfhar
4816 // 115: tfiar
4817 // 116: texasr
4818 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004819
4820 return false;
4821}
John McCallea8d8bb2010-03-11 00:10:12 +00004822
Bill Schmidt25cb3492012-10-03 19:18:57 +00004823bool
4824PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4825 CodeGen::CodeGenFunction &CGF,
4826 llvm::Value *Address) const {
4827
4828 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4829}
4830
4831bool
4832PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4833 llvm::Value *Address) const {
4834
4835 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4836}
4837
Chris Lattner0cf24192010-06-28 20:05:43 +00004838//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004839// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004840//===----------------------------------------------------------------------===//
4841
4842namespace {
4843
John McCall12f23522016-04-04 18:33:08 +00004844class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004845public:
4846 enum ABIKind {
4847 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004848 DarwinPCS,
4849 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004850 };
4851
4852private:
4853 ABIKind Kind;
4854
4855public:
John McCall12f23522016-04-04 18:33:08 +00004856 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4857 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004858
4859private:
4860 ABIKind getABIKind() const { return Kind; }
4861 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4862
4863 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004864 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004865 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4866 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4867 uint64_t Members) const override;
4868
Tim Northovera2ee4332014-03-29 15:09:45 +00004869 bool isIllegalVectorType(QualType Ty) const;
4870
David Blaikie1cbb9712014-11-14 19:09:44 +00004871 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004872 if (!getCXXABI().classifyReturnType(FI))
4873 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004874
Tim Northoverb047bfa2014-11-27 21:02:49 +00004875 for (auto &it : FI.arguments())
4876 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004877 }
4878
John McCall7f416cc2015-09-08 08:05:57 +00004879 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4880 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004881
John McCall7f416cc2015-09-08 08:05:57 +00004882 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4883 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004884
John McCall7f416cc2015-09-08 08:05:57 +00004885 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4886 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004887 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4888 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4889 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004890 }
John McCall12f23522016-04-04 18:33:08 +00004891
Martin Storsjo502de222017-07-13 17:59:14 +00004892 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4893 QualType Ty) const override;
4894
John McCall12f23522016-04-04 18:33:08 +00004895 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4896 ArrayRef<llvm::Type*> scalars,
4897 bool asReturnValue) const override {
4898 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4899 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004900 bool isSwiftErrorInRegister() const override {
4901 return true;
4902 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004903
4904 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4905 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004906};
4907
Tim Northover573cbee2014-05-24 12:52:07 +00004908class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004909public:
Tim Northover573cbee2014-05-24 12:52:07 +00004910 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4911 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004912
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004913 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004914 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004915 }
4916
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004917 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4918 return 31;
4919 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004920
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004921 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004922};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004923
4924class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4925public:
4926 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4927 : AArch64TargetCodeGenInfo(CGT, K) {}
4928
4929 void getDependentLibraryOption(llvm::StringRef Lib,
4930 llvm::SmallString<24> &Opt) const override {
4931 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4932 }
4933
4934 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4935 llvm::SmallString<32> &Opt) const override {
4936 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4937 }
4938};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004939}
Tim Northovera2ee4332014-03-29 15:09:45 +00004940
Tim Northoverb047bfa2014-11-27 21:02:49 +00004941ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004942 Ty = useFirstFieldIfTransparentUnion(Ty);
4943
Tim Northovera2ee4332014-03-29 15:09:45 +00004944 // Handle illegal vector types here.
4945 if (isIllegalVectorType(Ty)) {
4946 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004947 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004948 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004949 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4950 return ABIArgInfo::getDirect(ResType);
4951 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004952 if (Size <= 32) {
4953 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004954 return ABIArgInfo::getDirect(ResType);
4955 }
4956 if (Size == 64) {
4957 llvm::Type *ResType =
4958 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004959 return ABIArgInfo::getDirect(ResType);
4960 }
4961 if (Size == 128) {
4962 llvm::Type *ResType =
4963 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004964 return ABIArgInfo::getDirect(ResType);
4965 }
John McCall7f416cc2015-09-08 08:05:57 +00004966 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004967 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004968
4969 if (!isAggregateTypeForABI(Ty)) {
4970 // Treat an enum type as its underlying type.
4971 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4972 Ty = EnumTy->getDecl()->getIntegerType();
4973
Tim Northovera2ee4332014-03-29 15:09:45 +00004974 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4975 ? ABIArgInfo::getExtend()
4976 : ABIArgInfo::getDirect());
4977 }
4978
4979 // Structures with either a non-trivial destructor or a non-trivial
4980 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004981 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004982 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4983 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004984 }
4985
4986 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4987 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00004988 uint64_t Size = getContext().getTypeSize(Ty);
4989 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4990 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004991 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4992 return ABIArgInfo::getIgnore();
4993
Tim Northover23bcad22017-05-05 22:36:06 +00004994 // GNU C mode. The only argument that gets ignored is an empty one with size
4995 // 0.
4996 if (IsEmpty && Size == 0)
4997 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00004998 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4999 }
5000
5001 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00005002 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005003 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005004 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00005005 return ABIArgInfo::getDirect(
5006 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00005007 }
5008
5009 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005010 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005011 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5012 // same size and alignment.
5013 if (getTarget().isRenderScriptTarget()) {
5014 return coerceToIntArray(Ty, getContext(), getVMContext());
5015 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00005016 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005017 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005018
Tim Northovera2ee4332014-03-29 15:09:45 +00005019 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5020 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005021 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005022 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5023 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5024 }
5025 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5026 }
5027
John McCall7f416cc2015-09-08 08:05:57 +00005028 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005029}
5030
Tim Northover573cbee2014-05-24 12:52:07 +00005031ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005032 if (RetTy->isVoidType())
5033 return ABIArgInfo::getIgnore();
5034
5035 // Large vector types should be returned via memory.
5036 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005037 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005038
5039 if (!isAggregateTypeForABI(RetTy)) {
5040 // Treat an enum type as its underlying type.
5041 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5042 RetTy = EnumTy->getDecl()->getIntegerType();
5043
Tim Northover4dab6982014-04-18 13:46:08 +00005044 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5045 ? ABIArgInfo::getExtend()
5046 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005047 }
5048
Tim Northover23bcad22017-05-05 22:36:06 +00005049 uint64_t Size = getContext().getTypeSize(RetTy);
5050 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005051 return ABIArgInfo::getIgnore();
5052
Craig Topper8a13c412014-05-21 05:09:00 +00005053 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005054 uint64_t Members = 0;
5055 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005056 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5057 return ABIArgInfo::getDirect();
5058
5059 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005060 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005061 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5062 // same size and alignment.
5063 if (getTarget().isRenderScriptTarget()) {
5064 return coerceToIntArray(RetTy, getContext(), getVMContext());
5065 }
Pete Cooper635b5092015-04-17 22:16:24 +00005066 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005067 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005068
5069 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5070 // For aggregates with 16-byte alignment, we use i128.
5071 if (Alignment < 128 && Size == 128) {
5072 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5073 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5074 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005075 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5076 }
5077
John McCall7f416cc2015-09-08 08:05:57 +00005078 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005079}
5080
Tim Northover573cbee2014-05-24 12:52:07 +00005081/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5082bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005083 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5084 // Check whether VT is legal.
5085 unsigned NumElements = VT->getNumElements();
5086 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005087 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005088 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005089 return true;
5090 return Size != 64 && (Size != 128 || NumElements == 1);
5091 }
5092 return false;
5093}
5094
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005095bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5096 llvm::Type *eltTy,
5097 unsigned elts) const {
5098 if (!llvm::isPowerOf2_32(elts))
5099 return false;
5100 if (totalSize.getQuantity() != 8 &&
5101 (totalSize.getQuantity() != 16 || elts == 1))
5102 return false;
5103 return true;
5104}
5105
Reid Klecknere9f6a712014-10-31 17:10:41 +00005106bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5107 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5108 // point type or a short-vector type. This is the same as the 32-bit ABI,
5109 // but with the difference that any floating-point type is allowed,
5110 // including __fp16.
5111 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5112 if (BT->isFloatingPoint())
5113 return true;
5114 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5115 unsigned VecSize = getContext().getTypeSize(VT);
5116 if (VecSize == 64 || VecSize == 128)
5117 return true;
5118 }
5119 return false;
5120}
5121
5122bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5123 uint64_t Members) const {
5124 return Members <= 4;
5125}
5126
John McCall7f416cc2015-09-08 08:05:57 +00005127Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005128 QualType Ty,
5129 CodeGenFunction &CGF) const {
5130 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005131 bool IsIndirect = AI.isIndirect();
5132
Tim Northoverb047bfa2014-11-27 21:02:49 +00005133 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5134 if (IsIndirect)
5135 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5136 else if (AI.getCoerceToType())
5137 BaseTy = AI.getCoerceToType();
5138
5139 unsigned NumRegs = 1;
5140 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5141 BaseTy = ArrTy->getElementType();
5142 NumRegs = ArrTy->getNumElements();
5143 }
5144 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5145
Tim Northovera2ee4332014-03-29 15:09:45 +00005146 // The AArch64 va_list type and handling is specified in the Procedure Call
5147 // Standard, section B.4:
5148 //
5149 // struct {
5150 // void *__stack;
5151 // void *__gr_top;
5152 // void *__vr_top;
5153 // int __gr_offs;
5154 // int __vr_offs;
5155 // };
5156
5157 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5158 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5159 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5160 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005161
John McCall7f416cc2015-09-08 08:05:57 +00005162 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5163 CharUnits TyAlign = TyInfo.second;
5164
5165 Address reg_offs_p = Address::invalid();
5166 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005167 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005168 CharUnits reg_top_offset;
5169 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005170 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005171 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005172 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005173 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5174 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005175 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5176 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005177 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005178 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005179 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005180 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005181 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005182 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5183 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005184 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5185 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005186 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005187 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005188 }
5189
5190 //=======================================
5191 // Find out where argument was passed
5192 //=======================================
5193
5194 // If reg_offs >= 0 we're already using the stack for this type of
5195 // argument. We don't want to keep updating reg_offs (in case it overflows,
5196 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5197 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005198 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005199 UsingStack = CGF.Builder.CreateICmpSGE(
5200 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5201
5202 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5203
5204 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005205 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005206 CGF.EmitBlock(MaybeRegBlock);
5207
5208 // Integer arguments may need to correct register alignment (for example a
5209 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5210 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005211 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5212 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005213
5214 reg_offs = CGF.Builder.CreateAdd(
5215 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5216 "align_regoffs");
5217 reg_offs = CGF.Builder.CreateAnd(
5218 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5219 "aligned_regoffs");
5220 }
5221
5222 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005223 // The fact that this is done unconditionally reflects the fact that
5224 // allocating an argument to the stack also uses up all the remaining
5225 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005226 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005227 NewOffset = CGF.Builder.CreateAdd(
5228 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5229 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5230
5231 // Now we're in a position to decide whether this argument really was in
5232 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005233 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005234 InRegs = CGF.Builder.CreateICmpSLE(
5235 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5236
5237 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5238
5239 //=======================================
5240 // Argument was in registers
5241 //=======================================
5242
5243 // Now we emit the code for if the argument was originally passed in
5244 // registers. First start the appropriate block:
5245 CGF.EmitBlock(InRegBlock);
5246
John McCall7f416cc2015-09-08 08:05:57 +00005247 llvm::Value *reg_top = nullptr;
5248 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5249 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005250 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005251 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5252 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5253 Address RegAddr = Address::invalid();
5254 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005255
5256 if (IsIndirect) {
5257 // If it's been passed indirectly (actually a struct), whatever we find from
5258 // stored registers or on the stack will actually be a struct **.
5259 MemTy = llvm::PointerType::getUnqual(MemTy);
5260 }
5261
Craig Topper8a13c412014-05-21 05:09:00 +00005262 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005263 uint64_t NumMembers = 0;
5264 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005265 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005266 // Homogeneous aggregates passed in registers will have their elements split
5267 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5268 // qN+1, ...). We reload and store into a temporary local variable
5269 // contiguously.
5270 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005271 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005272 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5273 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005274 Address Tmp = CGF.CreateTempAlloca(HFATy,
5275 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005276
John McCall7f416cc2015-09-08 08:05:57 +00005277 // On big-endian platforms, the value will be right-aligned in its slot.
5278 int Offset = 0;
5279 if (CGF.CGM.getDataLayout().isBigEndian() &&
5280 BaseTyInfo.first.getQuantity() < 16)
5281 Offset = 16 - BaseTyInfo.first.getQuantity();
5282
Tim Northovera2ee4332014-03-29 15:09:45 +00005283 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005284 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5285 Address LoadAddr =
5286 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5287 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5288
5289 Address StoreAddr =
5290 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005291
5292 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5293 CGF.Builder.CreateStore(Elem, StoreAddr);
5294 }
5295
John McCall7f416cc2015-09-08 08:05:57 +00005296 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005297 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005298 // Otherwise the object is contiguous in memory.
5299
5300 // It might be right-aligned in its slot.
5301 CharUnits SlotSize = BaseAddr.getAlignment();
5302 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005303 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005304 TyInfo.first < SlotSize) {
5305 CharUnits Offset = SlotSize - TyInfo.first;
5306 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005307 }
5308
John McCall7f416cc2015-09-08 08:05:57 +00005309 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005310 }
5311
5312 CGF.EmitBranch(ContBlock);
5313
5314 //=======================================
5315 // Argument was on the stack
5316 //=======================================
5317 CGF.EmitBlock(OnStackBlock);
5318
John McCall7f416cc2015-09-08 08:05:57 +00005319 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5320 CharUnits::Zero(), "stack_p");
5321 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005322
John McCall7f416cc2015-09-08 08:05:57 +00005323 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005324 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005325 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5326 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005327
John McCall7f416cc2015-09-08 08:05:57 +00005328 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005329
John McCall7f416cc2015-09-08 08:05:57 +00005330 OnStackPtr = CGF.Builder.CreateAdd(
5331 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005332 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005333 OnStackPtr = CGF.Builder.CreateAnd(
5334 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005335 "align_stack");
5336
John McCall7f416cc2015-09-08 08:05:57 +00005337 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005338 }
John McCall7f416cc2015-09-08 08:05:57 +00005339 Address OnStackAddr(OnStackPtr,
5340 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005341
John McCall7f416cc2015-09-08 08:05:57 +00005342 // All stack slots are multiples of 8 bytes.
5343 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5344 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005345 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005346 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005347 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005348 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005349
John McCall7f416cc2015-09-08 08:05:57 +00005350 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005351 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005352 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005353
5354 // Write the new value of __stack for the next call to va_arg
5355 CGF.Builder.CreateStore(NewStack, stack_p);
5356
5357 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005358 TyInfo.first < StackSlotSize) {
5359 CharUnits Offset = StackSlotSize - TyInfo.first;
5360 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005361 }
5362
John McCall7f416cc2015-09-08 08:05:57 +00005363 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005364
5365 CGF.EmitBranch(ContBlock);
5366
5367 //=======================================
5368 // Tidy up
5369 //=======================================
5370 CGF.EmitBlock(ContBlock);
5371
John McCall7f416cc2015-09-08 08:05:57 +00005372 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5373 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005374
5375 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005376 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5377 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005378
5379 return ResAddr;
5380}
5381
John McCall7f416cc2015-09-08 08:05:57 +00005382Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5383 CodeGenFunction &CGF) const {
5384 // The backend's lowering doesn't support va_arg for aggregates or
5385 // illegal vector types. Lower VAArg here for these cases and use
5386 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005387 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005388 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005389
John McCall7f416cc2015-09-08 08:05:57 +00005390 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005391
John McCall7f416cc2015-09-08 08:05:57 +00005392 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005393 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005394 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5395 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5396 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005397 }
5398
John McCall7f416cc2015-09-08 08:05:57 +00005399 // The size of the actual thing passed, which might end up just
5400 // being a pointer for indirect types.
5401 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5402
5403 // Arguments bigger than 16 bytes which aren't homogeneous
5404 // aggregates should be passed indirectly.
5405 bool IsIndirect = false;
5406 if (TyInfo.first.getQuantity() > 16) {
5407 const Type *Base = nullptr;
5408 uint64_t Members = 0;
5409 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005410 }
5411
John McCall7f416cc2015-09-08 08:05:57 +00005412 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5413 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005414}
5415
Martin Storsjo502de222017-07-13 17:59:14 +00005416Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5417 QualType Ty) const {
5418 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5419 CGF.getContext().getTypeInfoInChars(Ty),
5420 CharUnits::fromQuantity(8),
5421 /*allowHigherAlign*/ false);
5422}
5423
Tim Northovera2ee4332014-03-29 15:09:45 +00005424//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005425// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005426//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005427
5428namespace {
5429
John McCall12f23522016-04-04 18:33:08 +00005430class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005431public:
5432 enum ABIKind {
5433 APCS = 0,
5434 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005435 AAPCS_VFP = 2,
5436 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005437 };
5438
5439private:
5440 ABIKind Kind;
5441
5442public:
John McCall12f23522016-04-04 18:33:08 +00005443 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5444 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005445 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005446 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005447
John McCall3480ef22011-08-30 01:42:09 +00005448 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005449 switch (getTarget().getTriple().getEnvironment()) {
5450 case llvm::Triple::Android:
5451 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005452 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005453 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005454 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005455 case llvm::Triple::MuslEABI:
5456 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005457 return true;
5458 default:
5459 return false;
5460 }
John McCall3480ef22011-08-30 01:42:09 +00005461 }
5462
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005463 bool isEABIHF() const {
5464 switch (getTarget().getTriple().getEnvironment()) {
5465 case llvm::Triple::EABIHF:
5466 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005467 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005468 return true;
5469 default:
5470 return false;
5471 }
5472 }
5473
Daniel Dunbar020daa92009-09-12 01:00:39 +00005474 ABIKind getABIKind() const { return Kind; }
5475
Tim Northovera484bc02013-10-01 14:34:25 +00005476private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005477 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005478 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005479 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005480
Reid Klecknere9f6a712014-10-31 17:10:41 +00005481 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5482 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5483 uint64_t Members) const override;
5484
Craig Topper4f12f102014-03-12 06:41:41 +00005485 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005486
John McCall7f416cc2015-09-08 08:05:57 +00005487 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5488 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005489
5490 llvm::CallingConv::ID getLLVMDefaultCC() const;
5491 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005492 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005493
5494 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5495 ArrayRef<llvm::Type*> scalars,
5496 bool asReturnValue) const override {
5497 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5498 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005499 bool isSwiftErrorInRegister() const override {
5500 return true;
5501 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005502 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5503 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005504};
5505
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005506class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5507public:
Chris Lattner2b037972010-07-29 02:01:43 +00005508 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5509 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005510
John McCall3480ef22011-08-30 01:42:09 +00005511 const ARMABIInfo &getABIInfo() const {
5512 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5513 }
5514
Craig Topper4f12f102014-03-12 06:41:41 +00005515 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005516 return 13;
5517 }
Roman Divackyc1617352011-05-18 19:36:54 +00005518
Craig Topper4f12f102014-03-12 06:41:41 +00005519 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005520 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005521 }
5522
Roman Divackyc1617352011-05-18 19:36:54 +00005523 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005524 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005525 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005526
5527 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005528 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005529 return false;
5530 }
John McCall3480ef22011-08-30 01:42:09 +00005531
Craig Topper4f12f102014-03-12 06:41:41 +00005532 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005533 if (getABIInfo().isEABI()) return 88;
5534 return TargetCodeGenInfo::getSizeOfUnwindException();
5535 }
Tim Northovera484bc02013-10-01 14:34:25 +00005536
Eric Christopher162c91c2015-06-05 22:03:00 +00005537 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005538 CodeGen::CodeGenModule &CGM,
5539 ForDefinition_t IsForDefinition) const override {
5540 if (!IsForDefinition)
5541 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005542 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005543 if (!FD)
5544 return;
5545
5546 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5547 if (!Attr)
5548 return;
5549
5550 const char *Kind;
5551 switch (Attr->getInterrupt()) {
5552 case ARMInterruptAttr::Generic: Kind = ""; break;
5553 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5554 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5555 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5556 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5557 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5558 }
5559
5560 llvm::Function *Fn = cast<llvm::Function>(GV);
5561
5562 Fn->addFnAttr("interrupt", Kind);
5563
Tim Northover5627d392015-10-30 16:30:45 +00005564 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5565 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005566 return;
5567
5568 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5569 // however this is not necessarily true on taking any interrupt. Instruct
5570 // the backend to perform a realignment as part of the function prologue.
5571 llvm::AttrBuilder B;
5572 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005573 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005574 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005575};
5576
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005577class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005578public:
5579 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5580 : ARMTargetCodeGenInfo(CGT, K) {}
5581
Eric Christopher162c91c2015-06-05 22:03:00 +00005582 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005583 CodeGen::CodeGenModule &CGM,
5584 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005585
5586 void getDependentLibraryOption(llvm::StringRef Lib,
5587 llvm::SmallString<24> &Opt) const override {
5588 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5589 }
5590
5591 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5592 llvm::SmallString<32> &Opt) const override {
5593 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5594 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005595};
5596
Eric Christopher162c91c2015-06-05 22:03:00 +00005597void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005598 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5599 ForDefinition_t IsForDefinition) const {
5600 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5601 if (!IsForDefinition)
5602 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005603 addStackProbeSizeTargetAttribute(D, GV, CGM);
5604}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005605}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005606
Chris Lattner22326a12010-07-29 02:31:05 +00005607void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005608 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005609 FI.getReturnInfo() =
5610 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005611
Tim Northoverbc784d12015-02-24 17:22:40 +00005612 for (auto &I : FI.arguments())
5613 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005614
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005615 // Always honor user-specified calling convention.
5616 if (FI.getCallingConvention() != llvm::CallingConv::C)
5617 return;
5618
John McCall882987f2013-02-28 19:01:20 +00005619 llvm::CallingConv::ID cc = getRuntimeCC();
5620 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005621 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005622}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005623
John McCall882987f2013-02-28 19:01:20 +00005624/// Return the default calling convention that LLVM will use.
5625llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5626 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005627 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005628 return llvm::CallingConv::ARM_AAPCS_VFP;
5629 else if (isEABI())
5630 return llvm::CallingConv::ARM_AAPCS;
5631 else
5632 return llvm::CallingConv::ARM_APCS;
5633}
5634
5635/// Return the calling convention that our ABI would like us to use
5636/// as the C calling convention.
5637llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005638 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005639 case APCS: return llvm::CallingConv::ARM_APCS;
5640 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5641 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005642 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005643 }
John McCall882987f2013-02-28 19:01:20 +00005644 llvm_unreachable("bad ABI kind");
5645}
5646
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005647void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005648 assert(getRuntimeCC() == llvm::CallingConv::C);
5649
5650 // Don't muddy up the IR with a ton of explicit annotations if
5651 // they'd just match what LLVM will infer from the triple.
5652 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5653 if (abiCC != getLLVMDefaultCC())
5654 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005655
Tim Northover5627d392015-10-30 16:30:45 +00005656 // AAPCS apparently requires runtime support functions to be soft-float, but
5657 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5658 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005659
5660 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5661 // AEABI-complying FP helper functions to use the base AAPCS.
5662 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5663 // support functions emitted by clang such as the _Complex helpers follow the
5664 // abiCC.
5665 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005666 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005667}
5668
Tim Northoverbc784d12015-02-24 17:22:40 +00005669ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5670 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005671 // 6.1.2.1 The following argument types are VFP CPRCs:
5672 // A single-precision floating-point type (including promoted
5673 // half-precision types); A double-precision floating-point type;
5674 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5675 // with a Base Type of a single- or double-precision floating-point type,
5676 // 64-bit containerized vectors or 128-bit containerized vectors with one
5677 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005678 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005679
Reid Klecknerb1be6832014-11-15 01:41:41 +00005680 Ty = useFirstFieldIfTransparentUnion(Ty);
5681
Manman Renfef9e312012-10-16 19:18:39 +00005682 // Handle illegal vector types here.
5683 if (isIllegalVectorType(Ty)) {
5684 uint64_t Size = getContext().getTypeSize(Ty);
5685 if (Size <= 32) {
5686 llvm::Type *ResType =
5687 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005688 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005689 }
5690 if (Size == 64) {
5691 llvm::Type *ResType = llvm::VectorType::get(
5692 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005693 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005694 }
5695 if (Size == 128) {
5696 llvm::Type *ResType = llvm::VectorType::get(
5697 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005698 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005699 }
John McCall7f416cc2015-09-08 08:05:57 +00005700 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005701 }
5702
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005703 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5704 // unspecified. This is not done for OpenCL as it handles the half type
5705 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005706 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005707 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5708 llvm::Type::getFloatTy(getVMContext()) :
5709 llvm::Type::getInt32Ty(getVMContext());
5710 return ABIArgInfo::getDirect(ResType);
5711 }
5712
John McCalla1dee5302010-08-22 10:59:02 +00005713 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005714 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005715 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005716 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005717 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005718
Tim Northover5a1558e2014-11-07 22:30:50 +00005719 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5720 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005721 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005722
Oliver Stannard405bded2014-02-11 09:25:50 +00005723 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005724 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005725 }
Tim Northover1060eae2013-06-21 22:49:34 +00005726
Daniel Dunbar09d33622009-09-14 21:54:03 +00005727 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005728 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005729 return ABIArgInfo::getIgnore();
5730
Tim Northover5a1558e2014-11-07 22:30:50 +00005731 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005732 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5733 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005734 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005735 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005736 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005737 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005738 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005739 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005740 }
Tim Northover5627d392015-10-30 16:30:45 +00005741 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5742 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5743 // this convention even for a variadic function: the backend will use GPRs
5744 // if needed.
5745 const Type *Base = nullptr;
5746 uint64_t Members = 0;
5747 if (isHomogeneousAggregate(Ty, Base, Members)) {
5748 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5749 llvm::Type *Ty =
5750 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5751 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5752 }
5753 }
5754
5755 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5756 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5757 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5758 // bigger than 128-bits, they get placed in space allocated by the caller,
5759 // and a pointer is passed.
5760 return ABIArgInfo::getIndirect(
5761 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005762 }
5763
Manman Ren6c30e132012-08-13 21:23:55 +00005764 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005765 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5766 // most 8-byte. We realign the indirect argument if type alignment is bigger
5767 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005768 uint64_t ABIAlign = 4;
5769 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5770 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005771 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005772 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005773
Manman Ren8cd99812012-11-06 04:58:01 +00005774 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005775 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005776 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5777 /*ByVal=*/true,
5778 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005779 }
5780
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005781 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5782 // same size and alignment.
5783 if (getTarget().isRenderScriptTarget()) {
5784 return coerceToIntArray(Ty, getContext(), getVMContext());
5785 }
5786
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005787 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005788 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005789 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005790 // FIXME: Try to match the types of the arguments more accurately where
5791 // we can.
5792 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005793 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5794 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005795 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005796 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5797 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005798 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005799
Tim Northover5a1558e2014-11-07 22:30:50 +00005800 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005801}
5802
Chris Lattner458b2aa2010-07-29 02:16:43 +00005803static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005804 llvm::LLVMContext &VMContext) {
5805 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5806 // is called integer-like if its size is less than or equal to one word, and
5807 // the offset of each of its addressable sub-fields is zero.
5808
5809 uint64_t Size = Context.getTypeSize(Ty);
5810
5811 // Check that the type fits in a word.
5812 if (Size > 32)
5813 return false;
5814
5815 // FIXME: Handle vector types!
5816 if (Ty->isVectorType())
5817 return false;
5818
Daniel Dunbard53bac72009-09-14 02:20:34 +00005819 // Float types are never treated as "integer like".
5820 if (Ty->isRealFloatingType())
5821 return false;
5822
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005823 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005824 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005825 return true;
5826
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005827 // Small complex integer types are "integer like".
5828 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5829 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005830
5831 // Single element and zero sized arrays should be allowed, by the definition
5832 // above, but they are not.
5833
5834 // Otherwise, it must be a record type.
5835 const RecordType *RT = Ty->getAs<RecordType>();
5836 if (!RT) return false;
5837
5838 // Ignore records with flexible arrays.
5839 const RecordDecl *RD = RT->getDecl();
5840 if (RD->hasFlexibleArrayMember())
5841 return false;
5842
5843 // Check that all sub-fields are at offset 0, and are themselves "integer
5844 // like".
5845 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5846
5847 bool HadField = false;
5848 unsigned idx = 0;
5849 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5850 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005851 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005852
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005853 // Bit-fields are not addressable, we only need to verify they are "integer
5854 // like". We still have to disallow a subsequent non-bitfield, for example:
5855 // struct { int : 0; int x }
5856 // is non-integer like according to gcc.
5857 if (FD->isBitField()) {
5858 if (!RD->isUnion())
5859 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005860
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005861 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5862 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005863
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005864 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005865 }
5866
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005867 // Check if this field is at offset 0.
5868 if (Layout.getFieldOffset(idx) != 0)
5869 return false;
5870
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005871 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5872 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005873
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005874 // Only allow at most one field in a structure. This doesn't match the
5875 // wording above, but follows gcc in situations with a field following an
5876 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005877 if (!RD->isUnion()) {
5878 if (HadField)
5879 return false;
5880
5881 HadField = true;
5882 }
5883 }
5884
5885 return true;
5886}
5887
Oliver Stannard405bded2014-02-11 09:25:50 +00005888ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5889 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005890 bool IsEffectivelyAAPCS_VFP =
5891 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005892
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005893 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005894 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005895
Daniel Dunbar19964db2010-09-23 01:54:32 +00005896 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005897 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005898 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005899 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005900
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005901 // __fp16 gets returned as if it were an int or float, but with the top 16
5902 // bits unspecified. This is not done for OpenCL as it handles the half type
5903 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005904 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005905 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5906 llvm::Type::getFloatTy(getVMContext()) :
5907 llvm::Type::getInt32Ty(getVMContext());
5908 return ABIArgInfo::getDirect(ResType);
5909 }
5910
John McCalla1dee5302010-08-22 10:59:02 +00005911 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005912 // Treat an enum type as its underlying type.
5913 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5914 RetTy = EnumTy->getDecl()->getIntegerType();
5915
Tim Northover5a1558e2014-11-07 22:30:50 +00005916 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5917 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005918 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005919
5920 // Are we following APCS?
5921 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005922 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005923 return ABIArgInfo::getIgnore();
5924
Daniel Dunbareedf1512010-02-01 23:31:19 +00005925 // Complex types are all returned as packed integers.
5926 //
5927 // FIXME: Consider using 2 x vector types if the back end handles them
5928 // correctly.
5929 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005930 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5931 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005932
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005933 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005934 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005935 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005936 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005937 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005938 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005939 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005940 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5941 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005942 }
5943
5944 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005945 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005946 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005947
5948 // Otherwise this is an AAPCS variant.
5949
Chris Lattner458b2aa2010-07-29 02:16:43 +00005950 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005951 return ABIArgInfo::getIgnore();
5952
Bob Wilson1d9269a2011-11-02 04:51:36 +00005953 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005954 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005955 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005956 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005957 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005958 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005959 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005960 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005961 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005962 }
5963
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005964 // Aggregates <= 4 bytes are returned in r0; other aggregates
5965 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005966 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005967 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005968 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5969 // same size and alignment.
5970 if (getTarget().isRenderScriptTarget()) {
5971 return coerceToIntArray(RetTy, getContext(), getVMContext());
5972 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005973 if (getDataLayout().isBigEndian())
5974 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005975 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005976
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005977 // Return in the smallest viable integer type.
5978 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005979 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005980 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005981 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5982 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005983 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5984 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5985 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005986 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005987 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005988 }
5989
John McCall7f416cc2015-09-08 08:05:57 +00005990 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005991}
5992
Manman Renfef9e312012-10-16 19:18:39 +00005993/// isIllegalVector - check whether Ty is an illegal vector type.
5994bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005995 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5996 if (isAndroid()) {
5997 // Android shipped using Clang 3.1, which supported a slightly different
5998 // vector ABI. The primary differences were that 3-element vector types
5999 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6000 // accepts that legacy behavior for Android only.
6001 // Check whether VT is legal.
6002 unsigned NumElements = VT->getNumElements();
6003 // NumElements should be power of 2 or equal to 3.
6004 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6005 return true;
6006 } else {
6007 // Check whether VT is legal.
6008 unsigned NumElements = VT->getNumElements();
6009 uint64_t Size = getContext().getTypeSize(VT);
6010 // NumElements should be power of 2.
6011 if (!llvm::isPowerOf2_32(NumElements))
6012 return true;
6013 // Size should be greater than 32 bits.
6014 return Size <= 32;
6015 }
Manman Renfef9e312012-10-16 19:18:39 +00006016 }
6017 return false;
6018}
6019
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006020bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6021 llvm::Type *eltTy,
6022 unsigned numElts) const {
6023 if (!llvm::isPowerOf2_32(numElts))
6024 return false;
6025 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6026 if (size > 64)
6027 return false;
6028 if (vectorSize.getQuantity() != 8 &&
6029 (vectorSize.getQuantity() != 16 || numElts == 1))
6030 return false;
6031 return true;
6032}
6033
Reid Klecknere9f6a712014-10-31 17:10:41 +00006034bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6035 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6036 // double, or 64-bit or 128-bit vectors.
6037 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6038 if (BT->getKind() == BuiltinType::Float ||
6039 BT->getKind() == BuiltinType::Double ||
6040 BT->getKind() == BuiltinType::LongDouble)
6041 return true;
6042 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6043 unsigned VecSize = getContext().getTypeSize(VT);
6044 if (VecSize == 64 || VecSize == 128)
6045 return true;
6046 }
6047 return false;
6048}
6049
6050bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6051 uint64_t Members) const {
6052 return Members <= 4;
6053}
6054
John McCall7f416cc2015-09-08 08:05:57 +00006055Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6056 QualType Ty) const {
6057 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006058
John McCall7f416cc2015-09-08 08:05:57 +00006059 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006060 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006061 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6062 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6063 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006064 }
6065
John McCall7f416cc2015-09-08 08:05:57 +00006066 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6067 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006068
John McCall7f416cc2015-09-08 08:05:57 +00006069 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6070 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006071 const Type *Base = nullptr;
6072 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006073 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6074 IsIndirect = true;
6075
Tim Northover5627d392015-10-30 16:30:45 +00006076 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6077 // allocated by the caller.
6078 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6079 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6080 !isHomogeneousAggregate(Ty, Base, Members)) {
6081 IsIndirect = true;
6082
John McCall7f416cc2015-09-08 08:05:57 +00006083 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006084 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6085 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006086 // Our callers should be prepared to handle an under-aligned address.
6087 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6088 getABIKind() == ARMABIInfo::AAPCS) {
6089 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6090 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006091 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6092 // ARMv7k allows type alignment up to 16 bytes.
6093 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6094 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006095 } else {
6096 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006097 }
John McCall7f416cc2015-09-08 08:05:57 +00006098 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006099
John McCall7f416cc2015-09-08 08:05:57 +00006100 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6101 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006102}
6103
Chris Lattner0cf24192010-06-28 20:05:43 +00006104//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006105// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006106//===----------------------------------------------------------------------===//
6107
6108namespace {
6109
Justin Holewinski83e96682012-05-24 17:43:12 +00006110class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006111public:
Justin Holewinski36837432013-03-30 14:38:24 +00006112 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006113
6114 ABIArgInfo classifyReturnType(QualType RetTy) const;
6115 ABIArgInfo classifyArgumentType(QualType Ty) const;
6116
Craig Topper4f12f102014-03-12 06:41:41 +00006117 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006118 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6119 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006120};
6121
Justin Holewinski83e96682012-05-24 17:43:12 +00006122class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006123public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006124 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6125 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006126
Eric Christopher162c91c2015-06-05 22:03:00 +00006127 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006128 CodeGen::CodeGenModule &M,
6129 ForDefinition_t IsForDefinition) const override;
6130
Justin Holewinski36837432013-03-30 14:38:24 +00006131private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006132 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6133 // resulting MDNode to the nvvm.annotations MDNode.
6134 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006135};
6136
Justin Holewinski83e96682012-05-24 17:43:12 +00006137ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006138 if (RetTy->isVoidType())
6139 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006140
6141 // note: this is different from default ABI
6142 if (!RetTy->isScalarType())
6143 return ABIArgInfo::getDirect();
6144
6145 // Treat an enum type as its underlying type.
6146 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6147 RetTy = EnumTy->getDecl()->getIntegerType();
6148
6149 return (RetTy->isPromotableIntegerType() ?
6150 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006151}
6152
Justin Holewinski83e96682012-05-24 17:43:12 +00006153ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006154 // Treat an enum type as its underlying type.
6155 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6156 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006157
Eli Bendersky95338a02014-10-29 13:43:21 +00006158 // Return aggregates type as indirect by value
6159 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006160 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006161
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006162 return (Ty->isPromotableIntegerType() ?
6163 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006164}
6165
Justin Holewinski83e96682012-05-24 17:43:12 +00006166void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006167 if (!getCXXABI().classifyReturnType(FI))
6168 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006169 for (auto &I : FI.arguments())
6170 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006171
6172 // Always honor user-specified calling convention.
6173 if (FI.getCallingConvention() != llvm::CallingConv::C)
6174 return;
6175
John McCall882987f2013-02-28 19:01:20 +00006176 FI.setEffectiveCallingConvention(getRuntimeCC());
6177}
6178
John McCall7f416cc2015-09-08 08:05:57 +00006179Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6180 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006181 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006182}
6183
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006184void NVPTXTargetCodeGenInfo::setTargetAttributes(
6185 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6186 ForDefinition_t IsForDefinition) const {
6187 if (!IsForDefinition)
6188 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006189 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006190 if (!FD) return;
6191
6192 llvm::Function *F = cast<llvm::Function>(GV);
6193
6194 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006195 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006196 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006197 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006198 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006199 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006200 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6201 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006202 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006203 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006204 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006205 }
Justin Holewinski38031972011-10-05 17:58:44 +00006206
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006207 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006208 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006209 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006210 // __global__ functions cannot be called from the device, we do not
6211 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006212 if (FD->hasAttr<CUDAGlobalAttr>()) {
6213 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6214 addNVVMMetadata(F, "kernel", 1);
6215 }
Artem Belevich7093e402015-04-21 22:55:54 +00006216 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006217 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006218 llvm::APSInt MaxThreads(32);
6219 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6220 if (MaxThreads > 0)
6221 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6222
6223 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6224 // not specified in __launch_bounds__ or if the user specified a 0 value,
6225 // we don't have to add a PTX directive.
6226 if (Attr->getMinBlocks()) {
6227 llvm::APSInt MinBlocks(32);
6228 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6229 if (MinBlocks > 0)
6230 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6231 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006232 }
6233 }
Justin Holewinski38031972011-10-05 17:58:44 +00006234 }
6235}
6236
Eli Benderskye06a2c42014-04-15 16:57:05 +00006237void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6238 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006239 llvm::Module *M = F->getParent();
6240 llvm::LLVMContext &Ctx = M->getContext();
6241
6242 // Get "nvvm.annotations" metadata node
6243 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6244
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006245 llvm::Metadata *MDVals[] = {
6246 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6247 llvm::ConstantAsMetadata::get(
6248 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006249 // Append metadata to nvvm.annotations
6250 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6251}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006252}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006253
6254//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006255// SystemZ ABI Implementation
6256//===----------------------------------------------------------------------===//
6257
6258namespace {
6259
Bryan Chane3f1ed52016-04-28 13:56:43 +00006260class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006261 bool HasVector;
6262
Ulrich Weigand47445072013-05-06 16:26:41 +00006263public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006264 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006265 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006266
6267 bool isPromotableIntegerType(QualType Ty) const;
6268 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006269 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006270 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006271 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006272
6273 ABIArgInfo classifyReturnType(QualType RetTy) const;
6274 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6275
Craig Topper4f12f102014-03-12 06:41:41 +00006276 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006277 if (!getCXXABI().classifyReturnType(FI))
6278 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006279 for (auto &I : FI.arguments())
6280 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006281 }
6282
John McCall7f416cc2015-09-08 08:05:57 +00006283 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6284 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006285
6286 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6287 ArrayRef<llvm::Type*> scalars,
6288 bool asReturnValue) const override {
6289 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6290 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006291 bool isSwiftErrorInRegister() const override {
6292 return true;
6293 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006294};
6295
6296class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6297public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006298 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6299 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006300};
6301
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006302}
Ulrich Weigand47445072013-05-06 16:26:41 +00006303
6304bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6305 // Treat an enum type as its underlying type.
6306 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6307 Ty = EnumTy->getDecl()->getIntegerType();
6308
6309 // Promotable integer types are required to be promoted by the ABI.
6310 if (Ty->isPromotableIntegerType())
6311 return true;
6312
6313 // 32-bit values must also be promoted.
6314 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6315 switch (BT->getKind()) {
6316 case BuiltinType::Int:
6317 case BuiltinType::UInt:
6318 return true;
6319 default:
6320 return false;
6321 }
6322 return false;
6323}
6324
6325bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006326 return (Ty->isAnyComplexType() ||
6327 Ty->isVectorType() ||
6328 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006329}
6330
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006331bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6332 return (HasVector &&
6333 Ty->isVectorType() &&
6334 getContext().getTypeSize(Ty) <= 128);
6335}
6336
Ulrich Weigand47445072013-05-06 16:26:41 +00006337bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6338 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6339 switch (BT->getKind()) {
6340 case BuiltinType::Float:
6341 case BuiltinType::Double:
6342 return true;
6343 default:
6344 return false;
6345 }
6346
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006347 return false;
6348}
6349
6350QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006351 if (const RecordType *RT = Ty->getAsStructureType()) {
6352 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006353 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006354
6355 // If this is a C++ record, check the bases first.
6356 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006357 for (const auto &I : CXXRD->bases()) {
6358 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006359
6360 // Empty bases don't affect things either way.
6361 if (isEmptyRecord(getContext(), Base, true))
6362 continue;
6363
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006364 if (!Found.isNull())
6365 return Ty;
6366 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006367 }
6368
6369 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006370 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006371 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006372 // Unlike isSingleElementStruct(), empty structure and array fields
6373 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006374 if (getContext().getLangOpts().CPlusPlus &&
6375 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6376 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006377
6378 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006379 // Nested structures still do though.
6380 if (!Found.isNull())
6381 return Ty;
6382 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006383 }
6384
6385 // Unlike isSingleElementStruct(), trailing padding is allowed.
6386 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006387 if (!Found.isNull())
6388 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006389 }
6390
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006391 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006392}
6393
John McCall7f416cc2015-09-08 08:05:57 +00006394Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6395 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006396 // Assume that va_list type is correct; should be pointer to LLVM type:
6397 // struct {
6398 // i64 __gpr;
6399 // i64 __fpr;
6400 // i8 *__overflow_arg_area;
6401 // i8 *__reg_save_area;
6402 // };
6403
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006404 // Every non-vector argument occupies 8 bytes and is passed by preference
6405 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6406 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006407 Ty = getContext().getCanonicalType(Ty);
6408 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006409 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006410 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006411 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006412 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006413 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006414 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006415 CharUnits UnpaddedSize;
6416 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006417 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006418 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6419 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006420 } else {
6421 if (AI.getCoerceToType())
6422 ArgTy = AI.getCoerceToType();
6423 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006424 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006425 UnpaddedSize = TyInfo.first;
6426 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006427 }
John McCall7f416cc2015-09-08 08:05:57 +00006428 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6429 if (IsVector && UnpaddedSize > PaddedSize)
6430 PaddedSize = CharUnits::fromQuantity(16);
6431 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006432
John McCall7f416cc2015-09-08 08:05:57 +00006433 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006434
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006435 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006436 llvm::Value *PaddedSizeV =
6437 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006438
6439 if (IsVector) {
6440 // Work out the address of a vector argument on the stack.
6441 // Vector arguments are always passed in the high bits of a
6442 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006443 Address OverflowArgAreaPtr =
6444 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006445 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006446 Address OverflowArgArea =
6447 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6448 TyInfo.second);
6449 Address MemAddr =
6450 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006451
6452 // Update overflow_arg_area_ptr pointer
6453 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006454 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6455 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006456 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6457
6458 return MemAddr;
6459 }
6460
John McCall7f416cc2015-09-08 08:05:57 +00006461 assert(PaddedSize.getQuantity() == 8);
6462
6463 unsigned MaxRegs, RegCountField, RegSaveIndex;
6464 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006465 if (InFPRs) {
6466 MaxRegs = 4; // Maximum of 4 FPR arguments
6467 RegCountField = 1; // __fpr
6468 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006469 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006470 } else {
6471 MaxRegs = 5; // Maximum of 5 GPR arguments
6472 RegCountField = 0; // __gpr
6473 RegSaveIndex = 2; // save offset for r2
6474 RegPadding = Padding; // values are passed in the low bits of a GPR
6475 }
6476
John McCall7f416cc2015-09-08 08:05:57 +00006477 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6478 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6479 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006480 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006481 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6482 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006483 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006484
6485 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6486 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6487 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6488 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6489
6490 // Emit code to load the value if it was passed in registers.
6491 CGF.EmitBlock(InRegBlock);
6492
6493 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006494 llvm::Value *ScaledRegCount =
6495 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6496 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006497 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6498 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006499 llvm::Value *RegOffset =
6500 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006501 Address RegSaveAreaPtr =
6502 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6503 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006504 llvm::Value *RegSaveArea =
6505 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006506 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6507 "raw_reg_addr"),
6508 PaddedSize);
6509 Address RegAddr =
6510 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006511
6512 // Update the register count
6513 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6514 llvm::Value *NewRegCount =
6515 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6516 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6517 CGF.EmitBranch(ContBlock);
6518
6519 // Emit code to load the value if it was passed in memory.
6520 CGF.EmitBlock(InMemBlock);
6521
6522 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006523 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6524 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6525 Address OverflowArgArea =
6526 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6527 PaddedSize);
6528 Address RawMemAddr =
6529 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6530 Address MemAddr =
6531 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006532
6533 // Update overflow_arg_area_ptr pointer
6534 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006535 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6536 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006537 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6538 CGF.EmitBranch(ContBlock);
6539
6540 // Return the appropriate result.
6541 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006542 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6543 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006544
6545 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006546 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6547 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006548
6549 return ResAddr;
6550}
6551
Ulrich Weigand47445072013-05-06 16:26:41 +00006552ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6553 if (RetTy->isVoidType())
6554 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006555 if (isVectorArgumentType(RetTy))
6556 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006557 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006558 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006559 return (isPromotableIntegerType(RetTy) ?
6560 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6561}
6562
6563ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6564 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006565 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006566 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006567
6568 // Integers and enums are extended to full register width.
6569 if (isPromotableIntegerType(Ty))
6570 return ABIArgInfo::getExtend();
6571
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006572 // Handle vector types and vector-like structure types. Note that
6573 // as opposed to float-like structure types, we do not allow any
6574 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006575 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006576 QualType SingleElementTy = GetSingleElementType(Ty);
6577 if (isVectorArgumentType(SingleElementTy) &&
6578 getContext().getTypeSize(SingleElementTy) == Size)
6579 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6580
6581 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006582 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006583 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006584
6585 // Handle small structures.
6586 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6587 // Structures with flexible arrays have variable length, so really
6588 // fail the size test above.
6589 const RecordDecl *RD = RT->getDecl();
6590 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006591 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006592
6593 // The structure is passed as an unextended integer, a float, or a double.
6594 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006595 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006596 assert(Size == 32 || Size == 64);
6597 if (Size == 32)
6598 PassTy = llvm::Type::getFloatTy(getVMContext());
6599 else
6600 PassTy = llvm::Type::getDoubleTy(getVMContext());
6601 } else
6602 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6603 return ABIArgInfo::getDirect(PassTy);
6604 }
6605
6606 // Non-structure compounds are passed indirectly.
6607 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006608 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006609
Craig Topper8a13c412014-05-21 05:09:00 +00006610 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006611}
6612
6613//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006614// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006615//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006616
6617namespace {
6618
6619class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6620public:
Chris Lattner2b037972010-07-29 02:01:43 +00006621 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6622 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006623 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006624 CodeGen::CodeGenModule &M,
6625 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006626};
6627
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006628}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006629
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006630void MSP430TargetCodeGenInfo::setTargetAttributes(
6631 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6632 ForDefinition_t IsForDefinition) const {
6633 if (!IsForDefinition)
6634 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006635 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006636 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6637 // Handle 'interrupt' attribute:
6638 llvm::Function *F = cast<llvm::Function>(GV);
6639
6640 // Step 1: Set ISR calling convention.
6641 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6642
6643 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006644 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006645
6646 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006647 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006648 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6649 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006650 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006651 }
6652}
6653
Chris Lattner0cf24192010-06-28 20:05:43 +00006654//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006655// MIPS ABI Implementation. This works for both little-endian and
6656// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006657//===----------------------------------------------------------------------===//
6658
John McCall943fae92010-05-27 06:19:26 +00006659namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006660class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006661 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006662 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6663 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006664 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006665 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006666 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006667 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006668public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006669 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006670 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006671 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006672
6673 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006674 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006675 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006676 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6677 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006678 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006679};
6680
John McCall943fae92010-05-27 06:19:26 +00006681class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006682 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006683public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006684 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6685 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006686 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006687
Craig Topper4f12f102014-03-12 06:41:41 +00006688 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006689 return 29;
6690 }
6691
Eric Christopher162c91c2015-06-05 22:03:00 +00006692 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006693 CodeGen::CodeGenModule &CGM,
6694 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006695 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006696 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006697 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006698
6699 if (FD->hasAttr<MipsLongCallAttr>())
6700 Fn->addFnAttr("long-call");
6701 else if (FD->hasAttr<MipsShortCallAttr>())
6702 Fn->addFnAttr("short-call");
6703
6704 // Other attributes do not have a meaning for declarations.
6705 if (!IsForDefinition)
6706 return;
6707
Reed Kotler3d5966f2013-03-13 20:40:30 +00006708 if (FD->hasAttr<Mips16Attr>()) {
6709 Fn->addFnAttr("mips16");
6710 }
6711 else if (FD->hasAttr<NoMips16Attr>()) {
6712 Fn->addFnAttr("nomips16");
6713 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006714
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006715 if (FD->hasAttr<MicroMipsAttr>())
6716 Fn->addFnAttr("micromips");
6717 else if (FD->hasAttr<NoMicroMipsAttr>())
6718 Fn->addFnAttr("nomicromips");
6719
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006720 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6721 if (!Attr)
6722 return;
6723
6724 const char *Kind;
6725 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006726 case MipsInterruptAttr::eic: Kind = "eic"; break;
6727 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6728 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6729 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6730 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6731 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6732 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6733 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6734 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6735 }
6736
6737 Fn->addFnAttr("interrupt", Kind);
6738
Reed Kotler373feca2013-01-16 17:10:28 +00006739 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006740
John McCall943fae92010-05-27 06:19:26 +00006741 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006742 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006743
Craig Topper4f12f102014-03-12 06:41:41 +00006744 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006745 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006746 }
John McCall943fae92010-05-27 06:19:26 +00006747};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006748}
John McCall943fae92010-05-27 06:19:26 +00006749
Eric Christopher7565e0d2015-05-29 23:09:49 +00006750void MipsABIInfo::CoerceToIntArgs(
6751 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006752 llvm::IntegerType *IntTy =
6753 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006754
6755 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6756 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6757 ArgList.push_back(IntTy);
6758
6759 // If necessary, add one more integer type to ArgList.
6760 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6761
6762 if (R)
6763 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006764}
6765
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006766// In N32/64, an aligned double precision floating point field is passed in
6767// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006768llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006769 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6770
6771 if (IsO32) {
6772 CoerceToIntArgs(TySize, ArgList);
6773 return llvm::StructType::get(getVMContext(), ArgList);
6774 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006775
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006776 if (Ty->isComplexType())
6777 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006778
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006779 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006780
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006781 // Unions/vectors are passed in integer registers.
6782 if (!RT || !RT->isStructureOrClassType()) {
6783 CoerceToIntArgs(TySize, ArgList);
6784 return llvm::StructType::get(getVMContext(), ArgList);
6785 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006786
6787 const RecordDecl *RD = RT->getDecl();
6788 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006789 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006790
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006791 uint64_t LastOffset = 0;
6792 unsigned idx = 0;
6793 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6794
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006795 // Iterate over fields in the struct/class and check if there are any aligned
6796 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006797 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6798 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006799 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006800 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6801
6802 if (!BT || BT->getKind() != BuiltinType::Double)
6803 continue;
6804
6805 uint64_t Offset = Layout.getFieldOffset(idx);
6806 if (Offset % 64) // Ignore doubles that are not aligned.
6807 continue;
6808
6809 // Add ((Offset - LastOffset) / 64) args of type i64.
6810 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6811 ArgList.push_back(I64);
6812
6813 // Add double type.
6814 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6815 LastOffset = Offset + 64;
6816 }
6817
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006818 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6819 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006820
6821 return llvm::StructType::get(getVMContext(), ArgList);
6822}
6823
Akira Hatanakaddd66342013-10-29 18:41:15 +00006824llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6825 uint64_t Offset) const {
6826 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006827 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006828
Akira Hatanakaddd66342013-10-29 18:41:15 +00006829 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006830}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006831
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006832ABIArgInfo
6833MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006834 Ty = useFirstFieldIfTransparentUnion(Ty);
6835
Akira Hatanaka1632af62012-01-09 19:31:25 +00006836 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006837 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006838 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006839
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006840 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6841 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006842 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6843 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006844
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006845 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006846 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006847 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006848 return ABIArgInfo::getIgnore();
6849
Mark Lacey3825e832013-10-06 01:33:34 +00006850 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006851 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006852 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006853 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006854
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006855 // If we have reached here, aggregates are passed directly by coercing to
6856 // another structure type. Padding is inserted if the offset of the
6857 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006858 ABIArgInfo ArgInfo =
6859 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6860 getPaddingType(OrigOffset, CurrOffset));
6861 ArgInfo.setInReg(true);
6862 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006863 }
6864
6865 // Treat an enum type as its underlying type.
6866 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6867 Ty = EnumTy->getDecl()->getIntegerType();
6868
Daniel Sanders5b445b32014-10-24 14:42:42 +00006869 // All integral types are promoted to the GPR width.
6870 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006871 return ABIArgInfo::getExtend();
6872
Akira Hatanakaddd66342013-10-29 18:41:15 +00006873 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006874 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006875}
6876
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006877llvm::Type*
6878MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006879 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006880 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006881
Akira Hatanakab6f74432012-02-09 18:49:26 +00006882 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006883 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006884 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6885 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006886
Akira Hatanakab6f74432012-02-09 18:49:26 +00006887 // N32/64 returns struct/classes in floating point registers if the
6888 // following conditions are met:
6889 // 1. The size of the struct/class is no larger than 128-bit.
6890 // 2. The struct/class has one or two fields all of which are floating
6891 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006892 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006893 //
6894 // Any other composite results are returned in integer registers.
6895 //
6896 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6897 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6898 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006899 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006900
Akira Hatanakab6f74432012-02-09 18:49:26 +00006901 if (!BT || !BT->isFloatingPoint())
6902 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006903
David Blaikie2d7c57e2012-04-30 02:36:29 +00006904 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006905 }
6906
6907 if (b == e)
6908 return llvm::StructType::get(getVMContext(), RTList,
6909 RD->hasAttr<PackedAttr>());
6910
6911 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006912 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006913 }
6914
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006915 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006916 return llvm::StructType::get(getVMContext(), RTList);
6917}
6918
Akira Hatanakab579fe52011-06-02 00:09:17 +00006919ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006920 uint64_t Size = getContext().getTypeSize(RetTy);
6921
Daniel Sandersed39f582014-09-04 13:28:14 +00006922 if (RetTy->isVoidType())
6923 return ABIArgInfo::getIgnore();
6924
6925 // O32 doesn't treat zero-sized structs differently from other structs.
6926 // However, N32/N64 ignores zero sized return values.
6927 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006928 return ABIArgInfo::getIgnore();
6929
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006930 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006931 if (Size <= 128) {
6932 if (RetTy->isAnyComplexType())
6933 return ABIArgInfo::getDirect();
6934
Daniel Sanderse5018b62014-09-04 15:05:39 +00006935 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006936 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006937 if (!IsO32 ||
6938 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6939 ABIArgInfo ArgInfo =
6940 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6941 ArgInfo.setInReg(true);
6942 return ArgInfo;
6943 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006944 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006945
John McCall7f416cc2015-09-08 08:05:57 +00006946 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006947 }
6948
6949 // Treat an enum type as its underlying type.
6950 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6951 RetTy = EnumTy->getDecl()->getIntegerType();
6952
6953 return (RetTy->isPromotableIntegerType() ?
6954 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6955}
6956
6957void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006958 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006959 if (!getCXXABI().classifyReturnType(FI))
6960 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006961
Eric Christopher7565e0d2015-05-29 23:09:49 +00006962 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006963 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006964
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006965 for (auto &I : FI.arguments())
6966 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006967}
6968
John McCall7f416cc2015-09-08 08:05:57 +00006969Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6970 QualType OrigTy) const {
6971 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006972
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006973 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6974 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006975 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006976 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006977 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006978 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006979 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006980 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006981 DidPromote = true;
6982 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6983 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006984 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006985
John McCall7f416cc2015-09-08 08:05:57 +00006986 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006987
John McCall7f416cc2015-09-08 08:05:57 +00006988 // The alignment of things in the argument area is never larger than
6989 // StackAlignInBytes.
6990 TyInfo.second =
6991 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6992
6993 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6994 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6995
6996 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6997 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6998
6999
7000 // If there was a promotion, "unpromote" into a temporary.
7001 // TODO: can we just use a pointer into a subset of the original slot?
7002 if (DidPromote) {
7003 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7004 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7005
7006 // Truncate down to the right width.
7007 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7008 : CGF.IntPtrTy);
7009 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7010 if (OrigTy->isPointerType())
7011 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7012
7013 CGF.Builder.CreateStore(V, Temp);
7014 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007015 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00007016
John McCall7f416cc2015-09-08 08:05:57 +00007017 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007018}
7019
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007020bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
7021 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007022
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007023 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7024 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7025 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00007026
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007027 return false;
7028}
7029
John McCall943fae92010-05-27 06:19:26 +00007030bool
7031MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7032 llvm::Value *Address) const {
7033 // This information comes from gcc's implementation, which seems to
7034 // as canonical as it gets.
7035
John McCall943fae92010-05-27 06:19:26 +00007036 // Everything on MIPS is 4 bytes. Double-precision FP registers
7037 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007038 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007039
7040 // 0-31 are the general purpose registers, $0 - $31.
7041 // 32-63 are the floating-point registers, $f0 - $f31.
7042 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7043 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007044 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007045
7046 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7047 // They are one bit wide and ignored here.
7048
7049 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7050 // (coprocessor 1 is the FP unit)
7051 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7052 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7053 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007054 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007055 return false;
7056}
7057
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007058//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007059// AVR ABI Implementation.
7060//===----------------------------------------------------------------------===//
7061
7062namespace {
7063class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7064public:
7065 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7066 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7067
7068 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007069 CodeGen::CodeGenModule &CGM,
7070 ForDefinition_t IsForDefinition) const override {
7071 if (!IsForDefinition)
7072 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007073 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7074 if (!FD) return;
7075 auto *Fn = cast<llvm::Function>(GV);
7076
7077 if (FD->getAttr<AVRInterruptAttr>())
7078 Fn->addFnAttr("interrupt");
7079
7080 if (FD->getAttr<AVRSignalAttr>())
7081 Fn->addFnAttr("signal");
7082 }
7083};
7084}
7085
7086//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007087// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007088// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007089// handling.
7090//===----------------------------------------------------------------------===//
7091
7092namespace {
7093
7094class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7095public:
7096 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7097 : DefaultTargetCodeGenInfo(CGT) {}
7098
Eric Christopher162c91c2015-06-05 22:03:00 +00007099 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007100 CodeGen::CodeGenModule &M,
7101 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007102};
7103
Eric Christopher162c91c2015-06-05 22:03:00 +00007104void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007105 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7106 ForDefinition_t IsForDefinition) const {
7107 if (!IsForDefinition)
7108 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007109 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007110 if (!FD) return;
7111
7112 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007113
David Blaikiebbafb8a2012-03-11 07:00:24 +00007114 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007115 if (FD->hasAttr<OpenCLKernelAttr>()) {
7116 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007117 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007118 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7119 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007120 // Convert the reqd_work_group_size() attributes to metadata.
7121 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007122 llvm::NamedMDNode *OpenCLMetadata =
7123 M.getModule().getOrInsertNamedMetadata(
7124 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007125
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007126 SmallVector<llvm::Metadata *, 5> Operands;
7127 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007128
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007129 Operands.push_back(
7130 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7131 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7132 Operands.push_back(
7133 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7134 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7135 Operands.push_back(
7136 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7137 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007138
Eric Christopher7565e0d2015-05-29 23:09:49 +00007139 // Add a boolean constant operand for "required" (true) or "hint"
7140 // (false) for implementing the work_group_size_hint attr later.
7141 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007142 Operands.push_back(
7143 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007144 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7145 }
7146 }
7147 }
7148}
7149
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007150}
John McCall943fae92010-05-27 06:19:26 +00007151
Tony Linthicum76329bf2011-12-12 21:14:55 +00007152//===----------------------------------------------------------------------===//
7153// Hexagon ABI Implementation
7154//===----------------------------------------------------------------------===//
7155
7156namespace {
7157
7158class HexagonABIInfo : public ABIInfo {
7159
7160
7161public:
7162 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7163
7164private:
7165
7166 ABIArgInfo classifyReturnType(QualType RetTy) const;
7167 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7168
Craig Topper4f12f102014-03-12 06:41:41 +00007169 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007170
John McCall7f416cc2015-09-08 08:05:57 +00007171 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7172 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007173};
7174
7175class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7176public:
7177 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7178 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7179
Craig Topper4f12f102014-03-12 06:41:41 +00007180 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007181 return 29;
7182 }
7183};
7184
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007185}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007186
7187void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007188 if (!getCXXABI().classifyReturnType(FI))
7189 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007190 for (auto &I : FI.arguments())
7191 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007192}
7193
7194ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7195 if (!isAggregateTypeForABI(Ty)) {
7196 // Treat an enum type as its underlying type.
7197 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7198 Ty = EnumTy->getDecl()->getIntegerType();
7199
7200 return (Ty->isPromotableIntegerType() ?
7201 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7202 }
7203
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007204 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7205 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7206
Tony Linthicum76329bf2011-12-12 21:14:55 +00007207 // Ignore empty records.
7208 if (isEmptyRecord(getContext(), Ty, true))
7209 return ABIArgInfo::getIgnore();
7210
Tony Linthicum76329bf2011-12-12 21:14:55 +00007211 uint64_t Size = getContext().getTypeSize(Ty);
7212 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007213 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007214 // Pass in the smallest viable integer type.
7215 else if (Size > 32)
7216 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7217 else if (Size > 16)
7218 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7219 else if (Size > 8)
7220 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7221 else
7222 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7223}
7224
7225ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7226 if (RetTy->isVoidType())
7227 return ABIArgInfo::getIgnore();
7228
7229 // Large vector types should be returned via memory.
7230 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007231 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007232
7233 if (!isAggregateTypeForABI(RetTy)) {
7234 // Treat an enum type as its underlying type.
7235 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7236 RetTy = EnumTy->getDecl()->getIntegerType();
7237
7238 return (RetTy->isPromotableIntegerType() ?
7239 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7240 }
7241
Tony Linthicum76329bf2011-12-12 21:14:55 +00007242 if (isEmptyRecord(getContext(), RetTy, true))
7243 return ABIArgInfo::getIgnore();
7244
7245 // Aggregates <= 8 bytes are returned in r0; other aggregates
7246 // are returned indirectly.
7247 uint64_t Size = getContext().getTypeSize(RetTy);
7248 if (Size <= 64) {
7249 // Return in the smallest viable integer type.
7250 if (Size <= 8)
7251 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7252 if (Size <= 16)
7253 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7254 if (Size <= 32)
7255 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7256 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7257 }
7258
John McCall7f416cc2015-09-08 08:05:57 +00007259 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007260}
7261
John McCall7f416cc2015-09-08 08:05:57 +00007262Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7263 QualType Ty) const {
7264 // FIXME: Someone needs to audit that this handle alignment correctly.
7265 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7266 getContext().getTypeInfoInChars(Ty),
7267 CharUnits::fromQuantity(4),
7268 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007269}
7270
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007271//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007272// Lanai ABI Implementation
7273//===----------------------------------------------------------------------===//
7274
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007275namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007276class LanaiABIInfo : public DefaultABIInfo {
7277public:
7278 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7279
7280 bool shouldUseInReg(QualType Ty, CCState &State) const;
7281
7282 void computeInfo(CGFunctionInfo &FI) const override {
7283 CCState State(FI.getCallingConvention());
7284 // Lanai uses 4 registers to pass arguments unless the function has the
7285 // regparm attribute set.
7286 if (FI.getHasRegParm()) {
7287 State.FreeRegs = FI.getRegParm();
7288 } else {
7289 State.FreeRegs = 4;
7290 }
7291
7292 if (!getCXXABI().classifyReturnType(FI))
7293 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7294 for (auto &I : FI.arguments())
7295 I.info = classifyArgumentType(I.type, State);
7296 }
7297
Jacques Pienaare74d9132016-04-26 00:09:29 +00007298 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007299 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7300};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007301} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007302
7303bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7304 unsigned Size = getContext().getTypeSize(Ty);
7305 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7306
7307 if (SizeInRegs == 0)
7308 return false;
7309
7310 if (SizeInRegs > State.FreeRegs) {
7311 State.FreeRegs = 0;
7312 return false;
7313 }
7314
7315 State.FreeRegs -= SizeInRegs;
7316
7317 return true;
7318}
7319
Jacques Pienaare74d9132016-04-26 00:09:29 +00007320ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7321 CCState &State) const {
7322 if (!ByVal) {
7323 if (State.FreeRegs) {
7324 --State.FreeRegs; // Non-byval indirects just use one pointer.
7325 return getNaturalAlignIndirectInReg(Ty);
7326 }
7327 return getNaturalAlignIndirect(Ty, false);
7328 }
7329
7330 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007331 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007332 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7333 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7334 /*Realign=*/TypeAlign >
7335 MinABIStackAlignInBytes);
7336}
7337
Jacques Pienaard964cc22016-03-28 21:02:54 +00007338ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7339 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007340 // Check with the C++ ABI first.
7341 const RecordType *RT = Ty->getAs<RecordType>();
7342 if (RT) {
7343 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7344 if (RAA == CGCXXABI::RAA_Indirect) {
7345 return getIndirectResult(Ty, /*ByVal=*/false, State);
7346 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7347 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7348 }
7349 }
7350
7351 if (isAggregateTypeForABI(Ty)) {
7352 // Structures with flexible arrays are always indirect.
7353 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7354 return getIndirectResult(Ty, /*ByVal=*/true, State);
7355
7356 // Ignore empty structs/unions.
7357 if (isEmptyRecord(getContext(), Ty, true))
7358 return ABIArgInfo::getIgnore();
7359
7360 llvm::LLVMContext &LLVMContext = getVMContext();
7361 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7362 if (SizeInRegs <= State.FreeRegs) {
7363 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7364 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7365 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7366 State.FreeRegs -= SizeInRegs;
7367 return ABIArgInfo::getDirectInReg(Result);
7368 } else {
7369 State.FreeRegs = 0;
7370 }
7371 return getIndirectResult(Ty, true, State);
7372 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007373
7374 // Treat an enum type as its underlying type.
7375 if (const auto *EnumTy = Ty->getAs<EnumType>())
7376 Ty = EnumTy->getDecl()->getIntegerType();
7377
Jacques Pienaare74d9132016-04-26 00:09:29 +00007378 bool InReg = shouldUseInReg(Ty, State);
7379 if (Ty->isPromotableIntegerType()) {
7380 if (InReg)
7381 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007382 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007383 }
7384 if (InReg)
7385 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007386 return ABIArgInfo::getDirect();
7387}
7388
7389namespace {
7390class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7391public:
7392 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7393 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7394};
7395}
7396
7397//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007398// AMDGPU ABI Implementation
7399//===----------------------------------------------------------------------===//
7400
7401namespace {
7402
Matt Arsenault88d7da02016-08-22 19:25:59 +00007403class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007404private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007405 static const unsigned MaxNumRegsForArgsRet = 16;
7406
Matt Arsenault3fe73952017-08-09 21:44:58 +00007407 unsigned numRegsForType(QualType Ty) const;
7408
7409 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7410 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7411 uint64_t Members) const override;
7412
7413public:
7414 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7415 DefaultABIInfo(CGT) {}
7416
7417 ABIArgInfo classifyReturnType(QualType RetTy) const;
7418 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7419 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007420
7421 void computeInfo(CGFunctionInfo &FI) const override;
7422};
7423
Matt Arsenault3fe73952017-08-09 21:44:58 +00007424bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7425 return true;
7426}
7427
7428bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7429 const Type *Base, uint64_t Members) const {
7430 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7431
7432 // Homogeneous Aggregates may occupy at most 16 registers.
7433 return Members * NumRegs <= MaxNumRegsForArgsRet;
7434}
7435
Matt Arsenault3fe73952017-08-09 21:44:58 +00007436/// Estimate number of registers the type will use when passed in registers.
7437unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7438 unsigned NumRegs = 0;
7439
7440 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7441 // Compute from the number of elements. The reported size is based on the
7442 // in-memory size, which includes the padding 4th element for 3-vectors.
7443 QualType EltTy = VT->getElementType();
7444 unsigned EltSize = getContext().getTypeSize(EltTy);
7445
7446 // 16-bit element vectors should be passed as packed.
7447 if (EltSize == 16)
7448 return (VT->getNumElements() + 1) / 2;
7449
7450 unsigned EltNumRegs = (EltSize + 31) / 32;
7451 return EltNumRegs * VT->getNumElements();
7452 }
7453
7454 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7455 const RecordDecl *RD = RT->getDecl();
7456 assert(!RD->hasFlexibleArrayMember());
7457
7458 for (const FieldDecl *Field : RD->fields()) {
7459 QualType FieldTy = Field->getType();
7460 NumRegs += numRegsForType(FieldTy);
7461 }
7462
7463 return NumRegs;
7464 }
7465
7466 return (getContext().getTypeSize(Ty) + 31) / 32;
7467}
7468
Matt Arsenault88d7da02016-08-22 19:25:59 +00007469void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007470 llvm::CallingConv::ID CC = FI.getCallingConvention();
7471
Matt Arsenault88d7da02016-08-22 19:25:59 +00007472 if (!getCXXABI().classifyReturnType(FI))
7473 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7474
Matt Arsenault3fe73952017-08-09 21:44:58 +00007475 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7476 for (auto &Arg : FI.arguments()) {
7477 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7478 Arg.info = classifyKernelArgumentType(Arg.type);
7479 } else {
7480 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7481 }
7482 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007483}
7484
Matt Arsenault3fe73952017-08-09 21:44:58 +00007485ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7486 if (isAggregateTypeForABI(RetTy)) {
7487 // Records with non-trivial destructors/copy-constructors should not be
7488 // returned by value.
7489 if (!getRecordArgABI(RetTy, getCXXABI())) {
7490 // Ignore empty structs/unions.
7491 if (isEmptyRecord(getContext(), RetTy, true))
7492 return ABIArgInfo::getIgnore();
7493
7494 // Lower single-element structs to just return a regular value.
7495 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7496 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7497
7498 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7499 const RecordDecl *RD = RT->getDecl();
7500 if (RD->hasFlexibleArrayMember())
7501 return DefaultABIInfo::classifyReturnType(RetTy);
7502 }
7503
7504 // Pack aggregates <= 4 bytes into single VGPR or pair.
7505 uint64_t Size = getContext().getTypeSize(RetTy);
7506 if (Size <= 16)
7507 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7508
7509 if (Size <= 32)
7510 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7511
7512 if (Size <= 64) {
7513 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7514 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7515 }
7516
7517 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7518 return ABIArgInfo::getDirect();
7519 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007520 }
7521
Matt Arsenault3fe73952017-08-09 21:44:58 +00007522 // Otherwise just do the default thing.
7523 return DefaultABIInfo::classifyReturnType(RetTy);
7524}
7525
7526/// For kernels all parameters are really passed in a special buffer. It doesn't
7527/// make sense to pass anything byval, so everything must be direct.
7528ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7529 Ty = useFirstFieldIfTransparentUnion(Ty);
7530
7531 // TODO: Can we omit empty structs?
7532
Matt Arsenault88d7da02016-08-22 19:25:59 +00007533 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007534 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7535 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007536
7537 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7538 // individual elements, which confuses the Clover OpenCL backend; therefore we
7539 // have to set it to false here. Other args of getDirect() are just defaults.
7540 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7541}
7542
Matt Arsenault3fe73952017-08-09 21:44:58 +00007543ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7544 unsigned &NumRegsLeft) const {
7545 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7546
7547 Ty = useFirstFieldIfTransparentUnion(Ty);
7548
7549 if (isAggregateTypeForABI(Ty)) {
7550 // Records with non-trivial destructors/copy-constructors should not be
7551 // passed by value.
7552 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7553 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7554
7555 // Ignore empty structs/unions.
7556 if (isEmptyRecord(getContext(), Ty, true))
7557 return ABIArgInfo::getIgnore();
7558
7559 // Lower single-element structs to just pass a regular value. TODO: We
7560 // could do reasonable-size multiple-element structs too, using getExpand(),
7561 // though watch out for things like bitfields.
7562 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7563 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7564
7565 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7566 const RecordDecl *RD = RT->getDecl();
7567 if (RD->hasFlexibleArrayMember())
7568 return DefaultABIInfo::classifyArgumentType(Ty);
7569 }
7570
7571 // Pack aggregates <= 8 bytes into single VGPR or pair.
7572 uint64_t Size = getContext().getTypeSize(Ty);
7573 if (Size <= 64) {
7574 unsigned NumRegs = (Size + 31) / 32;
7575 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7576
7577 if (Size <= 16)
7578 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7579
7580 if (Size <= 32)
7581 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7582
7583 // XXX: Should this be i64 instead, and should the limit increase?
7584 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7585 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7586 }
7587
7588 if (NumRegsLeft > 0) {
7589 unsigned NumRegs = numRegsForType(Ty);
7590 if (NumRegsLeft >= NumRegs) {
7591 NumRegsLeft -= NumRegs;
7592 return ABIArgInfo::getDirect();
7593 }
7594 }
7595 }
7596
7597 // Otherwise just do the default thing.
7598 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7599 if (!ArgInfo.isIndirect()) {
7600 unsigned NumRegs = numRegsForType(Ty);
7601 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7602 }
7603
7604 return ArgInfo;
7605}
7606
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007607class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7608public:
7609 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007610 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007611 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007612 CodeGen::CodeGenModule &M,
7613 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007614 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007615
Yaxun Liu402804b2016-12-15 08:09:08 +00007616 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7617 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007618
7619 unsigned getASTAllocaAddressSpace() const override {
7620 return LangAS::FirstTargetAddressSpace +
7621 getABIInfo().getDataLayout().getAllocaAddrSpace();
7622 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00007623 unsigned getGlobalVarAddressSpace(CodeGenModule &CGM,
7624 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007625 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7626 llvm::LLVMContext &C) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007627};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007628}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007629
Eric Christopher162c91c2015-06-05 22:03:00 +00007630void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007631 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7632 ForDefinition_t IsForDefinition) const {
7633 if (!IsForDefinition)
7634 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007635 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007636 if (!FD)
7637 return;
7638
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007639 llvm::Function *F = cast<llvm::Function>(GV);
7640
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007641 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7642 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7643 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7644 if (ReqdWGS || FlatWGS) {
7645 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7646 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7647 if (ReqdWGS && Min == 0 && Max == 0)
7648 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007649
7650 if (Min != 0) {
7651 assert(Min <= Max && "Min must be less than or equal Max");
7652
7653 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7654 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7655 } else
7656 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007657 }
7658
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007659 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7660 unsigned Min = Attr->getMin();
7661 unsigned Max = Attr->getMax();
7662
7663 if (Min != 0) {
7664 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7665
7666 std::string AttrVal = llvm::utostr(Min);
7667 if (Max != 0)
7668 AttrVal = AttrVal + "," + llvm::utostr(Max);
7669 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7670 } else
7671 assert(Max == 0 && "Max must be zero");
7672 }
7673
7674 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007675 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007676
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007677 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007678 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7679 }
7680
7681 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7682 uint32_t NumVGPR = Attr->getNumVGPR();
7683
7684 if (NumVGPR != 0)
7685 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007686 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007687}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007688
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007689unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7690 return llvm::CallingConv::AMDGPU_KERNEL;
7691}
7692
Yaxun Liu402804b2016-12-15 08:09:08 +00007693// Currently LLVM assumes null pointers always have value 0,
7694// which results in incorrectly transformed IR. Therefore, instead of
7695// emitting null pointers in private and local address spaces, a null
7696// pointer in generic address space is emitted which is casted to a
7697// pointer in local or private address space.
7698llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7699 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7700 QualType QT) const {
7701 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7702 return llvm::ConstantPointerNull::get(PT);
7703
7704 auto &Ctx = CGM.getContext();
7705 auto NPT = llvm::PointerType::get(PT->getElementType(),
7706 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7707 return llvm::ConstantExpr::getAddrSpaceCast(
7708 llvm::ConstantPointerNull::get(NPT), PT);
7709}
7710
Yaxun Liucbf647c2017-07-08 13:24:52 +00007711unsigned
7712AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7713 const VarDecl *D) const {
7714 assert(!CGM.getLangOpts().OpenCL &&
7715 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7716 "Address space agnostic languages only");
7717 unsigned DefaultGlobalAS =
7718 LangAS::FirstTargetAddressSpace +
7719 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
7720 if (!D)
7721 return DefaultGlobalAS;
7722
7723 unsigned AddrSpace = D->getType().getAddressSpace();
7724 assert(AddrSpace == LangAS::Default ||
7725 AddrSpace >= LangAS::FirstTargetAddressSpace);
7726 if (AddrSpace != LangAS::Default)
7727 return AddrSpace;
7728
7729 if (CGM.isTypeConstant(D->getType(), false)) {
7730 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7731 return ConstAS.getValue();
7732 }
7733 return DefaultGlobalAS;
7734}
7735
Yaxun Liu39195062017-08-04 18:16:31 +00007736llvm::SyncScope::ID
7737AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7738 llvm::LLVMContext &C) const {
7739 StringRef Name;
7740 switch (S) {
7741 case SyncScope::OpenCLWorkGroup:
7742 Name = "workgroup";
7743 break;
7744 case SyncScope::OpenCLDevice:
7745 Name = "agent";
7746 break;
7747 case SyncScope::OpenCLAllSVMDevices:
7748 Name = "";
7749 break;
7750 case SyncScope::OpenCLSubGroup:
7751 Name = "subgroup";
7752 }
7753 return C.getOrInsertSyncScopeID(Name);
7754}
7755
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007756//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007757// SPARC v8 ABI Implementation.
7758// Based on the SPARC Compliance Definition version 2.4.1.
7759//
7760// Ensures that complex values are passed in registers.
7761//
7762namespace {
7763class SparcV8ABIInfo : public DefaultABIInfo {
7764public:
7765 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7766
7767private:
7768 ABIArgInfo classifyReturnType(QualType RetTy) const;
7769 void computeInfo(CGFunctionInfo &FI) const override;
7770};
7771} // end anonymous namespace
7772
7773
7774ABIArgInfo
7775SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7776 if (Ty->isAnyComplexType()) {
7777 return ABIArgInfo::getDirect();
7778 }
7779 else {
7780 return DefaultABIInfo::classifyReturnType(Ty);
7781 }
7782}
7783
7784void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7785
7786 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7787 for (auto &Arg : FI.arguments())
7788 Arg.info = classifyArgumentType(Arg.type);
7789}
7790
7791namespace {
7792class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7793public:
7794 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7795 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7796};
7797} // end anonymous namespace
7798
7799//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007800// SPARC v9 ABI Implementation.
7801// Based on the SPARC Compliance Definition version 2.4.1.
7802//
7803// Function arguments a mapped to a nominal "parameter array" and promoted to
7804// registers depending on their type. Each argument occupies 8 or 16 bytes in
7805// the array, structs larger than 16 bytes are passed indirectly.
7806//
7807// One case requires special care:
7808//
7809// struct mixed {
7810// int i;
7811// float f;
7812// };
7813//
7814// When a struct mixed is passed by value, it only occupies 8 bytes in the
7815// parameter array, but the int is passed in an integer register, and the float
7816// is passed in a floating point register. This is represented as two arguments
7817// with the LLVM IR inreg attribute:
7818//
7819// declare void f(i32 inreg %i, float inreg %f)
7820//
7821// The code generator will only allocate 4 bytes from the parameter array for
7822// the inreg arguments. All other arguments are allocated a multiple of 8
7823// bytes.
7824//
7825namespace {
7826class SparcV9ABIInfo : public ABIInfo {
7827public:
7828 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7829
7830private:
7831 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007832 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007833 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7834 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007835
7836 // Coercion type builder for structs passed in registers. The coercion type
7837 // serves two purposes:
7838 //
7839 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7840 // in registers.
7841 // 2. Expose aligned floating point elements as first-level elements, so the
7842 // code generator knows to pass them in floating point registers.
7843 //
7844 // We also compute the InReg flag which indicates that the struct contains
7845 // aligned 32-bit floats.
7846 //
7847 struct CoerceBuilder {
7848 llvm::LLVMContext &Context;
7849 const llvm::DataLayout &DL;
7850 SmallVector<llvm::Type*, 8> Elems;
7851 uint64_t Size;
7852 bool InReg;
7853
7854 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7855 : Context(c), DL(dl), Size(0), InReg(false) {}
7856
7857 // Pad Elems with integers until Size is ToSize.
7858 void pad(uint64_t ToSize) {
7859 assert(ToSize >= Size && "Cannot remove elements");
7860 if (ToSize == Size)
7861 return;
7862
7863 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007864 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007865 if (Aligned > Size && Aligned <= ToSize) {
7866 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7867 Size = Aligned;
7868 }
7869
7870 // Add whole 64-bit words.
7871 while (Size + 64 <= ToSize) {
7872 Elems.push_back(llvm::Type::getInt64Ty(Context));
7873 Size += 64;
7874 }
7875
7876 // Final in-word padding.
7877 if (Size < ToSize) {
7878 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7879 Size = ToSize;
7880 }
7881 }
7882
7883 // Add a floating point element at Offset.
7884 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7885 // Unaligned floats are treated as integers.
7886 if (Offset % Bits)
7887 return;
7888 // The InReg flag is only required if there are any floats < 64 bits.
7889 if (Bits < 64)
7890 InReg = true;
7891 pad(Offset);
7892 Elems.push_back(Ty);
7893 Size = Offset + Bits;
7894 }
7895
7896 // Add a struct type to the coercion type, starting at Offset (in bits).
7897 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7898 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7899 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7900 llvm::Type *ElemTy = StrTy->getElementType(i);
7901 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7902 switch (ElemTy->getTypeID()) {
7903 case llvm::Type::StructTyID:
7904 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7905 break;
7906 case llvm::Type::FloatTyID:
7907 addFloat(ElemOffset, ElemTy, 32);
7908 break;
7909 case llvm::Type::DoubleTyID:
7910 addFloat(ElemOffset, ElemTy, 64);
7911 break;
7912 case llvm::Type::FP128TyID:
7913 addFloat(ElemOffset, ElemTy, 128);
7914 break;
7915 case llvm::Type::PointerTyID:
7916 if (ElemOffset % 64 == 0) {
7917 pad(ElemOffset);
7918 Elems.push_back(ElemTy);
7919 Size += 64;
7920 }
7921 break;
7922 default:
7923 break;
7924 }
7925 }
7926 }
7927
7928 // Check if Ty is a usable substitute for the coercion type.
7929 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007930 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007931 }
7932
7933 // Get the coercion type as a literal struct type.
7934 llvm::Type *getType() const {
7935 if (Elems.size() == 1)
7936 return Elems.front();
7937 else
7938 return llvm::StructType::get(Context, Elems);
7939 }
7940 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007941};
7942} // end anonymous namespace
7943
7944ABIArgInfo
7945SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7946 if (Ty->isVoidType())
7947 return ABIArgInfo::getIgnore();
7948
7949 uint64_t Size = getContext().getTypeSize(Ty);
7950
7951 // Anything too big to fit in registers is passed with an explicit indirect
7952 // pointer / sret pointer.
7953 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007954 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007955
7956 // Treat an enum type as its underlying type.
7957 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7958 Ty = EnumTy->getDecl()->getIntegerType();
7959
7960 // Integer types smaller than a register are extended.
7961 if (Size < 64 && Ty->isIntegerType())
7962 return ABIArgInfo::getExtend();
7963
7964 // Other non-aggregates go in registers.
7965 if (!isAggregateTypeForABI(Ty))
7966 return ABIArgInfo::getDirect();
7967
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007968 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7969 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7970 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007971 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007972
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007973 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007974 // Build a coercion type from the LLVM struct type.
7975 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7976 if (!StrTy)
7977 return ABIArgInfo::getDirect();
7978
7979 CoerceBuilder CB(getVMContext(), getDataLayout());
7980 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007981 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007982
7983 // Try to use the original type for coercion.
7984 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7985
7986 if (CB.InReg)
7987 return ABIArgInfo::getDirectInReg(CoerceTy);
7988 else
7989 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007990}
7991
John McCall7f416cc2015-09-08 08:05:57 +00007992Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7993 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007994 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7995 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7996 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7997 AI.setCoerceToType(ArgTy);
7998
John McCall7f416cc2015-09-08 08:05:57 +00007999 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008000
John McCall7f416cc2015-09-08 08:05:57 +00008001 CGBuilderTy &Builder = CGF.Builder;
8002 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8003 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8004
8005 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8006
8007 Address ArgAddr = Address::invalid();
8008 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008009 switch (AI.getKind()) {
8010 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008011 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008012 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008013 llvm_unreachable("Unsupported ABI kind for va_arg");
8014
John McCall7f416cc2015-09-08 08:05:57 +00008015 case ABIArgInfo::Extend: {
8016 Stride = SlotSize;
8017 CharUnits Offset = SlotSize - TypeInfo.first;
8018 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008019 break;
John McCall7f416cc2015-09-08 08:05:57 +00008020 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008021
John McCall7f416cc2015-09-08 08:05:57 +00008022 case ABIArgInfo::Direct: {
8023 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008024 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008025 ArgAddr = Addr;
8026 break;
John McCall7f416cc2015-09-08 08:05:57 +00008027 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008028
8029 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008030 Stride = SlotSize;
8031 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8032 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8033 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008034 break;
8035
8036 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008037 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008038 }
8039
8040 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008041 llvm::Value *NextPtr =
8042 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8043 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008044
John McCall7f416cc2015-09-08 08:05:57 +00008045 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008046}
8047
8048void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8049 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008050 for (auto &I : FI.arguments())
8051 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008052}
8053
8054namespace {
8055class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8056public:
8057 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8058 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008059
Craig Topper4f12f102014-03-12 06:41:41 +00008060 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008061 return 14;
8062 }
8063
8064 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008065 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008066};
8067} // end anonymous namespace
8068
Roman Divackyf02c9942014-02-24 18:46:27 +00008069bool
8070SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8071 llvm::Value *Address) const {
8072 // This is calculated from the LLVM and GCC tables and verified
8073 // against gcc output. AFAIK all ABIs use the same encoding.
8074
8075 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8076
8077 llvm::IntegerType *i8 = CGF.Int8Ty;
8078 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8079 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8080
8081 // 0-31: the 8-byte general-purpose registers
8082 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8083
8084 // 32-63: f0-31, the 4-byte floating-point registers
8085 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8086
8087 // Y = 64
8088 // PSR = 65
8089 // WIM = 66
8090 // TBR = 67
8091 // PC = 68
8092 // NPC = 69
8093 // FSR = 70
8094 // CSR = 71
8095 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008096
Roman Divackyf02c9942014-02-24 18:46:27 +00008097 // 72-87: d0-15, the 8-byte floating-point registers
8098 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8099
8100 return false;
8101}
8102
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008103
Robert Lytton0e076492013-08-13 09:43:10 +00008104//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008105// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008106//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008107
Robert Lytton0e076492013-08-13 09:43:10 +00008108namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008109
8110/// A SmallStringEnc instance is used to build up the TypeString by passing
8111/// it by reference between functions that append to it.
8112typedef llvm::SmallString<128> SmallStringEnc;
8113
8114/// TypeStringCache caches the meta encodings of Types.
8115///
8116/// The reason for caching TypeStrings is two fold:
8117/// 1. To cache a type's encoding for later uses;
8118/// 2. As a means to break recursive member type inclusion.
8119///
8120/// A cache Entry can have a Status of:
8121/// NonRecursive: The type encoding is not recursive;
8122/// Recursive: The type encoding is recursive;
8123/// Incomplete: An incomplete TypeString;
8124/// IncompleteUsed: An incomplete TypeString that has been used in a
8125/// Recursive type encoding.
8126///
8127/// A NonRecursive entry will have all of its sub-members expanded as fully
8128/// as possible. Whilst it may contain types which are recursive, the type
8129/// itself is not recursive and thus its encoding may be safely used whenever
8130/// the type is encountered.
8131///
8132/// A Recursive entry will have all of its sub-members expanded as fully as
8133/// possible. The type itself is recursive and it may contain other types which
8134/// are recursive. The Recursive encoding must not be used during the expansion
8135/// of a recursive type's recursive branch. For simplicity the code uses
8136/// IncompleteCount to reject all usage of Recursive encodings for member types.
8137///
8138/// An Incomplete entry is always a RecordType and only encodes its
8139/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8140/// are placed into the cache during type expansion as a means to identify and
8141/// handle recursive inclusion of types as sub-members. If there is recursion
8142/// the entry becomes IncompleteUsed.
8143///
8144/// During the expansion of a RecordType's members:
8145///
8146/// If the cache contains a NonRecursive encoding for the member type, the
8147/// cached encoding is used;
8148///
8149/// If the cache contains a Recursive encoding for the member type, the
8150/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8151///
8152/// If the member is a RecordType, an Incomplete encoding is placed into the
8153/// cache to break potential recursive inclusion of itself as a sub-member;
8154///
8155/// Once a member RecordType has been expanded, its temporary incomplete
8156/// entry is removed from the cache. If a Recursive encoding was swapped out
8157/// it is swapped back in;
8158///
8159/// If an incomplete entry is used to expand a sub-member, the incomplete
8160/// entry is marked as IncompleteUsed. The cache keeps count of how many
8161/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8162///
8163/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8164/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8165/// Else the member is part of a recursive type and thus the recursion has
8166/// been exited too soon for the encoding to be correct for the member.
8167///
8168class TypeStringCache {
8169 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8170 struct Entry {
8171 std::string Str; // The encoded TypeString for the type.
8172 enum Status State; // Information about the encoding in 'Str'.
8173 std::string Swapped; // A temporary place holder for a Recursive encoding
8174 // during the expansion of RecordType's members.
8175 };
8176 std::map<const IdentifierInfo *, struct Entry> Map;
8177 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8178 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8179public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008180 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008181 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8182 bool removeIncomplete(const IdentifierInfo *ID);
8183 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8184 bool IsRecursive);
8185 StringRef lookupStr(const IdentifierInfo *ID);
8186};
8187
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008188/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008189/// FieldEncoding is a helper for this ordering process.
8190class FieldEncoding {
8191 bool HasName;
8192 std::string Enc;
8193public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008194 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008195 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008196 bool operator<(const FieldEncoding &rhs) const {
8197 if (HasName != rhs.HasName) return HasName;
8198 return Enc < rhs.Enc;
8199 }
8200};
8201
Robert Lytton7d1db152013-08-19 09:46:39 +00008202class XCoreABIInfo : public DefaultABIInfo {
8203public:
8204 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008205 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8206 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008207};
8208
Robert Lyttond21e2d72014-03-03 13:45:29 +00008209class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008210 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008211public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008212 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008213 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008214 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8215 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008216};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008217
Robert Lytton2d196952013-10-11 10:29:34 +00008218} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008219
James Y Knight29b5f082016-02-24 02:59:33 +00008220// TODO: this implementation is likely now redundant with the default
8221// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008222Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8223 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008224 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008225
Robert Lytton2d196952013-10-11 10:29:34 +00008226 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008227 CharUnits SlotSize = CharUnits::fromQuantity(4);
8228 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008229
Robert Lytton2d196952013-10-11 10:29:34 +00008230 // Handle the argument.
8231 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008232 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008233 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8234 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8235 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008236 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008237
8238 Address Val = Address::invalid();
8239 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008240 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008241 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008242 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008243 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008244 llvm_unreachable("Unsupported ABI kind for va_arg");
8245 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008246 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8247 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008248 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008249 case ABIArgInfo::Extend:
8250 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008251 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8252 ArgSize = CharUnits::fromQuantity(
8253 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008254 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008255 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008256 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008257 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8258 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8259 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008260 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008261 }
Robert Lytton2d196952013-10-11 10:29:34 +00008262
8263 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008264 if (!ArgSize.isZero()) {
8265 llvm::Value *APN =
8266 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8267 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008268 }
John McCall7f416cc2015-09-08 08:05:57 +00008269
Robert Lytton2d196952013-10-11 10:29:34 +00008270 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008271}
Robert Lytton0e076492013-08-13 09:43:10 +00008272
Robert Lytton844aeeb2014-05-02 09:33:20 +00008273/// During the expansion of a RecordType, an incomplete TypeString is placed
8274/// into the cache as a means to identify and break recursion.
8275/// If there is a Recursive encoding in the cache, it is swapped out and will
8276/// be reinserted by removeIncomplete().
8277/// All other types of encoding should have been used rather than arriving here.
8278void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8279 std::string StubEnc) {
8280 if (!ID)
8281 return;
8282 Entry &E = Map[ID];
8283 assert( (E.Str.empty() || E.State == Recursive) &&
8284 "Incorrectly use of addIncomplete");
8285 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8286 E.Swapped.swap(E.Str); // swap out the Recursive
8287 E.Str.swap(StubEnc);
8288 E.State = Incomplete;
8289 ++IncompleteCount;
8290}
8291
8292/// Once the RecordType has been expanded, the temporary incomplete TypeString
8293/// must be removed from the cache.
8294/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8295/// Returns true if the RecordType was defined recursively.
8296bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8297 if (!ID)
8298 return false;
8299 auto I = Map.find(ID);
8300 assert(I != Map.end() && "Entry not present");
8301 Entry &E = I->second;
8302 assert( (E.State == Incomplete ||
8303 E.State == IncompleteUsed) &&
8304 "Entry must be an incomplete type");
8305 bool IsRecursive = false;
8306 if (E.State == IncompleteUsed) {
8307 // We made use of our Incomplete encoding, thus we are recursive.
8308 IsRecursive = true;
8309 --IncompleteUsedCount;
8310 }
8311 if (E.Swapped.empty())
8312 Map.erase(I);
8313 else {
8314 // Swap the Recursive back.
8315 E.Swapped.swap(E.Str);
8316 E.Swapped.clear();
8317 E.State = Recursive;
8318 }
8319 --IncompleteCount;
8320 return IsRecursive;
8321}
8322
8323/// Add the encoded TypeString to the cache only if it is NonRecursive or
8324/// Recursive (viz: all sub-members were expanded as fully as possible).
8325void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8326 bool IsRecursive) {
8327 if (!ID || IncompleteUsedCount)
8328 return; // No key or it is is an incomplete sub-type so don't add.
8329 Entry &E = Map[ID];
8330 if (IsRecursive && !E.Str.empty()) {
8331 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8332 "This is not the same Recursive entry");
8333 // The parent container was not recursive after all, so we could have used
8334 // this Recursive sub-member entry after all, but we assumed the worse when
8335 // we started viz: IncompleteCount!=0.
8336 return;
8337 }
8338 assert(E.Str.empty() && "Entry already present");
8339 E.Str = Str.str();
8340 E.State = IsRecursive? Recursive : NonRecursive;
8341}
8342
8343/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8344/// are recursively expanding a type (IncompleteCount != 0) and the cached
8345/// encoding is Recursive, return an empty StringRef.
8346StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8347 if (!ID)
8348 return StringRef(); // We have no key.
8349 auto I = Map.find(ID);
8350 if (I == Map.end())
8351 return StringRef(); // We have no encoding.
8352 Entry &E = I->second;
8353 if (E.State == Recursive && IncompleteCount)
8354 return StringRef(); // We don't use Recursive encodings for member types.
8355
8356 if (E.State == Incomplete) {
8357 // The incomplete type is being used to break out of recursion.
8358 E.State = IncompleteUsed;
8359 ++IncompleteUsedCount;
8360 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008361 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008362}
8363
8364/// The XCore ABI includes a type information section that communicates symbol
8365/// type information to the linker. The linker uses this information to verify
8366/// safety/correctness of things such as array bound and pointers et al.
8367/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8368/// This type information (TypeString) is emitted into meta data for all global
8369/// symbols: definitions, declarations, functions & variables.
8370///
8371/// The TypeString carries type, qualifier, name, size & value details.
8372/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008373/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008374/// The output is tested by test/CodeGen/xcore-stringtype.c.
8375///
8376static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8377 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8378
8379/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8380void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8381 CodeGen::CodeGenModule &CGM) const {
8382 SmallStringEnc Enc;
8383 if (getTypeString(Enc, D, CGM, TSC)) {
8384 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008385 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8386 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008387 llvm::NamedMDNode *MD =
8388 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8389 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8390 }
8391}
8392
Xiuli Pan972bea82016-03-24 03:57:17 +00008393//===----------------------------------------------------------------------===//
8394// SPIR ABI Implementation
8395//===----------------------------------------------------------------------===//
8396
8397namespace {
8398class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8399public:
8400 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8401 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008402 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008403};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008404
Xiuli Pan972bea82016-03-24 03:57:17 +00008405} // End anonymous namespace.
8406
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008407namespace clang {
8408namespace CodeGen {
8409void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8410 DefaultABIInfo SPIRABI(CGM.getTypes());
8411 SPIRABI.computeInfo(FI);
8412}
8413}
8414}
8415
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008416unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8417 return llvm::CallingConv::SPIR_KERNEL;
8418}
8419
Robert Lytton844aeeb2014-05-02 09:33:20 +00008420static bool appendType(SmallStringEnc &Enc, QualType QType,
8421 const CodeGen::CodeGenModule &CGM,
8422 TypeStringCache &TSC);
8423
8424/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008425/// Builds a SmallVector containing the encoded field types in declaration
8426/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008427static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8428 const RecordDecl *RD,
8429 const CodeGen::CodeGenModule &CGM,
8430 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008431 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008432 SmallStringEnc Enc;
8433 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008434 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008435 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008436 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008437 Enc += "b(";
8438 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008439 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008440 Enc += ':';
8441 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008442 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008443 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008444 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008445 Enc += ')';
8446 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008447 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008448 }
8449 return true;
8450}
8451
8452/// Appends structure and union types to Enc and adds encoding to cache.
8453/// Recursively calls appendType (via extractFieldType) for each field.
8454/// Union types have their fields ordered according to the ABI.
8455static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8456 const CodeGen::CodeGenModule &CGM,
8457 TypeStringCache &TSC, const IdentifierInfo *ID) {
8458 // Append the cached TypeString if we have one.
8459 StringRef TypeString = TSC.lookupStr(ID);
8460 if (!TypeString.empty()) {
8461 Enc += TypeString;
8462 return true;
8463 }
8464
8465 // Start to emit an incomplete TypeString.
8466 size_t Start = Enc.size();
8467 Enc += (RT->isUnionType()? 'u' : 's');
8468 Enc += '(';
8469 if (ID)
8470 Enc += ID->getName();
8471 Enc += "){";
8472
8473 // We collect all encoded fields and order as necessary.
8474 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008475 const RecordDecl *RD = RT->getDecl()->getDefinition();
8476 if (RD && !RD->field_empty()) {
8477 // An incomplete TypeString stub is placed in the cache for this RecordType
8478 // so that recursive calls to this RecordType will use it whilst building a
8479 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008480 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008481 std::string StubEnc(Enc.substr(Start).str());
8482 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8483 TSC.addIncomplete(ID, std::move(StubEnc));
8484 if (!extractFieldType(FE, RD, CGM, TSC)) {
8485 (void) TSC.removeIncomplete(ID);
8486 return false;
8487 }
8488 IsRecursive = TSC.removeIncomplete(ID);
8489 // The ABI requires unions to be sorted but not structures.
8490 // See FieldEncoding::operator< for sort algorithm.
8491 if (RT->isUnionType())
8492 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008493 // We can now complete the TypeString.
8494 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008495 for (unsigned I = 0; I != E; ++I) {
8496 if (I)
8497 Enc += ',';
8498 Enc += FE[I].str();
8499 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008500 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008501 Enc += '}';
8502 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8503 return true;
8504}
8505
8506/// Appends enum types to Enc and adds the encoding to the cache.
8507static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8508 TypeStringCache &TSC,
8509 const IdentifierInfo *ID) {
8510 // Append the cached TypeString if we have one.
8511 StringRef TypeString = TSC.lookupStr(ID);
8512 if (!TypeString.empty()) {
8513 Enc += TypeString;
8514 return true;
8515 }
8516
8517 size_t Start = Enc.size();
8518 Enc += "e(";
8519 if (ID)
8520 Enc += ID->getName();
8521 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008522
8523 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008524 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008525 SmallVector<FieldEncoding, 16> FE;
8526 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8527 ++I) {
8528 SmallStringEnc EnumEnc;
8529 EnumEnc += "m(";
8530 EnumEnc += I->getName();
8531 EnumEnc += "){";
8532 I->getInitVal().toString(EnumEnc);
8533 EnumEnc += '}';
8534 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8535 }
8536 std::sort(FE.begin(), FE.end());
8537 unsigned E = FE.size();
8538 for (unsigned I = 0; I != E; ++I) {
8539 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008540 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008541 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008542 }
8543 }
8544 Enc += '}';
8545 TSC.addIfComplete(ID, Enc.substr(Start), false);
8546 return true;
8547}
8548
8549/// Appends type's qualifier to Enc.
8550/// This is done prior to appending the type's encoding.
8551static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8552 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008553 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008554 int Lookup = 0;
8555 if (QT.isConstQualified())
8556 Lookup += 1<<0;
8557 if (QT.isRestrictQualified())
8558 Lookup += 1<<1;
8559 if (QT.isVolatileQualified())
8560 Lookup += 1<<2;
8561 Enc += Table[Lookup];
8562}
8563
8564/// Appends built-in types to Enc.
8565static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8566 const char *EncType;
8567 switch (BT->getKind()) {
8568 case BuiltinType::Void:
8569 EncType = "0";
8570 break;
8571 case BuiltinType::Bool:
8572 EncType = "b";
8573 break;
8574 case BuiltinType::Char_U:
8575 EncType = "uc";
8576 break;
8577 case BuiltinType::UChar:
8578 EncType = "uc";
8579 break;
8580 case BuiltinType::SChar:
8581 EncType = "sc";
8582 break;
8583 case BuiltinType::UShort:
8584 EncType = "us";
8585 break;
8586 case BuiltinType::Short:
8587 EncType = "ss";
8588 break;
8589 case BuiltinType::UInt:
8590 EncType = "ui";
8591 break;
8592 case BuiltinType::Int:
8593 EncType = "si";
8594 break;
8595 case BuiltinType::ULong:
8596 EncType = "ul";
8597 break;
8598 case BuiltinType::Long:
8599 EncType = "sl";
8600 break;
8601 case BuiltinType::ULongLong:
8602 EncType = "ull";
8603 break;
8604 case BuiltinType::LongLong:
8605 EncType = "sll";
8606 break;
8607 case BuiltinType::Float:
8608 EncType = "ft";
8609 break;
8610 case BuiltinType::Double:
8611 EncType = "d";
8612 break;
8613 case BuiltinType::LongDouble:
8614 EncType = "ld";
8615 break;
8616 default:
8617 return false;
8618 }
8619 Enc += EncType;
8620 return true;
8621}
8622
8623/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8624static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8625 const CodeGen::CodeGenModule &CGM,
8626 TypeStringCache &TSC) {
8627 Enc += "p(";
8628 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8629 return false;
8630 Enc += ')';
8631 return true;
8632}
8633
8634/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008635static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8636 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008637 const CodeGen::CodeGenModule &CGM,
8638 TypeStringCache &TSC, StringRef NoSizeEnc) {
8639 if (AT->getSizeModifier() != ArrayType::Normal)
8640 return false;
8641 Enc += "a(";
8642 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8643 CAT->getSize().toStringUnsigned(Enc);
8644 else
8645 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8646 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008647 // The Qualifiers should be attached to the type rather than the array.
8648 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008649 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8650 return false;
8651 Enc += ')';
8652 return true;
8653}
8654
8655/// Appends a function encoding to Enc, calling appendType for the return type
8656/// and the arguments.
8657static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8658 const CodeGen::CodeGenModule &CGM,
8659 TypeStringCache &TSC) {
8660 Enc += "f{";
8661 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8662 return false;
8663 Enc += "}(";
8664 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8665 // N.B. we are only interested in the adjusted param types.
8666 auto I = FPT->param_type_begin();
8667 auto E = FPT->param_type_end();
8668 if (I != E) {
8669 do {
8670 if (!appendType(Enc, *I, CGM, TSC))
8671 return false;
8672 ++I;
8673 if (I != E)
8674 Enc += ',';
8675 } while (I != E);
8676 if (FPT->isVariadic())
8677 Enc += ",va";
8678 } else {
8679 if (FPT->isVariadic())
8680 Enc += "va";
8681 else
8682 Enc += '0';
8683 }
8684 }
8685 Enc += ')';
8686 return true;
8687}
8688
8689/// Handles the type's qualifier before dispatching a call to handle specific
8690/// type encodings.
8691static bool appendType(SmallStringEnc &Enc, QualType QType,
8692 const CodeGen::CodeGenModule &CGM,
8693 TypeStringCache &TSC) {
8694
8695 QualType QT = QType.getCanonicalType();
8696
Robert Lytton6adb20f2014-06-05 09:06:21 +00008697 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8698 // The Qualifiers should be attached to the type rather than the array.
8699 // Thus we don't call appendQualifier() here.
8700 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8701
Robert Lytton844aeeb2014-05-02 09:33:20 +00008702 appendQualifier(Enc, QT);
8703
8704 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8705 return appendBuiltinType(Enc, BT);
8706
Robert Lytton844aeeb2014-05-02 09:33:20 +00008707 if (const PointerType *PT = QT->getAs<PointerType>())
8708 return appendPointerType(Enc, PT, CGM, TSC);
8709
8710 if (const EnumType *ET = QT->getAs<EnumType>())
8711 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8712
8713 if (const RecordType *RT = QT->getAsStructureType())
8714 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8715
8716 if (const RecordType *RT = QT->getAsUnionType())
8717 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8718
8719 if (const FunctionType *FT = QT->getAs<FunctionType>())
8720 return appendFunctionType(Enc, FT, CGM, TSC);
8721
8722 return false;
8723}
8724
8725static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8726 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8727 if (!D)
8728 return false;
8729
8730 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8731 if (FD->getLanguageLinkage() != CLanguageLinkage)
8732 return false;
8733 return appendType(Enc, FD->getType(), CGM, TSC);
8734 }
8735
8736 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8737 if (VD->getLanguageLinkage() != CLanguageLinkage)
8738 return false;
8739 QualType QT = VD->getType().getCanonicalType();
8740 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8741 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008742 // The Qualifiers should be attached to the type rather than the array.
8743 // Thus we don't call appendQualifier() here.
8744 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008745 }
8746 return appendType(Enc, QT, CGM, TSC);
8747 }
8748 return false;
8749}
8750
8751
Robert Lytton0e076492013-08-13 09:43:10 +00008752//===----------------------------------------------------------------------===//
8753// Driver code
8754//===----------------------------------------------------------------------===//
8755
Rafael Espindola9f834732014-09-19 01:54:22 +00008756bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008757 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008758}
8759
Chris Lattner2b037972010-07-29 02:01:43 +00008760const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008761 if (TheTargetCodeGenInfo)
8762 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008763
Reid Kleckner9305fd12016-04-13 23:37:17 +00008764 // Helper to set the unique_ptr while still keeping the return value.
8765 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8766 this->TheTargetCodeGenInfo.reset(P);
8767 return *P;
8768 };
8769
John McCallc8e01702013-04-16 22:48:15 +00008770 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008771 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008772 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008773 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008774
Derek Schuff09338a22012-09-06 17:37:28 +00008775 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008776 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008777 case llvm::Triple::mips:
8778 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008779 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008780 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8781 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008782
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008783 case llvm::Triple::mips64:
8784 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008785 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008786
Dylan McKaye8232d72017-02-08 05:09:26 +00008787 case llvm::Triple::avr:
8788 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8789
Tim Northover25e8a672014-05-24 12:51:25 +00008790 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008791 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008792 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008793 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008794 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008795 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008796 return SetCGInfo(
8797 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008798
Reid Kleckner9305fd12016-04-13 23:37:17 +00008799 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008800 }
8801
Dan Gohmanc2853072015-09-03 22:51:53 +00008802 case llvm::Triple::wasm32:
8803 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008804 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008805
Daniel Dunbard59655c2009-09-12 00:59:49 +00008806 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008807 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008808 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008809 case llvm::Triple::thumbeb: {
8810 if (Triple.getOS() == llvm::Triple::Win32) {
8811 return SetCGInfo(
8812 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008813 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008814
Reid Kleckner9305fd12016-04-13 23:37:17 +00008815 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8816 StringRef ABIStr = getTarget().getABI();
8817 if (ABIStr == "apcs-gnu")
8818 Kind = ARMABIInfo::APCS;
8819 else if (ABIStr == "aapcs16")
8820 Kind = ARMABIInfo::AAPCS16_VFP;
8821 else if (CodeGenOpts.FloatABI == "hard" ||
8822 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008823 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008824 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008825 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008826 Kind = ARMABIInfo::AAPCS_VFP;
8827
8828 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8829 }
8830
John McCallea8d8bb2010-03-11 00:10:12 +00008831 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008832 return SetCGInfo(
8833 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008834 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008835 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008836 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008837 if (getTarget().getABI() == "elfv2")
8838 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008839 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008840 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008841
Hal Finkel415c2a32016-10-02 02:10:45 +00008842 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8843 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008844 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008845 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008846 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008847 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008848 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008849 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008850 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008851 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008852 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008853
Hal Finkel415c2a32016-10-02 02:10:45 +00008854 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8855 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008856 }
John McCallea8d8bb2010-03-11 00:10:12 +00008857
Peter Collingbournec947aae2012-05-20 23:28:41 +00008858 case llvm::Triple::nvptx:
8859 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008860 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008861
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008862 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008863 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008864
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008865 case llvm::Triple::systemz: {
8866 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008867 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008868 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008869
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008870 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008871 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008872 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008873
Eli Friedman33465822011-07-08 23:31:17 +00008874 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008875 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008876 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008877 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008878 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008879
John McCall1fe2a8c2013-06-18 02:46:29 +00008880 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008881 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8882 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8883 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008884 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008885 return SetCGInfo(new X86_32TargetCodeGenInfo(
8886 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8887 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8888 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008889 }
Eli Friedman33465822011-07-08 23:31:17 +00008890 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008891
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008892 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008893 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008894 X86AVXABILevel AVXLevel =
8895 (ABI == "avx512"
8896 ? X86AVXABILevel::AVX512
8897 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008898
Chris Lattner04dc9572010-08-31 16:44:54 +00008899 switch (Triple.getOS()) {
8900 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008901 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008902 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008903 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008904 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008905 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008906 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008907 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008908 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008909 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008910 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008911 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008912 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008913 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008914 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008915 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008916 case llvm::Triple::sparc:
8917 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008918 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008919 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008920 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008921 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008922 case llvm::Triple::spir:
8923 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008924 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008925 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008926}