blob: 77b9b4caab5d653c98ea44712ca7136aaf6bd187 [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)) {
2300 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2301 llvm::Function *Fn = cast<llvm::Function>(GV);
2302 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2303 }
2304 }
2305 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002306};
2307
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002308class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2309public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002310 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2311 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002312
2313 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002314 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002315 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002316 // If the argument contains a space, enclose it in quotes.
2317 if (Lib.find(" ") != StringRef::npos)
2318 Opt += "\"" + Lib.str() + "\"";
2319 else
2320 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002321 }
2322};
2323
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002324static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002325 // If the argument does not end in .lib, automatically add the suffix.
2326 // If the argument contains a space, enclose it in quotes.
2327 // This matches the behavior of MSVC.
2328 bool Quote = (Lib.find(" ") != StringRef::npos);
2329 std::string ArgStr = Quote ? "\"" : "";
2330 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002331 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002332 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002333 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002334 return ArgStr;
2335}
2336
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002337class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2338public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002339 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002340 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2341 unsigned NumRegisterParameters)
2342 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002343 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002344
Eric Christopher162c91c2015-06-05 22:03:00 +00002345 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002346 CodeGen::CodeGenModule &CGM,
2347 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002348
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002349 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002350 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002351 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002352 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002353 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002354
2355 void getDetectMismatchOption(llvm::StringRef Name,
2356 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002357 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002358 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002359 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002360};
2361
Hans Wennborg77dc2362015-01-20 19:45:50 +00002362static void addStackProbeSizeTargetAttribute(const Decl *D,
2363 llvm::GlobalValue *GV,
2364 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002365 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002366 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2367 llvm::Function *Fn = cast<llvm::Function>(GV);
2368
Eric Christopher7565e0d2015-05-29 23:09:49 +00002369 Fn->addFnAttr("stack-probe-size",
2370 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002371 }
2372 }
2373}
2374
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002375void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2376 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2377 ForDefinition_t IsForDefinition) const {
2378 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2379 if (!IsForDefinition)
2380 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002381 addStackProbeSizeTargetAttribute(D, GV, CGM);
2382}
2383
Chris Lattner04dc9572010-08-31 16:44:54 +00002384class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2385public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002386 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2387 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002388 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002389
Eric Christopher162c91c2015-06-05 22:03:00 +00002390 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002391 CodeGen::CodeGenModule &CGM,
2392 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002393
Craig Topper4f12f102014-03-12 06:41:41 +00002394 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002395 return 7;
2396 }
2397
2398 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002399 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002400 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002401
Chris Lattner04dc9572010-08-31 16:44:54 +00002402 // 0-15 are the 16 integer registers.
2403 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002404 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002405 return false;
2406 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002407
2408 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002409 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002410 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002411 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002412 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002413
2414 void getDetectMismatchOption(llvm::StringRef Name,
2415 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002416 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002417 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002418 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002419};
2420
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002421void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2422 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2423 ForDefinition_t IsForDefinition) const {
2424 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2425 if (!IsForDefinition)
2426 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002427 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2428 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2429 llvm::Function *Fn = cast<llvm::Function>(GV);
2430 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2431 }
2432 }
2433
Hans Wennborg77dc2362015-01-20 19:45:50 +00002434 addStackProbeSizeTargetAttribute(D, GV, CGM);
2435}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002436}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002437
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002438void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2439 Class &Hi) const {
2440 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2441 //
2442 // (a) If one of the classes is Memory, the whole argument is passed in
2443 // memory.
2444 //
2445 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2446 // memory.
2447 //
2448 // (c) If the size of the aggregate exceeds two eightbytes and the first
2449 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2450 // argument is passed in memory. NOTE: This is necessary to keep the
2451 // ABI working for processors that don't support the __m256 type.
2452 //
2453 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2454 //
2455 // Some of these are enforced by the merging logic. Others can arise
2456 // only with unions; for example:
2457 // union { _Complex double; unsigned; }
2458 //
2459 // Note that clauses (b) and (c) were added in 0.98.
2460 //
2461 if (Hi == Memory)
2462 Lo = Memory;
2463 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2464 Lo = Memory;
2465 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2466 Lo = Memory;
2467 if (Hi == SSEUp && Lo != SSE)
2468 Hi = SSE;
2469}
2470
Chris Lattnerd776fb12010-06-28 21:43:59 +00002471X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002472 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2473 // classified recursively so that always two fields are
2474 // considered. The resulting class is calculated according to
2475 // the classes of the fields in the eightbyte:
2476 //
2477 // (a) If both classes are equal, this is the resulting class.
2478 //
2479 // (b) If one of the classes is NO_CLASS, the resulting class is
2480 // the other class.
2481 //
2482 // (c) If one of the classes is MEMORY, the result is the MEMORY
2483 // class.
2484 //
2485 // (d) If one of the classes is INTEGER, the result is the
2486 // INTEGER.
2487 //
2488 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2489 // MEMORY is used as class.
2490 //
2491 // (f) Otherwise class SSE is used.
2492
2493 // Accum should never be memory (we should have returned) or
2494 // ComplexX87 (because this cannot be passed in a structure).
2495 assert((Accum != Memory && Accum != ComplexX87) &&
2496 "Invalid accumulated classification during merge.");
2497 if (Accum == Field || Field == NoClass)
2498 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002499 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002500 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002501 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002502 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002503 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002504 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002505 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2506 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002507 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002508 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509}
2510
Chris Lattner5c740f12010-06-30 19:14:05 +00002511void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002512 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002513 // FIXME: This code can be simplified by introducing a simple value class for
2514 // Class pairs with appropriate constructor methods for the various
2515 // situations.
2516
2517 // FIXME: Some of the split computations are wrong; unaligned vectors
2518 // shouldn't be passed in registers for example, so there is no chance they
2519 // can straddle an eightbyte. Verify & simplify.
2520
2521 Lo = Hi = NoClass;
2522
2523 Class &Current = OffsetBase < 64 ? Lo : Hi;
2524 Current = Memory;
2525
John McCall9dd450b2009-09-21 23:43:11 +00002526 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 BuiltinType::Kind k = BT->getKind();
2528
2529 if (k == BuiltinType::Void) {
2530 Current = NoClass;
2531 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2532 Lo = Integer;
2533 Hi = Integer;
2534 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2535 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002536 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537 Current = SSE;
2538 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002539 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002540 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002541 Lo = SSE;
2542 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002543 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002544 Lo = X87;
2545 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002546 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002547 Current = SSE;
2548 } else
2549 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002550 }
2551 // FIXME: _Decimal32 and _Decimal64 are SSE.
2552 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002553 return;
2554 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002555
Chris Lattnerd776fb12010-06-28 21:43:59 +00002556 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002557 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002558 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002559 return;
2560 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002561
Chris Lattnerd776fb12010-06-28 21:43:59 +00002562 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002563 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002564 return;
2565 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002566
Chris Lattnerd776fb12010-06-28 21:43:59 +00002567 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002568 if (Ty->isMemberFunctionPointerType()) {
2569 if (Has64BitPointers) {
2570 // If Has64BitPointers, this is an {i64, i64}, so classify both
2571 // Lo and Hi now.
2572 Lo = Hi = Integer;
2573 } else {
2574 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2575 // straddles an eightbyte boundary, Hi should be classified as well.
2576 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2577 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2578 if (EB_FuncPtr != EB_ThisAdj) {
2579 Lo = Hi = Integer;
2580 } else {
2581 Current = Integer;
2582 }
2583 }
2584 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002585 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002586 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002587 return;
2588 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002589
Chris Lattnerd776fb12010-06-28 21:43:59 +00002590 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002591 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002592 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2593 // gcc passes the following as integer:
2594 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2595 // 2 bytes - <2 x char>, <1 x short>
2596 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002597 Current = Integer;
2598
2599 // If this type crosses an eightbyte boundary, it should be
2600 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002601 uint64_t EB_Lo = (OffsetBase) / 64;
2602 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2603 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002604 Hi = Lo;
2605 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002606 QualType ElementType = VT->getElementType();
2607
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002608 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002609 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002610 return;
2611
David Majnemere2ae2282016-03-04 05:26:16 +00002612 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2613 // pass them as integer. For platforms where clang is the de facto
2614 // platform compiler, we must continue to use integer.
2615 if (!classifyIntegerMMXAsSSE() &&
2616 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2617 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2618 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2619 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002620 Current = Integer;
2621 else
2622 Current = SSE;
2623
2624 // If this type crosses an eightbyte boundary, it should be
2625 // split.
2626 if (OffsetBase && OffsetBase != 64)
2627 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002628 } else if (Size == 128 ||
2629 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002630 // Arguments of 256-bits are split into four eightbyte chunks. The
2631 // least significant one belongs to class SSE and all the others to class
2632 // SSEUP. The original Lo and Hi design considers that types can't be
2633 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2634 // This design isn't correct for 256-bits, but since there're no cases
2635 // where the upper parts would need to be inspected, avoid adding
2636 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002637 //
2638 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2639 // registers if they are "named", i.e. not part of the "..." of a
2640 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002641 //
2642 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2643 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002644 Lo = SSE;
2645 Hi = SSEUp;
2646 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002647 return;
2648 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002649
Chris Lattnerd776fb12010-06-28 21:43:59 +00002650 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002651 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002652
Chris Lattner2b037972010-07-29 02:01:43 +00002653 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002654 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002655 if (Size <= 64)
2656 Current = Integer;
2657 else if (Size <= 128)
2658 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002659 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002660 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002661 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002662 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002663 } else if (ET == getContext().LongDoubleTy) {
2664 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002665 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002666 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002667 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002668 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002669 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002670 Lo = Hi = SSE;
2671 else
2672 llvm_unreachable("unexpected long double representation!");
2673 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002674
2675 // If this complex type crosses an eightbyte boundary then it
2676 // should be split.
2677 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002678 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002679 if (Hi == NoClass && EB_Real != EB_Imag)
2680 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002681
Chris Lattnerd776fb12010-06-28 21:43:59 +00002682 return;
2683 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002684
Chris Lattner2b037972010-07-29 02:01:43 +00002685 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002686 // Arrays are treated like structures.
2687
Chris Lattner2b037972010-07-29 02:01:43 +00002688 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002689
2690 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002691 // than eight eightbytes, ..., it has class MEMORY.
2692 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002693 return;
2694
2695 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2696 // fields, it has class MEMORY.
2697 //
2698 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002699 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700 return;
2701
2702 // Otherwise implement simplified merge. We could be smarter about
2703 // this, but it isn't worth it and would be harder to verify.
2704 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002705 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002706 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002707
2708 // The only case a 256-bit wide vector could be used is when the array
2709 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2710 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002711 //
2712 if (Size > 128 &&
2713 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002714 return;
2715
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002716 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2717 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002718 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002719 Lo = merge(Lo, FieldLo);
2720 Hi = merge(Hi, FieldHi);
2721 if (Lo == Memory || Hi == Memory)
2722 break;
2723 }
2724
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002725 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002726 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002727 return;
2728 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002729
Chris Lattnerd776fb12010-06-28 21:43:59 +00002730 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002731 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002732
2733 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002734 // than eight eightbytes, ..., it has class MEMORY.
2735 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002736 return;
2737
Anders Carlsson20759ad2009-09-16 15:53:40 +00002738 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2739 // copy constructor or a non-trivial destructor, it is passed by invisible
2740 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002741 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002742 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002743
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002744 const RecordDecl *RD = RT->getDecl();
2745
2746 // Assume variable sized types are passed in memory.
2747 if (RD->hasFlexibleArrayMember())
2748 return;
2749
Chris Lattner2b037972010-07-29 02:01:43 +00002750 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002751
2752 // Reset Lo class, this will be recomputed.
2753 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002754
2755 // If this is a C++ record, classify the bases first.
2756 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002757 for (const auto &I : CXXRD->bases()) {
2758 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002759 "Unexpected base class!");
2760 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002761 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002762
2763 // Classify this field.
2764 //
2765 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2766 // single eightbyte, each is classified separately. Each eightbyte gets
2767 // initialized to class NO_CLASS.
2768 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002769 uint64_t Offset =
2770 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002771 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002772 Lo = merge(Lo, FieldLo);
2773 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002774 if (Lo == Memory || Hi == Memory) {
2775 postMerge(Size, Lo, Hi);
2776 return;
2777 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002778 }
2779 }
2780
2781 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002782 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002783 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002784 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002785 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2786 bool BitField = i->isBitField();
2787
David Majnemerb439dfe2016-08-15 07:20:40 +00002788 // Ignore padding bit-fields.
2789 if (BitField && i->isUnnamedBitfield())
2790 continue;
2791
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002792 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2793 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002794 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002795 // The only case a 256-bit wide vector could be used is when the struct
2796 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2797 // to work for sizes wider than 128, early check and fallback to memory.
2798 //
David Majnemerb229cb02016-08-15 06:39:18 +00002799 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2800 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002801 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002802 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002803 return;
2804 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002805 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002806 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002807 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002808 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002809 return;
2810 }
2811
2812 // Classify this field.
2813 //
2814 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2815 // exceeds a single eightbyte, each is classified
2816 // separately. Each eightbyte gets initialized to class
2817 // NO_CLASS.
2818 Class FieldLo, FieldHi;
2819
2820 // Bit-fields require special handling, they do not force the
2821 // structure to be passed in memory even if unaligned, and
2822 // therefore they can straddle an eightbyte.
2823 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002824 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002825 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002826 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002827
2828 uint64_t EB_Lo = Offset / 64;
2829 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002830
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002831 if (EB_Lo) {
2832 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2833 FieldLo = NoClass;
2834 FieldHi = Integer;
2835 } else {
2836 FieldLo = Integer;
2837 FieldHi = EB_Hi ? Integer : NoClass;
2838 }
2839 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002840 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002841 Lo = merge(Lo, FieldLo);
2842 Hi = merge(Hi, FieldHi);
2843 if (Lo == Memory || Hi == Memory)
2844 break;
2845 }
2846
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002847 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002848 }
2849}
2850
Chris Lattner22a931e2010-06-29 06:01:59 +00002851ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002852 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2853 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002854 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002855 // Treat an enum type as its underlying type.
2856 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2857 Ty = EnumTy->getDecl()->getIntegerType();
2858
2859 return (Ty->isPromotableIntegerType() ?
2860 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2861 }
2862
John McCall7f416cc2015-09-08 08:05:57 +00002863 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002864}
2865
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002866bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2867 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2868 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002869 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002870 if (Size <= 64 || Size > LargestVector)
2871 return true;
2872 }
2873
2874 return false;
2875}
2876
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002877ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2878 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002879 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2880 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002881 //
2882 // This assumption is optimistic, as there could be free registers available
2883 // when we need to pass this argument in memory, and LLVM could try to pass
2884 // the argument in the free register. This does not seem to happen currently,
2885 // but this code would be much safer if we could mark the argument with
2886 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002887 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002888 // Treat an enum type as its underlying type.
2889 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2890 Ty = EnumTy->getDecl()->getIntegerType();
2891
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002892 return (Ty->isPromotableIntegerType() ?
2893 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002894 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002895
Mark Lacey3825e832013-10-06 01:33:34 +00002896 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002897 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002898
Chris Lattner44c2b902011-05-22 23:21:23 +00002899 // Compute the byval alignment. We specify the alignment of the byval in all
2900 // cases so that the mid-level optimizer knows the alignment of the byval.
2901 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002902
2903 // Attempt to avoid passing indirect results using byval when possible. This
2904 // is important for good codegen.
2905 //
2906 // We do this by coercing the value into a scalar type which the backend can
2907 // handle naturally (i.e., without using byval).
2908 //
2909 // For simplicity, we currently only do this when we have exhausted all of the
2910 // free integer registers. Doing this when there are free integer registers
2911 // would require more care, as we would have to ensure that the coerced value
2912 // did not claim the unused register. That would require either reording the
2913 // arguments to the function (so that any subsequent inreg values came first),
2914 // or only doing this optimization when there were no following arguments that
2915 // might be inreg.
2916 //
2917 // We currently expect it to be rare (particularly in well written code) for
2918 // arguments to be passed on the stack when there are still free integer
2919 // registers available (this would typically imply large structs being passed
2920 // by value), so this seems like a fair tradeoff for now.
2921 //
2922 // We can revisit this if the backend grows support for 'onstack' parameter
2923 // attributes. See PR12193.
2924 if (freeIntRegs == 0) {
2925 uint64_t Size = getContext().getTypeSize(Ty);
2926
2927 // If this type fits in an eightbyte, coerce it into the matching integral
2928 // type, which will end up on the stack (with alignment 8).
2929 if (Align == 8 && Size <= 64)
2930 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2931 Size));
2932 }
2933
John McCall7f416cc2015-09-08 08:05:57 +00002934 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002935}
2936
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002937/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2938/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002939llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002940 // Wrapper structs/arrays that only contain vectors are passed just like
2941 // vectors; strip them off if present.
2942 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2943 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002944
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002945 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002946 if (isa<llvm::VectorType>(IRType) ||
2947 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002948 return IRType;
2949
2950 // We couldn't find the preferred IR vector type for 'Ty'.
2951 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002952 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002953
2954 // Return a LLVM IR vector type based on the size of 'Ty'.
2955 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2956 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002957}
2958
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002959/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2960/// is known to either be off the end of the specified type or being in
2961/// alignment padding. The user type specified is known to be at most 128 bits
2962/// in size, and have passed through X86_64ABIInfo::classify with a successful
2963/// classification that put one of the two halves in the INTEGER class.
2964///
2965/// It is conservatively correct to return false.
2966static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2967 unsigned EndBit, ASTContext &Context) {
2968 // If the bytes being queried are off the end of the type, there is no user
2969 // data hiding here. This handles analysis of builtins, vectors and other
2970 // types that don't contain interesting padding.
2971 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2972 if (TySize <= StartBit)
2973 return true;
2974
Chris Lattner98076a22010-07-29 07:43:55 +00002975 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2976 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2977 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2978
2979 // Check each element to see if the element overlaps with the queried range.
2980 for (unsigned i = 0; i != NumElts; ++i) {
2981 // If the element is after the span we care about, then we're done..
2982 unsigned EltOffset = i*EltSize;
2983 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002984
Chris Lattner98076a22010-07-29 07:43:55 +00002985 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2986 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2987 EndBit-EltOffset, Context))
2988 return false;
2989 }
2990 // If it overlaps no elements, then it is safe to process as padding.
2991 return true;
2992 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002993
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002994 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2995 const RecordDecl *RD = RT->getDecl();
2996 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002997
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002998 // If this is a C++ record, check the bases first.
2999 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00003000 for (const auto &I : CXXRD->bases()) {
3001 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003002 "Unexpected base class!");
3003 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00003004 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003005
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003006 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00003007 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003008 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003009
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003010 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00003011 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003012 EndBit-BaseOffset, Context))
3013 return false;
3014 }
3015 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003016
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003017 // Verify that no field has data that overlaps the region of interest. Yes
3018 // this could be sped up a lot by being smarter about queried fields,
3019 // however we're only looking at structs up to 16 bytes, so we don't care
3020 // much.
3021 unsigned idx = 0;
3022 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3023 i != e; ++i, ++idx) {
3024 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003025
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003026 // If we found a field after the region we care about, then we're done.
3027 if (FieldOffset >= EndBit) break;
3028
3029 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3030 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3031 Context))
3032 return false;
3033 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003034
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003035 // If nothing in this record overlapped the area of interest, then we're
3036 // clean.
3037 return true;
3038 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003039
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003040 return false;
3041}
3042
Chris Lattnere556a712010-07-29 18:39:32 +00003043/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3044/// float member at the specified offset. For example, {int,{float}} has a
3045/// float at offset 4. It is conservatively correct for this routine to return
3046/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003047static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003048 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003049 // Base case if we find a float.
3050 if (IROffset == 0 && IRType->isFloatTy())
3051 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003052
Chris Lattnere556a712010-07-29 18:39:32 +00003053 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003054 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003055 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3056 unsigned Elt = SL->getElementContainingOffset(IROffset);
3057 IROffset -= SL->getElementOffset(Elt);
3058 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3059 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003060
Chris Lattnere556a712010-07-29 18:39:32 +00003061 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003062 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3063 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003064 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3065 IROffset -= IROffset/EltSize*EltSize;
3066 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3067 }
3068
3069 return false;
3070}
3071
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003072
3073/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3074/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003075llvm::Type *X86_64ABIInfo::
3076GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003077 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003078 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003079 // pass as float if the last 4 bytes is just padding. This happens for
3080 // structs that contain 3 floats.
3081 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3082 SourceOffset*8+64, getContext()))
3083 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003084
Chris Lattnere556a712010-07-29 18:39:32 +00003085 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3086 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3087 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003088 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3089 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003090 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003091
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003092 return llvm::Type::getDoubleTy(getVMContext());
3093}
3094
3095
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003096/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3097/// an 8-byte GPR. This means that we either have a scalar or we are talking
3098/// about the high or low part of an up-to-16-byte struct. This routine picks
3099/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003100/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3101/// etc).
3102///
3103/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3104/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3105/// the 8-byte value references. PrefType may be null.
3106///
Alp Toker9907f082014-07-09 14:06:35 +00003107/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003108/// an offset into this that we're processing (which is always either 0 or 8).
3109///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003110llvm::Type *X86_64ABIInfo::
3111GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003112 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003113 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3114 // returning an 8-byte unit starting with it. See if we can safely use it.
3115 if (IROffset == 0) {
3116 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003117 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3118 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003119 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003120
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003121 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3122 // goodness in the source type is just tail padding. This is allowed to
3123 // kick in for struct {double,int} on the int, but not on
3124 // struct{double,int,int} because we wouldn't return the second int. We
3125 // have to do this analysis on the source type because we can't depend on
3126 // unions being lowered a specific way etc.
3127 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003128 IRType->isIntegerTy(32) ||
3129 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3130 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3131 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003132
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003133 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3134 SourceOffset*8+64, getContext()))
3135 return IRType;
3136 }
3137 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003138
Chris Lattner2192fe52011-07-18 04:24:23 +00003139 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003140 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003141 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003142 if (IROffset < SL->getSizeInBytes()) {
3143 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3144 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003145
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003146 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3147 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003148 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003149 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003150
Chris Lattner2192fe52011-07-18 04:24:23 +00003151 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003152 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003153 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003154 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003155 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3156 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003157 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003158
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003159 // Okay, we don't have any better idea of what to pass, so we pass this in an
3160 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003161 unsigned TySizeInBytes =
3162 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003163
Chris Lattner3f763422010-07-29 17:34:39 +00003164 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003165
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003166 // It is always safe to classify this as an integer type up to i64 that
3167 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003168 return llvm::IntegerType::get(getVMContext(),
3169 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003170}
3171
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003172
3173/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3174/// be used as elements of a two register pair to pass or return, return a
3175/// first class aggregate to represent them. For example, if the low part of
3176/// a by-value argument should be passed as i32* and the high part as float,
3177/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003178static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003179GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003180 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003181 // In order to correctly satisfy the ABI, we need to the high part to start
3182 // at offset 8. If the high and low parts we inferred are both 4-byte types
3183 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3184 // the second element at offset 8. Check for this:
3185 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3186 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003187 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003188 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003189
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003190 // To handle this, we have to increase the size of the low part so that the
3191 // second element will start at an 8 byte offset. We can't increase the size
3192 // of the second element because it might make us access off the end of the
3193 // struct.
3194 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003195 // There are usually two sorts of types the ABI generation code can produce
3196 // for the low part of a pair that aren't 8 bytes in size: float or
3197 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3198 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003199 // Promote these to a larger type.
3200 if (Lo->isFloatTy())
3201 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3202 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003203 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3204 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003205 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3206 }
3207 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003208
Serge Guelton1d993272017-05-09 19:31:30 +00003209 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003210
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003211 // Verify that the second element is at an 8-byte offset.
3212 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3213 "Invalid x86-64 argument pair!");
3214 return Result;
3215}
3216
Chris Lattner31faff52010-07-28 23:06:14 +00003217ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003218classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003219 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3220 // classification algorithm.
3221 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003222 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003223
3224 // Check some invariants.
3225 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003226 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3227
Craig Topper8a13c412014-05-21 05:09:00 +00003228 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003229 switch (Lo) {
3230 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003231 if (Hi == NoClass)
3232 return ABIArgInfo::getIgnore();
3233 // If the low part is just padding, it takes no register, leave ResType
3234 // null.
3235 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3236 "Unknown missing lo part");
3237 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003238
3239 case SSEUp:
3240 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003241 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003242
3243 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3244 // hidden argument.
3245 case Memory:
3246 return getIndirectReturnResult(RetTy);
3247
3248 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3249 // available register of the sequence %rax, %rdx is used.
3250 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003251 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003252
Chris Lattner1f3a0632010-07-29 21:42:50 +00003253 // If we have a sign or zero extended integer, make sure to return Extend
3254 // so that the parameter gets the right LLVM IR attributes.
3255 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3256 // Treat an enum type as its underlying type.
3257 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3258 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003259
Chris Lattner1f3a0632010-07-29 21:42:50 +00003260 if (RetTy->isIntegralOrEnumerationType() &&
3261 RetTy->isPromotableIntegerType())
3262 return ABIArgInfo::getExtend();
3263 }
Chris Lattner31faff52010-07-28 23:06:14 +00003264 break;
3265
3266 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3267 // available SSE register of the sequence %xmm0, %xmm1 is used.
3268 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003269 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003270 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003271
3272 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3273 // returned on the X87 stack in %st0 as 80-bit x87 number.
3274 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003275 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003276 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003277
3278 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3279 // part of the value is returned in %st0 and the imaginary part in
3280 // %st1.
3281 case ComplexX87:
3282 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003283 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003284 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003285 break;
3286 }
3287
Craig Topper8a13c412014-05-21 05:09:00 +00003288 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003289 switch (Hi) {
3290 // Memory was handled previously and X87 should
3291 // never occur as a hi class.
3292 case Memory:
3293 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003294 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003295
3296 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003297 case NoClass:
3298 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003299
Chris Lattner52b3c132010-09-01 00:20:33 +00003300 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003301 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003302 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3303 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003304 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003305 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003306 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003307 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3308 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003309 break;
3310
3311 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003312 // is passed in the next available eightbyte chunk if the last used
3313 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003314 //
Chris Lattner57540c52011-04-15 05:22:18 +00003315 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003316 case SSEUp:
3317 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003318 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003319 break;
3320
3321 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3322 // returned together with the previous X87 value in %st0.
3323 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003324 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003325 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003326 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003327 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003328 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003329 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003330 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3331 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003332 }
Chris Lattner31faff52010-07-28 23:06:14 +00003333 break;
3334 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003335
Chris Lattner52b3c132010-09-01 00:20:33 +00003336 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003337 // known to pass in the high eightbyte of the result. We do this by forming a
3338 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003339 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003340 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003341
Chris Lattner1f3a0632010-07-29 21:42:50 +00003342 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003343}
3344
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003345ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003346 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3347 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003348 const
3349{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003350 Ty = useFirstFieldIfTransparentUnion(Ty);
3351
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003352 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003353 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003354
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003355 // Check some invariants.
3356 // FIXME: Enforce these by construction.
3357 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003358 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3359
3360 neededInt = 0;
3361 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003362 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003363 switch (Lo) {
3364 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003365 if (Hi == NoClass)
3366 return ABIArgInfo::getIgnore();
3367 // If the low part is just padding, it takes no register, leave ResType
3368 // null.
3369 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3370 "Unknown missing lo part");
3371 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003372
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003373 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3374 // on the stack.
3375 case Memory:
3376
3377 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3378 // COMPLEX_X87, it is passed in memory.
3379 case X87:
3380 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003381 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003382 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003383 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003384
3385 case SSEUp:
3386 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003387 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003388
3389 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3390 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3391 // and %r9 is used.
3392 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003393 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003394
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003395 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003396 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003397
3398 // If we have a sign or zero extended integer, make sure to return Extend
3399 // so that the parameter gets the right LLVM IR attributes.
3400 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3401 // Treat an enum type as its underlying type.
3402 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3403 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003404
Chris Lattner1f3a0632010-07-29 21:42:50 +00003405 if (Ty->isIntegralOrEnumerationType() &&
3406 Ty->isPromotableIntegerType())
3407 return ABIArgInfo::getExtend();
3408 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003409
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003410 break;
3411
3412 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3413 // available SSE register is used, the registers are taken in the
3414 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003415 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003416 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003417 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003418 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003419 break;
3420 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003421 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003422
Craig Topper8a13c412014-05-21 05:09:00 +00003423 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003424 switch (Hi) {
3425 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003426 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003427 // which is passed in memory.
3428 case Memory:
3429 case X87:
3430 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003431 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003432
3433 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003434
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003435 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003436 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003437 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003438 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003439
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003440 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3441 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003442 break;
3443
3444 // X87Up generally doesn't occur here (long double is passed in
3445 // memory), except in situations involving unions.
3446 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003447 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003448 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003449
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003450 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3451 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003452
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003453 ++neededSSE;
3454 break;
3455
3456 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3457 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003458 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003459 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003460 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003461 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003462 break;
3463 }
3464
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003465 // If a high part was specified, merge it together with the low part. It is
3466 // known to pass in the high eightbyte of the result. We do this by forming a
3467 // first class struct aggregate with the high and low part: {low, high}
3468 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003469 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003470
Chris Lattner1f3a0632010-07-29 21:42:50 +00003471 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003472}
3473
Erich Keane757d3172016-11-02 18:29:35 +00003474ABIArgInfo
3475X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3476 unsigned &NeededSSE) const {
3477 auto RT = Ty->getAs<RecordType>();
3478 assert(RT && "classifyRegCallStructType only valid with struct types");
3479
3480 if (RT->getDecl()->hasFlexibleArrayMember())
3481 return getIndirectReturnResult(Ty);
3482
3483 // Sum up bases
3484 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3485 if (CXXRD->isDynamicClass()) {
3486 NeededInt = NeededSSE = 0;
3487 return getIndirectReturnResult(Ty);
3488 }
3489
3490 for (const auto &I : CXXRD->bases())
3491 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3492 .isIndirect()) {
3493 NeededInt = NeededSSE = 0;
3494 return getIndirectReturnResult(Ty);
3495 }
3496 }
3497
3498 // Sum up members
3499 for (const auto *FD : RT->getDecl()->fields()) {
3500 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3501 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3502 .isIndirect()) {
3503 NeededInt = NeededSSE = 0;
3504 return getIndirectReturnResult(Ty);
3505 }
3506 } else {
3507 unsigned LocalNeededInt, LocalNeededSSE;
3508 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3509 LocalNeededSSE, true)
3510 .isIndirect()) {
3511 NeededInt = NeededSSE = 0;
3512 return getIndirectReturnResult(Ty);
3513 }
3514 NeededInt += LocalNeededInt;
3515 NeededSSE += LocalNeededSSE;
3516 }
3517 }
3518
3519 return ABIArgInfo::getDirect();
3520}
3521
3522ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3523 unsigned &NeededInt,
3524 unsigned &NeededSSE) const {
3525
3526 NeededInt = 0;
3527 NeededSSE = 0;
3528
3529 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3530}
3531
Chris Lattner22326a12010-07-29 02:31:05 +00003532void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003533
Erich Keane757d3172016-11-02 18:29:35 +00003534 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003535
3536 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003537 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3538 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3539 unsigned NeededInt, NeededSSE;
3540
Erich Keanede1b2a92017-07-21 18:50:36 +00003541 if (!getCXXABI().classifyReturnType(FI)) {
3542 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3543 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3544 FI.getReturnInfo() =
3545 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3546 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3547 FreeIntRegs -= NeededInt;
3548 FreeSSERegs -= NeededSSE;
3549 } else {
3550 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3551 }
3552 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3553 // Complex Long Double Type is passed in Memory when Regcall
3554 // calling convention is used.
3555 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3556 if (getContext().getCanonicalType(CT->getElementType()) ==
3557 getContext().LongDoubleTy)
3558 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3559 } else
3560 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3561 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003562
3563 // If the return value is indirect, then the hidden argument is consuming one
3564 // integer register.
3565 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003566 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003567
Peter Collingbournef7706832014-12-12 23:41:25 +00003568 // The chain argument effectively gives us another free register.
3569 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003570 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003571
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003572 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003573 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3574 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003575 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003576 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003577 it != ie; ++it, ++ArgNo) {
3578 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003579
Erich Keane757d3172016-11-02 18:29:35 +00003580 if (IsRegCall && it->type->isStructureOrClassType())
3581 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3582 else
3583 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3584 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003585
3586 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3587 // eightbyte of an argument, the whole argument is passed on the
3588 // stack. If registers have already been assigned for some
3589 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003590 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3591 FreeIntRegs -= NeededInt;
3592 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003593 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003594 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003595 }
3596 }
3597}
3598
John McCall7f416cc2015-09-08 08:05:57 +00003599static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3600 Address VAListAddr, QualType Ty) {
3601 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3602 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003603 llvm::Value *overflow_arg_area =
3604 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3605
3606 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3607 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003608 // It isn't stated explicitly in the standard, but in practice we use
3609 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003610 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3611 if (Align > CharUnits::fromQuantity(8)) {
3612 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3613 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003614 }
3615
3616 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003617 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003618 llvm::Value *Res =
3619 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003620 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003621
3622 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3623 // l->overflow_arg_area + sizeof(type).
3624 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3625 // an 8 byte boundary.
3626
3627 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003628 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003629 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003630 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3631 "overflow_arg_area.next");
3632 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3633
3634 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003635 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003636}
3637
John McCall7f416cc2015-09-08 08:05:57 +00003638Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3639 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003640 // Assume that va_list type is correct; should be pointer to LLVM type:
3641 // struct {
3642 // i32 gp_offset;
3643 // i32 fp_offset;
3644 // i8* overflow_arg_area;
3645 // i8* reg_save_area;
3646 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003647 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003648
John McCall7f416cc2015-09-08 08:05:57 +00003649 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003650 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003651 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003652
3653 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3654 // in the registers. If not go to step 7.
3655 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003656 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003657
3658 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3659 // general purpose registers needed to pass type and num_fp to hold
3660 // the number of floating point registers needed.
3661
3662 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3663 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3664 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3665 //
3666 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3667 // register save space).
3668
Craig Topper8a13c412014-05-21 05:09:00 +00003669 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003670 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3671 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003672 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003673 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003674 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3675 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003676 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003677 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3678 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003679 }
3680
3681 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003682 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003683 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3684 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003685 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3686 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003687 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3688 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003689 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3690 }
3691
3692 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3693 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3694 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3695 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3696
3697 // Emit code to load the value if it was passed in registers.
3698
3699 CGF.EmitBlock(InRegBlock);
3700
3701 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3702 // an offset of l->gp_offset and/or l->fp_offset. This may require
3703 // copying to a temporary location in case the parameter is passed
3704 // in different register classes or requires an alignment greater
3705 // than 8 for general purpose registers and 16 for XMM registers.
3706 //
3707 // FIXME: This really results in shameful code when we end up needing to
3708 // collect arguments from different places; often what should result in a
3709 // simple assembling of a structure from scattered addresses has many more
3710 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003711 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003712 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3713 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3714 "reg_save_area");
3715
3716 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003717 if (neededInt && neededSSE) {
3718 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003719 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003720 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003721 Address Tmp = CGF.CreateMemTemp(Ty);
3722 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003723 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003724 llvm::Type *TyLo = ST->getElementType(0);
3725 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003726 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003727 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003728 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3729 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003730 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3731 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003732 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3733 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003734
John McCall7f416cc2015-09-08 08:05:57 +00003735 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003736 // FIXME: Our choice of alignment here and below is probably pessimistic.
3737 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3738 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3739 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003740 CGF.Builder.CreateStore(V,
3741 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3742
3743 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003744 V = CGF.Builder.CreateAlignedLoad(
3745 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3746 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003747 CharUnits Offset = CharUnits::fromQuantity(
3748 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3749 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3750
3751 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003752 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003753 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3754 CharUnits::fromQuantity(8));
3755 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003756
3757 // Copy to a temporary if necessary to ensure the appropriate alignment.
3758 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003759 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003760 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003761 CharUnits TyAlign = SizeAlign.second;
3762
3763 // Copy into a temporary if the type is more aligned than the
3764 // register save area.
3765 if (TyAlign.getQuantity() > 8) {
3766 Address Tmp = CGF.CreateMemTemp(Ty);
3767 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003768 RegAddr = Tmp;
3769 }
John McCall7f416cc2015-09-08 08:05:57 +00003770
Chris Lattner0cf24192010-06-28 20:05:43 +00003771 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003772 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3773 CharUnits::fromQuantity(16));
3774 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003775 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003776 assert(neededSSE == 2 && "Invalid number of needed registers!");
3777 // SSE registers are spaced 16 bytes apart in the register save
3778 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003779 // The ABI isn't explicit about this, but it seems reasonable
3780 // to assume that the slots are 16-byte aligned, since the stack is
3781 // naturally 16-byte aligned and the prologue is expected to store
3782 // all the SSE registers to the RSA.
3783 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3784 CharUnits::fromQuantity(16));
3785 Address RegAddrHi =
3786 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3787 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003788 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003789 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003790 llvm::Value *V;
3791 Address Tmp = CGF.CreateMemTemp(Ty);
3792 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3793 V = CGF.Builder.CreateLoad(
3794 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3795 CGF.Builder.CreateStore(V,
3796 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3797 V = CGF.Builder.CreateLoad(
3798 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3799 CGF.Builder.CreateStore(V,
3800 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3801
3802 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003803 }
3804
3805 // AMD64-ABI 3.5.7p5: Step 5. Set:
3806 // l->gp_offset = l->gp_offset + num_gp * 8
3807 // l->fp_offset = l->fp_offset + num_fp * 16.
3808 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003809 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003810 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3811 gp_offset_p);
3812 }
3813 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003814 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003815 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3816 fp_offset_p);
3817 }
3818 CGF.EmitBranch(ContBlock);
3819
3820 // Emit code to load the value if it was passed in memory.
3821
3822 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003823 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003824
3825 // Return the appropriate result.
3826
3827 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003828 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3829 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003830 return ResAddr;
3831}
3832
Charles Davisc7d5c942015-09-17 20:55:33 +00003833Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3834 QualType Ty) const {
3835 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3836 CGF.getContext().getTypeInfoInChars(Ty),
3837 CharUnits::fromQuantity(8),
3838 /*allowHigherAlign*/ false);
3839}
3840
Erich Keane521ed962017-01-05 00:20:51 +00003841ABIArgInfo
3842WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3843 const ABIArgInfo &current) const {
3844 // Assumes vectorCall calling convention.
3845 const Type *Base = nullptr;
3846 uint64_t NumElts = 0;
3847
3848 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3849 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3850 FreeSSERegs -= NumElts;
3851 return getDirectX86Hva();
3852 }
3853 return current;
3854}
3855
Reid Kleckner80944df2014-10-31 22:00:51 +00003856ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003857 bool IsReturnType, bool IsVectorCall,
3858 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003859
3860 if (Ty->isVoidType())
3861 return ABIArgInfo::getIgnore();
3862
3863 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3864 Ty = EnumTy->getDecl()->getIntegerType();
3865
Reid Kleckner80944df2014-10-31 22:00:51 +00003866 TypeInfo Info = getContext().getTypeInfo(Ty);
3867 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003868 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003869
Reid Kleckner9005f412014-05-02 00:51:20 +00003870 const RecordType *RT = Ty->getAs<RecordType>();
3871 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003872 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003873 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003874 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003875 }
3876
3877 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003878 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003879
Reid Kleckner9005f412014-05-02 00:51:20 +00003880 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003881
Reid Kleckner80944df2014-10-31 22:00:51 +00003882 const Type *Base = nullptr;
3883 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003884 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3885 // other targets.
3886 if ((IsVectorCall || IsRegCall) &&
3887 isHomogeneousAggregate(Ty, Base, NumElts)) {
3888 if (IsRegCall) {
3889 if (FreeSSERegs >= NumElts) {
3890 FreeSSERegs -= NumElts;
3891 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3892 return ABIArgInfo::getDirect();
3893 return ABIArgInfo::getExpand();
3894 }
3895 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3896 } else if (IsVectorCall) {
3897 if (FreeSSERegs >= NumElts &&
3898 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3899 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003900 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003901 } else if (IsReturnType) {
3902 return ABIArgInfo::getExpand();
3903 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3904 // HVAs are delayed and reclassified in the 2nd step.
3905 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3906 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003907 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003908 }
3909
Reid Klecknerec87fec2014-05-02 01:17:12 +00003910 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003911 // If the member pointer is represented by an LLVM int or ptr, pass it
3912 // directly.
3913 llvm::Type *LLTy = CGT.ConvertType(Ty);
3914 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3915 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003916 }
3917
Michael Kuperstein4f818702015-02-24 09:35:58 +00003918 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003919 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3920 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003921 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003922 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003923
Reid Kleckner9005f412014-05-02 00:51:20 +00003924 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003925 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003926 }
3927
Julien Lerouge10dcff82014-08-27 00:36:55 +00003928 // Bool type is always extended to the ABI, other builtin types are not
3929 // extended.
3930 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3931 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003932 return ABIArgInfo::getExtend();
3933
Reid Kleckner11a17192015-10-28 22:29:52 +00003934 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3935 // passes them indirectly through memory.
3936 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3937 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003938 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003939 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3940 }
3941
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003942 return ABIArgInfo::getDirect();
3943}
3944
Erich Keane521ed962017-01-05 00:20:51 +00003945void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3946 unsigned FreeSSERegs,
3947 bool IsVectorCall,
3948 bool IsRegCall) const {
3949 unsigned Count = 0;
3950 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003951 // Vectorcall in x64 only permits the first 6 arguments to be passed
3952 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003953 if (Count < VectorcallMaxParamNumAsReg)
3954 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3955 else {
3956 // Since these cannot be passed in registers, pretend no registers
3957 // are left.
3958 unsigned ZeroSSERegsAvail = 0;
3959 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3960 IsVectorCall, IsRegCall);
3961 }
3962 ++Count;
3963 }
3964
Erich Keane521ed962017-01-05 00:20:51 +00003965 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003966 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003967 }
3968}
3969
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003970void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003971 bool IsVectorCall =
3972 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003973 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003974
Erich Keane757d3172016-11-02 18:29:35 +00003975 unsigned FreeSSERegs = 0;
3976 if (IsVectorCall) {
3977 // We can use up to 4 SSE return registers with vectorcall.
3978 FreeSSERegs = 4;
3979 } else if (IsRegCall) {
3980 // RegCall gives us 16 SSE registers.
3981 FreeSSERegs = 16;
3982 }
3983
Reid Kleckner80944df2014-10-31 22:00:51 +00003984 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003985 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3986 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003987
Erich Keane757d3172016-11-02 18:29:35 +00003988 if (IsVectorCall) {
3989 // We can use up to 6 SSE register parameters with vectorcall.
3990 FreeSSERegs = 6;
3991 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00003992 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00003993 FreeSSERegs = 16;
3994 }
3995
Erich Keane521ed962017-01-05 00:20:51 +00003996 if (IsVectorCall) {
3997 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3998 } else {
3999 for (auto &I : FI.arguments())
4000 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4001 }
4002
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00004003}
4004
John McCall7f416cc2015-09-08 08:05:57 +00004005Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4006 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00004007
4008 bool IsIndirect = false;
4009
4010 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4011 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4012 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4013 uint64_t Width = getContext().getTypeSize(Ty);
4014 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4015 }
4016
4017 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004018 CGF.getContext().getTypeInfoInChars(Ty),
4019 CharUnits::fromQuantity(8),
4020 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004021}
Chris Lattner0cf24192010-06-28 20:05:43 +00004022
John McCallea8d8bb2010-03-11 00:10:12 +00004023// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004024namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004025/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4026class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004027bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00004028public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004029 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4030 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004031
John McCall7f416cc2015-09-08 08:05:57 +00004032 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4033 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004034};
4035
4036class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4037public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004038 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4039 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004040
Craig Topper4f12f102014-03-12 06:41:41 +00004041 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004042 // This is recovered from gcc output.
4043 return 1; // r1 is the dedicated stack pointer
4044 }
4045
4046 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004047 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004048};
4049
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004050}
John McCallea8d8bb2010-03-11 00:10:12 +00004051
James Y Knight29b5f082016-02-24 02:59:33 +00004052// TODO: this implementation is now likely redundant with
4053// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004054Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4055 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004056 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004057 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4058 // TODO: Implement this. For now ignore.
4059 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004060 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004061 }
4062
John McCall7f416cc2015-09-08 08:05:57 +00004063 // struct __va_list_tag {
4064 // unsigned char gpr;
4065 // unsigned char fpr;
4066 // unsigned short reserved;
4067 // void *overflow_arg_area;
4068 // void *reg_save_area;
4069 // };
4070
Roman Divacky8a12d842014-11-03 18:32:54 +00004071 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004072 bool isInt =
4073 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004074 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004075
4076 // All aggregates are passed indirectly? That doesn't seem consistent
4077 // with the argument-lowering code.
4078 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004079
4080 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004081
4082 // The calling convention either uses 1-2 GPRs or 1 FPR.
4083 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004084 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004085 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4086 } else {
4087 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004088 }
John McCall7f416cc2015-09-08 08:05:57 +00004089
4090 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4091
4092 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004093 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004094 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4095 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4096 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004097
Eric Christopher7565e0d2015-05-29 23:09:49 +00004098 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004099 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004100
4101 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4102 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4103 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4104
4105 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4106
John McCall7f416cc2015-09-08 08:05:57 +00004107 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4108 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004109
John McCall7f416cc2015-09-08 08:05:57 +00004110 // Case 1: consume registers.
4111 Address RegAddr = Address::invalid();
4112 {
4113 CGF.EmitBlock(UsingRegs);
4114
4115 Address RegSaveAreaPtr =
4116 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4117 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4118 CharUnits::fromQuantity(8));
4119 assert(RegAddr.getElementType() == CGF.Int8Ty);
4120
4121 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004122 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004123 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4124 CharUnits::fromQuantity(32));
4125 }
4126
4127 // Get the address of the saved value by scaling the number of
4128 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004129 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004130 llvm::Value *RegOffset =
4131 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4132 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4133 RegAddr.getPointer(), RegOffset),
4134 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4135 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4136
4137 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004138 NumRegs =
4139 Builder.CreateAdd(NumRegs,
4140 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004141 Builder.CreateStore(NumRegs, NumRegsAddr);
4142
4143 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004144 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004145
John McCall7f416cc2015-09-08 08:05:57 +00004146 // Case 2: consume space in the overflow area.
4147 Address MemAddr = Address::invalid();
4148 {
4149 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004150
Roman Divacky039b9702016-02-20 08:31:24 +00004151 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4152
John McCall7f416cc2015-09-08 08:05:57 +00004153 // Everything in the overflow area is rounded up to a size of at least 4.
4154 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4155
4156 CharUnits Size;
4157 if (!isIndirect) {
4158 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004159 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004160 } else {
4161 Size = CGF.getPointerSize();
4162 }
4163
4164 Address OverflowAreaAddr =
4165 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004166 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004167 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004168 // Round up address of argument to alignment
4169 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4170 if (Align > OverflowAreaAlign) {
4171 llvm::Value *Ptr = OverflowArea.getPointer();
4172 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4173 Align);
4174 }
4175
John McCall7f416cc2015-09-08 08:05:57 +00004176 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4177
4178 // Increase the overflow area.
4179 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4180 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4181 CGF.EmitBranch(Cont);
4182 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004183
4184 CGF.EmitBlock(Cont);
4185
John McCall7f416cc2015-09-08 08:05:57 +00004186 // Merge the cases with a phi.
4187 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4188 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004189
John McCall7f416cc2015-09-08 08:05:57 +00004190 // Load the pointer if the argument was passed indirectly.
4191 if (isIndirect) {
4192 Result = Address(Builder.CreateLoad(Result, "aggr"),
4193 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004194 }
4195
4196 return Result;
4197}
4198
John McCallea8d8bb2010-03-11 00:10:12 +00004199bool
4200PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4201 llvm::Value *Address) const {
4202 // This is calculated from the LLVM and GCC tables and verified
4203 // against gcc output. AFAIK all ABIs use the same encoding.
4204
4205 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004206
Chris Lattnerece04092012-02-07 00:39:47 +00004207 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004208 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4209 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4210 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4211
4212 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004213 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004214
4215 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004216 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004217
4218 // 64-76 are various 4-byte special-purpose registers:
4219 // 64: mq
4220 // 65: lr
4221 // 66: ctr
4222 // 67: ap
4223 // 68-75 cr0-7
4224 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004225 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004226
4227 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004228 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004229
4230 // 109: vrsave
4231 // 110: vscr
4232 // 111: spe_acc
4233 // 112: spefscr
4234 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004235 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004236
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004237 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004238}
4239
Roman Divackyd966e722012-05-09 18:22:46 +00004240// PowerPC-64
4241
4242namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004243/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004244class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004245public:
4246 enum ABIKind {
4247 ELFv1 = 0,
4248 ELFv2
4249 };
4250
4251private:
4252 static const unsigned GPRBits = 64;
4253 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004254 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004255 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004256
4257 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4258 // will be passed in a QPX register.
4259 bool IsQPXVectorTy(const Type *Ty) const {
4260 if (!HasQPX)
4261 return false;
4262
4263 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4264 unsigned NumElements = VT->getNumElements();
4265 if (NumElements == 1)
4266 return false;
4267
4268 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4269 if (getContext().getTypeSize(Ty) <= 256)
4270 return true;
4271 } else if (VT->getElementType()->
4272 isSpecificBuiltinType(BuiltinType::Float)) {
4273 if (getContext().getTypeSize(Ty) <= 128)
4274 return true;
4275 }
4276 }
4277
4278 return false;
4279 }
4280
4281 bool IsQPXVectorTy(QualType Ty) const {
4282 return IsQPXVectorTy(Ty.getTypePtr());
4283 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004284
4285public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004286 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4287 bool SoftFloatABI)
4288 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4289 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004290
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004291 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004292 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004293
4294 ABIArgInfo classifyReturnType(QualType RetTy) const;
4295 ABIArgInfo classifyArgumentType(QualType Ty) const;
4296
Reid Klecknere9f6a712014-10-31 17:10:41 +00004297 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4298 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4299 uint64_t Members) const override;
4300
Bill Schmidt84d37792012-10-12 19:26:17 +00004301 // TODO: We can add more logic to computeInfo to improve performance.
4302 // Example: For aggregate arguments that fit in a register, we could
4303 // use getDirectInReg (as is done below for structs containing a single
4304 // floating-point value) to avoid pushing them to memory on function
4305 // entry. This would require changing the logic in PPCISelLowering
4306 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004307 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004308 if (!getCXXABI().classifyReturnType(FI))
4309 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004310 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004311 // We rely on the default argument classification for the most part.
4312 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004313 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004314 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004315 if (T) {
4316 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004317 if (IsQPXVectorTy(T) ||
4318 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004319 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004320 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004321 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004322 continue;
4323 }
4324 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004325 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004326 }
4327 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004328
John McCall7f416cc2015-09-08 08:05:57 +00004329 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4330 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004331};
4332
4333class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004334
Bill Schmidt25cb3492012-10-03 19:18:57 +00004335public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004336 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004337 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4338 bool SoftFloatABI)
4339 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4340 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004341
Craig Topper4f12f102014-03-12 06:41:41 +00004342 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004343 // This is recovered from gcc output.
4344 return 1; // r1 is the dedicated stack pointer
4345 }
4346
4347 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004348 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004349};
4350
Roman Divackyd966e722012-05-09 18:22:46 +00004351class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4352public:
4353 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4354
Craig Topper4f12f102014-03-12 06:41:41 +00004355 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004356 // This is recovered from gcc output.
4357 return 1; // r1 is the dedicated stack pointer
4358 }
4359
4360 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004361 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004362};
4363
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004364}
Roman Divackyd966e722012-05-09 18:22:46 +00004365
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004366// Return true if the ABI requires Ty to be passed sign- or zero-
4367// extended to 64 bits.
4368bool
4369PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4370 // Treat an enum type as its underlying type.
4371 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4372 Ty = EnumTy->getDecl()->getIntegerType();
4373
4374 // Promotable integer types are required to be promoted by the ABI.
4375 if (Ty->isPromotableIntegerType())
4376 return true;
4377
4378 // In addition to the usual promotable integer types, we also need to
4379 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4380 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4381 switch (BT->getKind()) {
4382 case BuiltinType::Int:
4383 case BuiltinType::UInt:
4384 return true;
4385 default:
4386 break;
4387 }
4388
4389 return false;
4390}
4391
John McCall7f416cc2015-09-08 08:05:57 +00004392/// isAlignedParamType - Determine whether a type requires 16-byte or
4393/// higher alignment in the parameter area. Always returns at least 8.
4394CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004395 // Complex types are passed just like their elements.
4396 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4397 Ty = CTy->getElementType();
4398
4399 // Only vector types of size 16 bytes need alignment (larger types are
4400 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004401 if (IsQPXVectorTy(Ty)) {
4402 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004403 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004404
John McCall7f416cc2015-09-08 08:05:57 +00004405 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004406 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004407 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004408 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004409
4410 // For single-element float/vector structs, we consider the whole type
4411 // to have the same alignment requirements as its single element.
4412 const Type *AlignAsType = nullptr;
4413 const Type *EltType = isSingleElementStruct(Ty, getContext());
4414 if (EltType) {
4415 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004416 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004417 getContext().getTypeSize(EltType) == 128) ||
4418 (BT && BT->isFloatingPoint()))
4419 AlignAsType = EltType;
4420 }
4421
Ulrich Weigandb7122372014-07-21 00:48:09 +00004422 // Likewise for ELFv2 homogeneous aggregates.
4423 const Type *Base = nullptr;
4424 uint64_t Members = 0;
4425 if (!AlignAsType && Kind == ELFv2 &&
4426 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4427 AlignAsType = Base;
4428
Ulrich Weigand581badc2014-07-10 17:20:07 +00004429 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004430 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4431 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004432 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004433
John McCall7f416cc2015-09-08 08:05:57 +00004434 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004435 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004436 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004437 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004438
4439 // Otherwise, we only need alignment for any aggregate type that
4440 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004441 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4442 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004443 return CharUnits::fromQuantity(32);
4444 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004445 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004446
John McCall7f416cc2015-09-08 08:05:57 +00004447 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004448}
4449
Ulrich Weigandb7122372014-07-21 00:48:09 +00004450/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4451/// aggregate. Base is set to the base element type, and Members is set
4452/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004453bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4454 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004455 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4456 uint64_t NElements = AT->getSize().getZExtValue();
4457 if (NElements == 0)
4458 return false;
4459 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4460 return false;
4461 Members *= NElements;
4462 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4463 const RecordDecl *RD = RT->getDecl();
4464 if (RD->hasFlexibleArrayMember())
4465 return false;
4466
4467 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004468
4469 // If this is a C++ record, check the bases first.
4470 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4471 for (const auto &I : CXXRD->bases()) {
4472 // Ignore empty records.
4473 if (isEmptyRecord(getContext(), I.getType(), true))
4474 continue;
4475
4476 uint64_t FldMembers;
4477 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4478 return false;
4479
4480 Members += FldMembers;
4481 }
4482 }
4483
Ulrich Weigandb7122372014-07-21 00:48:09 +00004484 for (const auto *FD : RD->fields()) {
4485 // Ignore (non-zero arrays of) empty records.
4486 QualType FT = FD->getType();
4487 while (const ConstantArrayType *AT =
4488 getContext().getAsConstantArrayType(FT)) {
4489 if (AT->getSize().getZExtValue() == 0)
4490 return false;
4491 FT = AT->getElementType();
4492 }
4493 if (isEmptyRecord(getContext(), FT, true))
4494 continue;
4495
4496 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4497 if (getContext().getLangOpts().CPlusPlus &&
4498 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4499 continue;
4500
4501 uint64_t FldMembers;
4502 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4503 return false;
4504
4505 Members = (RD->isUnion() ?
4506 std::max(Members, FldMembers) : Members + FldMembers);
4507 }
4508
4509 if (!Base)
4510 return false;
4511
4512 // Ensure there is no padding.
4513 if (getContext().getTypeSize(Base) * Members !=
4514 getContext().getTypeSize(Ty))
4515 return false;
4516 } else {
4517 Members = 1;
4518 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4519 Members = 2;
4520 Ty = CT->getElementType();
4521 }
4522
Reid Klecknere9f6a712014-10-31 17:10:41 +00004523 // Most ABIs only support float, double, and some vector type widths.
4524 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004525 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004526
4527 // The base type must be the same for all members. Types that
4528 // agree in both total size and mode (float vs. vector) are
4529 // treated as being equivalent here.
4530 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004531 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004532 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004533 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4534 // so make sure to widen it explicitly.
4535 if (const VectorType *VT = Base->getAs<VectorType>()) {
4536 QualType EltTy = VT->getElementType();
4537 unsigned NumElements =
4538 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4539 Base = getContext()
4540 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4541 .getTypePtr();
4542 }
4543 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004544
4545 if (Base->isVectorType() != TyPtr->isVectorType() ||
4546 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4547 return false;
4548 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004549 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4550}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004551
Reid Klecknere9f6a712014-10-31 17:10:41 +00004552bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4553 // Homogeneous aggregates for ELFv2 must have base types of float,
4554 // double, long double, or 128-bit vectors.
4555 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4556 if (BT->getKind() == BuiltinType::Float ||
4557 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004558 BT->getKind() == BuiltinType::LongDouble) {
4559 if (IsSoftFloatABI)
4560 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004561 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004562 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004563 }
4564 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004565 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004566 return true;
4567 }
4568 return false;
4569}
4570
4571bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4572 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004573 // Vector types require one register, floating point types require one
4574 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004575 uint32_t NumRegs =
4576 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004577
4578 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004579 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004580}
4581
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004582ABIArgInfo
4583PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004584 Ty = useFirstFieldIfTransparentUnion(Ty);
4585
Bill Schmidt90b22c92012-11-27 02:46:43 +00004586 if (Ty->isAnyComplexType())
4587 return ABIArgInfo::getDirect();
4588
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004589 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4590 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004591 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004592 uint64_t Size = getContext().getTypeSize(Ty);
4593 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004594 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004595 else if (Size < 128) {
4596 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4597 return ABIArgInfo::getDirect(CoerceTy);
4598 }
4599 }
4600
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004601 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004602 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004603 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004604
John McCall7f416cc2015-09-08 08:05:57 +00004605 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4606 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004607
4608 // ELFv2 homogeneous aggregates are passed as array types.
4609 const Type *Base = nullptr;
4610 uint64_t Members = 0;
4611 if (Kind == ELFv2 &&
4612 isHomogeneousAggregate(Ty, Base, Members)) {
4613 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4614 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4615 return ABIArgInfo::getDirect(CoerceTy);
4616 }
4617
Ulrich Weigand601957f2014-07-21 00:56:36 +00004618 // If an aggregate may end up fully in registers, we do not
4619 // use the ByVal method, but pass the aggregate as array.
4620 // This is usually beneficial since we avoid forcing the
4621 // back-end to store the argument to memory.
4622 uint64_t Bits = getContext().getTypeSize(Ty);
4623 if (Bits > 0 && Bits <= 8 * GPRBits) {
4624 llvm::Type *CoerceTy;
4625
4626 // Types up to 8 bytes are passed as integer type (which will be
4627 // properly aligned in the argument save area doubleword).
4628 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004629 CoerceTy =
4630 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004631 // Larger types are passed as arrays, with the base type selected
4632 // according to the required alignment in the save area.
4633 else {
4634 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004635 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004636 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4637 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4638 }
4639
4640 return ABIArgInfo::getDirect(CoerceTy);
4641 }
4642
Ulrich Weigandb7122372014-07-21 00:48:09 +00004643 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004644 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4645 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004646 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004647 }
4648
4649 return (isPromotableTypeForABI(Ty) ?
4650 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4651}
4652
4653ABIArgInfo
4654PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4655 if (RetTy->isVoidType())
4656 return ABIArgInfo::getIgnore();
4657
Bill Schmidta3d121c2012-12-17 04:20:17 +00004658 if (RetTy->isAnyComplexType())
4659 return ABIArgInfo::getDirect();
4660
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004661 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4662 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004663 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004664 uint64_t Size = getContext().getTypeSize(RetTy);
4665 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004666 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004667 else if (Size < 128) {
4668 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4669 return ABIArgInfo::getDirect(CoerceTy);
4670 }
4671 }
4672
Ulrich Weigandb7122372014-07-21 00:48:09 +00004673 if (isAggregateTypeForABI(RetTy)) {
4674 // ELFv2 homogeneous aggregates are returned as array types.
4675 const Type *Base = nullptr;
4676 uint64_t Members = 0;
4677 if (Kind == ELFv2 &&
4678 isHomogeneousAggregate(RetTy, Base, Members)) {
4679 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4680 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4681 return ABIArgInfo::getDirect(CoerceTy);
4682 }
4683
4684 // ELFv2 small aggregates are returned in up to two registers.
4685 uint64_t Bits = getContext().getTypeSize(RetTy);
4686 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4687 if (Bits == 0)
4688 return ABIArgInfo::getIgnore();
4689
4690 llvm::Type *CoerceTy;
4691 if (Bits > GPRBits) {
4692 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004693 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004694 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004695 CoerceTy =
4696 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004697 return ABIArgInfo::getDirect(CoerceTy);
4698 }
4699
4700 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004701 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004702 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004703
4704 return (isPromotableTypeForABI(RetTy) ?
4705 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4706}
4707
Bill Schmidt25cb3492012-10-03 19:18:57 +00004708// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004709Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4710 QualType Ty) const {
4711 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4712 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004713
John McCall7f416cc2015-09-08 08:05:57 +00004714 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004715
Bill Schmidt924c4782013-01-14 17:45:36 +00004716 // If we have a complex type and the base type is smaller than 8 bytes,
4717 // the ABI calls for the real and imaginary parts to be right-adjusted
4718 // in separate doublewords. However, Clang expects us to produce a
4719 // pointer to a structure with the two parts packed tightly. So generate
4720 // loads of the real and imaginary parts relative to the va_list pointer,
4721 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004722 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4723 CharUnits EltSize = TypeInfo.first / 2;
4724 if (EltSize < SlotSize) {
4725 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4726 SlotSize * 2, SlotSize,
4727 SlotSize, /*AllowHigher*/ true);
4728
4729 Address RealAddr = Addr;
4730 Address ImagAddr = RealAddr;
4731 if (CGF.CGM.getDataLayout().isBigEndian()) {
4732 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4733 SlotSize - EltSize);
4734 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4735 2 * SlotSize - EltSize);
4736 } else {
4737 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4738 }
4739
4740 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4741 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4742 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4743 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4744 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4745
4746 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4747 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4748 /*init*/ true);
4749 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004750 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004751 }
4752
John McCall7f416cc2015-09-08 08:05:57 +00004753 // Otherwise, just use the general rule.
4754 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4755 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004756}
4757
4758static bool
4759PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4760 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004761 // This is calculated from the LLVM and GCC tables and verified
4762 // against gcc output. AFAIK all ABIs use the same encoding.
4763
4764 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4765
4766 llvm::IntegerType *i8 = CGF.Int8Ty;
4767 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4768 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4769 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4770
4771 // 0-31: r0-31, the 8-byte general-purpose registers
4772 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4773
4774 // 32-63: fp0-31, the 8-byte floating-point registers
4775 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4776
Hal Finkel84832a72016-08-30 02:38:34 +00004777 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004778 // 64: mq
4779 // 65: lr
4780 // 66: ctr
4781 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004782 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4783
4784 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004785 // 68-75 cr0-7
4786 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004787 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004788
4789 // 77-108: v0-31, the 16-byte vector registers
4790 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4791
4792 // 109: vrsave
4793 // 110: vscr
4794 // 111: spe_acc
4795 // 112: spefscr
4796 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004797 // 114: tfhar
4798 // 115: tfiar
4799 // 116: texasr
4800 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004801
4802 return false;
4803}
John McCallea8d8bb2010-03-11 00:10:12 +00004804
Bill Schmidt25cb3492012-10-03 19:18:57 +00004805bool
4806PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4807 CodeGen::CodeGenFunction &CGF,
4808 llvm::Value *Address) const {
4809
4810 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4811}
4812
4813bool
4814PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4815 llvm::Value *Address) const {
4816
4817 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4818}
4819
Chris Lattner0cf24192010-06-28 20:05:43 +00004820//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004821// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004822//===----------------------------------------------------------------------===//
4823
4824namespace {
4825
John McCall12f23522016-04-04 18:33:08 +00004826class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004827public:
4828 enum ABIKind {
4829 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004830 DarwinPCS,
4831 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004832 };
4833
4834private:
4835 ABIKind Kind;
4836
4837public:
John McCall12f23522016-04-04 18:33:08 +00004838 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4839 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004840
4841private:
4842 ABIKind getABIKind() const { return Kind; }
4843 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4844
4845 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004846 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004847 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4848 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4849 uint64_t Members) const override;
4850
Tim Northovera2ee4332014-03-29 15:09:45 +00004851 bool isIllegalVectorType(QualType Ty) const;
4852
David Blaikie1cbb9712014-11-14 19:09:44 +00004853 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004854 if (!getCXXABI().classifyReturnType(FI))
4855 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004856
Tim Northoverb047bfa2014-11-27 21:02:49 +00004857 for (auto &it : FI.arguments())
4858 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004859 }
4860
John McCall7f416cc2015-09-08 08:05:57 +00004861 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4862 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004863
John McCall7f416cc2015-09-08 08:05:57 +00004864 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4865 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004866
John McCall7f416cc2015-09-08 08:05:57 +00004867 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4868 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004869 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4870 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4871 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004872 }
John McCall12f23522016-04-04 18:33:08 +00004873
Martin Storsjo502de222017-07-13 17:59:14 +00004874 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4875 QualType Ty) const override;
4876
John McCall12f23522016-04-04 18:33:08 +00004877 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4878 ArrayRef<llvm::Type*> scalars,
4879 bool asReturnValue) const override {
4880 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4881 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004882 bool isSwiftErrorInRegister() const override {
4883 return true;
4884 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004885
4886 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4887 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004888};
4889
Tim Northover573cbee2014-05-24 12:52:07 +00004890class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004891public:
Tim Northover573cbee2014-05-24 12:52:07 +00004892 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4893 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004894
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004895 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00004896 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004897 }
4898
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004899 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4900 return 31;
4901 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004902
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004903 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004904};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004905
4906class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4907public:
4908 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4909 : AArch64TargetCodeGenInfo(CGT, K) {}
4910
4911 void getDependentLibraryOption(llvm::StringRef Lib,
4912 llvm::SmallString<24> &Opt) const override {
4913 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4914 }
4915
4916 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4917 llvm::SmallString<32> &Opt) const override {
4918 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4919 }
4920};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004921}
Tim Northovera2ee4332014-03-29 15:09:45 +00004922
Tim Northoverb047bfa2014-11-27 21:02:49 +00004923ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004924 Ty = useFirstFieldIfTransparentUnion(Ty);
4925
Tim Northovera2ee4332014-03-29 15:09:45 +00004926 // Handle illegal vector types here.
4927 if (isIllegalVectorType(Ty)) {
4928 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004929 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004930 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004931 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4932 return ABIArgInfo::getDirect(ResType);
4933 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004934 if (Size <= 32) {
4935 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004936 return ABIArgInfo::getDirect(ResType);
4937 }
4938 if (Size == 64) {
4939 llvm::Type *ResType =
4940 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004941 return ABIArgInfo::getDirect(ResType);
4942 }
4943 if (Size == 128) {
4944 llvm::Type *ResType =
4945 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004946 return ABIArgInfo::getDirect(ResType);
4947 }
John McCall7f416cc2015-09-08 08:05:57 +00004948 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004949 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004950
4951 if (!isAggregateTypeForABI(Ty)) {
4952 // Treat an enum type as its underlying type.
4953 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4954 Ty = EnumTy->getDecl()->getIntegerType();
4955
Tim Northovera2ee4332014-03-29 15:09:45 +00004956 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4957 ? ABIArgInfo::getExtend()
4958 : ABIArgInfo::getDirect());
4959 }
4960
4961 // Structures with either a non-trivial destructor or a non-trivial
4962 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004963 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004964 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4965 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004966 }
4967
4968 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4969 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00004970 uint64_t Size = getContext().getTypeSize(Ty);
4971 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4972 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004973 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4974 return ABIArgInfo::getIgnore();
4975
Tim Northover23bcad22017-05-05 22:36:06 +00004976 // GNU C mode. The only argument that gets ignored is an empty one with size
4977 // 0.
4978 if (IsEmpty && Size == 0)
4979 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00004980 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4981 }
4982
4983 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004984 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004985 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004986 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004987 return ABIArgInfo::getDirect(
4988 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004989 }
4990
4991 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00004992 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004993 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4994 // same size and alignment.
4995 if (getTarget().isRenderScriptTarget()) {
4996 return coerceToIntArray(Ty, getContext(), getVMContext());
4997 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004998 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00004999 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00005000
Tim Northovera2ee4332014-03-29 15:09:45 +00005001 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5002 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00005003 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005004 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5005 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5006 }
5007 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5008 }
5009
John McCall7f416cc2015-09-08 08:05:57 +00005010 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00005011}
5012
Tim Northover573cbee2014-05-24 12:52:07 +00005013ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005014 if (RetTy->isVoidType())
5015 return ABIArgInfo::getIgnore();
5016
5017 // Large vector types should be returned via memory.
5018 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005019 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005020
5021 if (!isAggregateTypeForABI(RetTy)) {
5022 // Treat an enum type as its underlying type.
5023 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5024 RetTy = EnumTy->getDecl()->getIntegerType();
5025
Tim Northover4dab6982014-04-18 13:46:08 +00005026 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5027 ? ABIArgInfo::getExtend()
5028 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005029 }
5030
Tim Northover23bcad22017-05-05 22:36:06 +00005031 uint64_t Size = getContext().getTypeSize(RetTy);
5032 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005033 return ABIArgInfo::getIgnore();
5034
Craig Topper8a13c412014-05-21 05:09:00 +00005035 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005036 uint64_t Members = 0;
5037 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005038 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5039 return ABIArgInfo::getDirect();
5040
5041 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005042 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005043 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5044 // same size and alignment.
5045 if (getTarget().isRenderScriptTarget()) {
5046 return coerceToIntArray(RetTy, getContext(), getVMContext());
5047 }
Pete Cooper635b5092015-04-17 22:16:24 +00005048 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005049 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005050
5051 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5052 // For aggregates with 16-byte alignment, we use i128.
5053 if (Alignment < 128 && Size == 128) {
5054 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5055 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5056 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005057 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5058 }
5059
John McCall7f416cc2015-09-08 08:05:57 +00005060 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005061}
5062
Tim Northover573cbee2014-05-24 12:52:07 +00005063/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5064bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005065 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5066 // Check whether VT is legal.
5067 unsigned NumElements = VT->getNumElements();
5068 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005069 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005070 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005071 return true;
5072 return Size != 64 && (Size != 128 || NumElements == 1);
5073 }
5074 return false;
5075}
5076
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005077bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5078 llvm::Type *eltTy,
5079 unsigned elts) const {
5080 if (!llvm::isPowerOf2_32(elts))
5081 return false;
5082 if (totalSize.getQuantity() != 8 &&
5083 (totalSize.getQuantity() != 16 || elts == 1))
5084 return false;
5085 return true;
5086}
5087
Reid Klecknere9f6a712014-10-31 17:10:41 +00005088bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5089 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5090 // point type or a short-vector type. This is the same as the 32-bit ABI,
5091 // but with the difference that any floating-point type is allowed,
5092 // including __fp16.
5093 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5094 if (BT->isFloatingPoint())
5095 return true;
5096 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5097 unsigned VecSize = getContext().getTypeSize(VT);
5098 if (VecSize == 64 || VecSize == 128)
5099 return true;
5100 }
5101 return false;
5102}
5103
5104bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5105 uint64_t Members) const {
5106 return Members <= 4;
5107}
5108
John McCall7f416cc2015-09-08 08:05:57 +00005109Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005110 QualType Ty,
5111 CodeGenFunction &CGF) const {
5112 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005113 bool IsIndirect = AI.isIndirect();
5114
Tim Northoverb047bfa2014-11-27 21:02:49 +00005115 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5116 if (IsIndirect)
5117 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5118 else if (AI.getCoerceToType())
5119 BaseTy = AI.getCoerceToType();
5120
5121 unsigned NumRegs = 1;
5122 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5123 BaseTy = ArrTy->getElementType();
5124 NumRegs = ArrTy->getNumElements();
5125 }
5126 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5127
Tim Northovera2ee4332014-03-29 15:09:45 +00005128 // The AArch64 va_list type and handling is specified in the Procedure Call
5129 // Standard, section B.4:
5130 //
5131 // struct {
5132 // void *__stack;
5133 // void *__gr_top;
5134 // void *__vr_top;
5135 // int __gr_offs;
5136 // int __vr_offs;
5137 // };
5138
5139 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5140 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5141 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5142 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005143
John McCall7f416cc2015-09-08 08:05:57 +00005144 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5145 CharUnits TyAlign = TyInfo.second;
5146
5147 Address reg_offs_p = Address::invalid();
5148 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005149 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005150 CharUnits reg_top_offset;
5151 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005152 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005153 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005154 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005155 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5156 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005157 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5158 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005159 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005160 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005161 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005162 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005163 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005164 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5165 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005166 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5167 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005168 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005169 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005170 }
5171
5172 //=======================================
5173 // Find out where argument was passed
5174 //=======================================
5175
5176 // If reg_offs >= 0 we're already using the stack for this type of
5177 // argument. We don't want to keep updating reg_offs (in case it overflows,
5178 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5179 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005180 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005181 UsingStack = CGF.Builder.CreateICmpSGE(
5182 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5183
5184 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5185
5186 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005187 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005188 CGF.EmitBlock(MaybeRegBlock);
5189
5190 // Integer arguments may need to correct register alignment (for example a
5191 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5192 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005193 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5194 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005195
5196 reg_offs = CGF.Builder.CreateAdd(
5197 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5198 "align_regoffs");
5199 reg_offs = CGF.Builder.CreateAnd(
5200 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5201 "aligned_regoffs");
5202 }
5203
5204 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005205 // The fact that this is done unconditionally reflects the fact that
5206 // allocating an argument to the stack also uses up all the remaining
5207 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005208 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005209 NewOffset = CGF.Builder.CreateAdd(
5210 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5211 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5212
5213 // Now we're in a position to decide whether this argument really was in
5214 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005215 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005216 InRegs = CGF.Builder.CreateICmpSLE(
5217 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5218
5219 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5220
5221 //=======================================
5222 // Argument was in registers
5223 //=======================================
5224
5225 // Now we emit the code for if the argument was originally passed in
5226 // registers. First start the appropriate block:
5227 CGF.EmitBlock(InRegBlock);
5228
John McCall7f416cc2015-09-08 08:05:57 +00005229 llvm::Value *reg_top = nullptr;
5230 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5231 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005232 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005233 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5234 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5235 Address RegAddr = Address::invalid();
5236 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005237
5238 if (IsIndirect) {
5239 // If it's been passed indirectly (actually a struct), whatever we find from
5240 // stored registers or on the stack will actually be a struct **.
5241 MemTy = llvm::PointerType::getUnqual(MemTy);
5242 }
5243
Craig Topper8a13c412014-05-21 05:09:00 +00005244 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005245 uint64_t NumMembers = 0;
5246 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005247 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005248 // Homogeneous aggregates passed in registers will have their elements split
5249 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5250 // qN+1, ...). We reload and store into a temporary local variable
5251 // contiguously.
5252 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005253 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005254 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5255 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005256 Address Tmp = CGF.CreateTempAlloca(HFATy,
5257 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005258
John McCall7f416cc2015-09-08 08:05:57 +00005259 // On big-endian platforms, the value will be right-aligned in its slot.
5260 int Offset = 0;
5261 if (CGF.CGM.getDataLayout().isBigEndian() &&
5262 BaseTyInfo.first.getQuantity() < 16)
5263 Offset = 16 - BaseTyInfo.first.getQuantity();
5264
Tim Northovera2ee4332014-03-29 15:09:45 +00005265 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005266 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5267 Address LoadAddr =
5268 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5269 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5270
5271 Address StoreAddr =
5272 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005273
5274 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5275 CGF.Builder.CreateStore(Elem, StoreAddr);
5276 }
5277
John McCall7f416cc2015-09-08 08:05:57 +00005278 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005279 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005280 // Otherwise the object is contiguous in memory.
5281
5282 // It might be right-aligned in its slot.
5283 CharUnits SlotSize = BaseAddr.getAlignment();
5284 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005285 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005286 TyInfo.first < SlotSize) {
5287 CharUnits Offset = SlotSize - TyInfo.first;
5288 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005289 }
5290
John McCall7f416cc2015-09-08 08:05:57 +00005291 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005292 }
5293
5294 CGF.EmitBranch(ContBlock);
5295
5296 //=======================================
5297 // Argument was on the stack
5298 //=======================================
5299 CGF.EmitBlock(OnStackBlock);
5300
John McCall7f416cc2015-09-08 08:05:57 +00005301 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5302 CharUnits::Zero(), "stack_p");
5303 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005304
John McCall7f416cc2015-09-08 08:05:57 +00005305 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005306 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005307 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5308 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005309
John McCall7f416cc2015-09-08 08:05:57 +00005310 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005311
John McCall7f416cc2015-09-08 08:05:57 +00005312 OnStackPtr = CGF.Builder.CreateAdd(
5313 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005314 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005315 OnStackPtr = CGF.Builder.CreateAnd(
5316 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005317 "align_stack");
5318
John McCall7f416cc2015-09-08 08:05:57 +00005319 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005320 }
John McCall7f416cc2015-09-08 08:05:57 +00005321 Address OnStackAddr(OnStackPtr,
5322 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005323
John McCall7f416cc2015-09-08 08:05:57 +00005324 // All stack slots are multiples of 8 bytes.
5325 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5326 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005327 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005328 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005329 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005330 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005331
John McCall7f416cc2015-09-08 08:05:57 +00005332 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005333 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005334 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005335
5336 // Write the new value of __stack for the next call to va_arg
5337 CGF.Builder.CreateStore(NewStack, stack_p);
5338
5339 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005340 TyInfo.first < StackSlotSize) {
5341 CharUnits Offset = StackSlotSize - TyInfo.first;
5342 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005343 }
5344
John McCall7f416cc2015-09-08 08:05:57 +00005345 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005346
5347 CGF.EmitBranch(ContBlock);
5348
5349 //=======================================
5350 // Tidy up
5351 //=======================================
5352 CGF.EmitBlock(ContBlock);
5353
John McCall7f416cc2015-09-08 08:05:57 +00005354 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5355 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005356
5357 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005358 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5359 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005360
5361 return ResAddr;
5362}
5363
John McCall7f416cc2015-09-08 08:05:57 +00005364Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5365 CodeGenFunction &CGF) const {
5366 // The backend's lowering doesn't support va_arg for aggregates or
5367 // illegal vector types. Lower VAArg here for these cases and use
5368 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005369 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005370 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005371
John McCall7f416cc2015-09-08 08:05:57 +00005372 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005373
John McCall7f416cc2015-09-08 08:05:57 +00005374 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005375 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005376 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5377 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5378 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005379 }
5380
John McCall7f416cc2015-09-08 08:05:57 +00005381 // The size of the actual thing passed, which might end up just
5382 // being a pointer for indirect types.
5383 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5384
5385 // Arguments bigger than 16 bytes which aren't homogeneous
5386 // aggregates should be passed indirectly.
5387 bool IsIndirect = false;
5388 if (TyInfo.first.getQuantity() > 16) {
5389 const Type *Base = nullptr;
5390 uint64_t Members = 0;
5391 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005392 }
5393
John McCall7f416cc2015-09-08 08:05:57 +00005394 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5395 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005396}
5397
Martin Storsjo502de222017-07-13 17:59:14 +00005398Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5399 QualType Ty) const {
5400 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5401 CGF.getContext().getTypeInfoInChars(Ty),
5402 CharUnits::fromQuantity(8),
5403 /*allowHigherAlign*/ false);
5404}
5405
Tim Northovera2ee4332014-03-29 15:09:45 +00005406//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005407// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005408//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005409
5410namespace {
5411
John McCall12f23522016-04-04 18:33:08 +00005412class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005413public:
5414 enum ABIKind {
5415 APCS = 0,
5416 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005417 AAPCS_VFP = 2,
5418 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005419 };
5420
5421private:
5422 ABIKind Kind;
5423
5424public:
John McCall12f23522016-04-04 18:33:08 +00005425 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5426 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005427 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005428 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005429
John McCall3480ef22011-08-30 01:42:09 +00005430 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005431 switch (getTarget().getTriple().getEnvironment()) {
5432 case llvm::Triple::Android:
5433 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005434 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005435 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005436 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005437 case llvm::Triple::MuslEABI:
5438 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005439 return true;
5440 default:
5441 return false;
5442 }
John McCall3480ef22011-08-30 01:42:09 +00005443 }
5444
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005445 bool isEABIHF() const {
5446 switch (getTarget().getTriple().getEnvironment()) {
5447 case llvm::Triple::EABIHF:
5448 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005449 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005450 return true;
5451 default:
5452 return false;
5453 }
5454 }
5455
Daniel Dunbar020daa92009-09-12 01:00:39 +00005456 ABIKind getABIKind() const { return Kind; }
5457
Tim Northovera484bc02013-10-01 14:34:25 +00005458private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005459 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005460 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005461 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005462
Reid Klecknere9f6a712014-10-31 17:10:41 +00005463 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5464 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5465 uint64_t Members) const override;
5466
Craig Topper4f12f102014-03-12 06:41:41 +00005467 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005468
John McCall7f416cc2015-09-08 08:05:57 +00005469 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5470 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005471
5472 llvm::CallingConv::ID getLLVMDefaultCC() const;
5473 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005474 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005475
5476 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5477 ArrayRef<llvm::Type*> scalars,
5478 bool asReturnValue) const override {
5479 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5480 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005481 bool isSwiftErrorInRegister() const override {
5482 return true;
5483 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005484 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5485 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005486};
5487
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005488class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5489public:
Chris Lattner2b037972010-07-29 02:01:43 +00005490 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5491 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005492
John McCall3480ef22011-08-30 01:42:09 +00005493 const ARMABIInfo &getABIInfo() const {
5494 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5495 }
5496
Craig Topper4f12f102014-03-12 06:41:41 +00005497 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005498 return 13;
5499 }
Roman Divackyc1617352011-05-18 19:36:54 +00005500
Craig Topper4f12f102014-03-12 06:41:41 +00005501 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Oliver Stannard7f188642017-08-21 09:54:46 +00005502 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
John McCall31168b02011-06-15 23:02:42 +00005503 }
5504
Roman Divackyc1617352011-05-18 19:36:54 +00005505 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005506 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005507 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005508
5509 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005510 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005511 return false;
5512 }
John McCall3480ef22011-08-30 01:42:09 +00005513
Craig Topper4f12f102014-03-12 06:41:41 +00005514 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005515 if (getABIInfo().isEABI()) return 88;
5516 return TargetCodeGenInfo::getSizeOfUnwindException();
5517 }
Tim Northovera484bc02013-10-01 14:34:25 +00005518
Eric Christopher162c91c2015-06-05 22:03:00 +00005519 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005520 CodeGen::CodeGenModule &CGM,
5521 ForDefinition_t IsForDefinition) const override {
5522 if (!IsForDefinition)
5523 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005524 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005525 if (!FD)
5526 return;
5527
5528 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5529 if (!Attr)
5530 return;
5531
5532 const char *Kind;
5533 switch (Attr->getInterrupt()) {
5534 case ARMInterruptAttr::Generic: Kind = ""; break;
5535 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5536 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5537 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5538 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5539 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5540 }
5541
5542 llvm::Function *Fn = cast<llvm::Function>(GV);
5543
5544 Fn->addFnAttr("interrupt", Kind);
5545
Tim Northover5627d392015-10-30 16:30:45 +00005546 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5547 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005548 return;
5549
5550 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5551 // however this is not necessarily true on taking any interrupt. Instruct
5552 // the backend to perform a realignment as part of the function prologue.
5553 llvm::AttrBuilder B;
5554 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005555 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005556 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005557};
5558
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005559class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005560public:
5561 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5562 : ARMTargetCodeGenInfo(CGT, K) {}
5563
Eric Christopher162c91c2015-06-05 22:03:00 +00005564 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005565 CodeGen::CodeGenModule &CGM,
5566 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005567
5568 void getDependentLibraryOption(llvm::StringRef Lib,
5569 llvm::SmallString<24> &Opt) const override {
5570 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5571 }
5572
5573 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5574 llvm::SmallString<32> &Opt) const override {
5575 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5576 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005577};
5578
Eric Christopher162c91c2015-06-05 22:03:00 +00005579void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005580 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5581 ForDefinition_t IsForDefinition) const {
5582 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5583 if (!IsForDefinition)
5584 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005585 addStackProbeSizeTargetAttribute(D, GV, CGM);
5586}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005587}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005588
Chris Lattner22326a12010-07-29 02:31:05 +00005589void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005590 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005591 FI.getReturnInfo() =
5592 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005593
Tim Northoverbc784d12015-02-24 17:22:40 +00005594 for (auto &I : FI.arguments())
5595 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005596
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005597 // Always honor user-specified calling convention.
5598 if (FI.getCallingConvention() != llvm::CallingConv::C)
5599 return;
5600
John McCall882987f2013-02-28 19:01:20 +00005601 llvm::CallingConv::ID cc = getRuntimeCC();
5602 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005603 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005604}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005605
John McCall882987f2013-02-28 19:01:20 +00005606/// Return the default calling convention that LLVM will use.
5607llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5608 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005609 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005610 return llvm::CallingConv::ARM_AAPCS_VFP;
5611 else if (isEABI())
5612 return llvm::CallingConv::ARM_AAPCS;
5613 else
5614 return llvm::CallingConv::ARM_APCS;
5615}
5616
5617/// Return the calling convention that our ABI would like us to use
5618/// as the C calling convention.
5619llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005620 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005621 case APCS: return llvm::CallingConv::ARM_APCS;
5622 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5623 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005624 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005625 }
John McCall882987f2013-02-28 19:01:20 +00005626 llvm_unreachable("bad ABI kind");
5627}
5628
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005629void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005630 assert(getRuntimeCC() == llvm::CallingConv::C);
5631
5632 // Don't muddy up the IR with a ton of explicit annotations if
5633 // they'd just match what LLVM will infer from the triple.
5634 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5635 if (abiCC != getLLVMDefaultCC())
5636 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005637
Tim Northover5627d392015-10-30 16:30:45 +00005638 // AAPCS apparently requires runtime support functions to be soft-float, but
5639 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5640 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005641
5642 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5643 // AEABI-complying FP helper functions to use the base AAPCS.
5644 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5645 // support functions emitted by clang such as the _Complex helpers follow the
5646 // abiCC.
5647 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005648 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005649}
5650
Tim Northoverbc784d12015-02-24 17:22:40 +00005651ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5652 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005653 // 6.1.2.1 The following argument types are VFP CPRCs:
5654 // A single-precision floating-point type (including promoted
5655 // half-precision types); A double-precision floating-point type;
5656 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5657 // with a Base Type of a single- or double-precision floating-point type,
5658 // 64-bit containerized vectors or 128-bit containerized vectors with one
5659 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005660 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005661
Reid Klecknerb1be6832014-11-15 01:41:41 +00005662 Ty = useFirstFieldIfTransparentUnion(Ty);
5663
Manman Renfef9e312012-10-16 19:18:39 +00005664 // Handle illegal vector types here.
5665 if (isIllegalVectorType(Ty)) {
5666 uint64_t Size = getContext().getTypeSize(Ty);
5667 if (Size <= 32) {
5668 llvm::Type *ResType =
5669 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005670 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005671 }
5672 if (Size == 64) {
5673 llvm::Type *ResType = llvm::VectorType::get(
5674 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005675 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005676 }
5677 if (Size == 128) {
5678 llvm::Type *ResType = llvm::VectorType::get(
5679 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005680 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005681 }
John McCall7f416cc2015-09-08 08:05:57 +00005682 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005683 }
5684
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005685 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5686 // unspecified. This is not done for OpenCL as it handles the half type
5687 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005688 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005689 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5690 llvm::Type::getFloatTy(getVMContext()) :
5691 llvm::Type::getInt32Ty(getVMContext());
5692 return ABIArgInfo::getDirect(ResType);
5693 }
5694
John McCalla1dee5302010-08-22 10:59:02 +00005695 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005696 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005697 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005698 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005699 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005700
Tim Northover5a1558e2014-11-07 22:30:50 +00005701 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5702 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005703 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005704
Oliver Stannard405bded2014-02-11 09:25:50 +00005705 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005706 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005707 }
Tim Northover1060eae2013-06-21 22:49:34 +00005708
Daniel Dunbar09d33622009-09-14 21:54:03 +00005709 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005710 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005711 return ABIArgInfo::getIgnore();
5712
Tim Northover5a1558e2014-11-07 22:30:50 +00005713 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005714 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5715 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005716 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005717 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005718 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005719 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005720 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005721 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005722 }
Tim Northover5627d392015-10-30 16:30:45 +00005723 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5724 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5725 // this convention even for a variadic function: the backend will use GPRs
5726 // if needed.
5727 const Type *Base = nullptr;
5728 uint64_t Members = 0;
5729 if (isHomogeneousAggregate(Ty, Base, Members)) {
5730 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5731 llvm::Type *Ty =
5732 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5733 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5734 }
5735 }
5736
5737 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5738 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5739 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5740 // bigger than 128-bits, they get placed in space allocated by the caller,
5741 // and a pointer is passed.
5742 return ABIArgInfo::getIndirect(
5743 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005744 }
5745
Manman Ren6c30e132012-08-13 21:23:55 +00005746 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005747 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5748 // most 8-byte. We realign the indirect argument if type alignment is bigger
5749 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005750 uint64_t ABIAlign = 4;
5751 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5752 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005753 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005754 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005755
Manman Ren8cd99812012-11-06 04:58:01 +00005756 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005757 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005758 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5759 /*ByVal=*/true,
5760 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005761 }
5762
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005763 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5764 // same size and alignment.
5765 if (getTarget().isRenderScriptTarget()) {
5766 return coerceToIntArray(Ty, getContext(), getVMContext());
5767 }
5768
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005769 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005770 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005771 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005772 // FIXME: Try to match the types of the arguments more accurately where
5773 // we can.
5774 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005775 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5776 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005777 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005778 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5779 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005780 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005781
Tim Northover5a1558e2014-11-07 22:30:50 +00005782 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005783}
5784
Chris Lattner458b2aa2010-07-29 02:16:43 +00005785static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005786 llvm::LLVMContext &VMContext) {
5787 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5788 // is called integer-like if its size is less than or equal to one word, and
5789 // the offset of each of its addressable sub-fields is zero.
5790
5791 uint64_t Size = Context.getTypeSize(Ty);
5792
5793 // Check that the type fits in a word.
5794 if (Size > 32)
5795 return false;
5796
5797 // FIXME: Handle vector types!
5798 if (Ty->isVectorType())
5799 return false;
5800
Daniel Dunbard53bac72009-09-14 02:20:34 +00005801 // Float types are never treated as "integer like".
5802 if (Ty->isRealFloatingType())
5803 return false;
5804
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005805 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005806 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005807 return true;
5808
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005809 // Small complex integer types are "integer like".
5810 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5811 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005812
5813 // Single element and zero sized arrays should be allowed, by the definition
5814 // above, but they are not.
5815
5816 // Otherwise, it must be a record type.
5817 const RecordType *RT = Ty->getAs<RecordType>();
5818 if (!RT) return false;
5819
5820 // Ignore records with flexible arrays.
5821 const RecordDecl *RD = RT->getDecl();
5822 if (RD->hasFlexibleArrayMember())
5823 return false;
5824
5825 // Check that all sub-fields are at offset 0, and are themselves "integer
5826 // like".
5827 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5828
5829 bool HadField = false;
5830 unsigned idx = 0;
5831 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5832 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005833 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005834
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005835 // Bit-fields are not addressable, we only need to verify they are "integer
5836 // like". We still have to disallow a subsequent non-bitfield, for example:
5837 // struct { int : 0; int x }
5838 // is non-integer like according to gcc.
5839 if (FD->isBitField()) {
5840 if (!RD->isUnion())
5841 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005842
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005843 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5844 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005845
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005846 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005847 }
5848
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005849 // Check if this field is at offset 0.
5850 if (Layout.getFieldOffset(idx) != 0)
5851 return false;
5852
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005853 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5854 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005855
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005856 // Only allow at most one field in a structure. This doesn't match the
5857 // wording above, but follows gcc in situations with a field following an
5858 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005859 if (!RD->isUnion()) {
5860 if (HadField)
5861 return false;
5862
5863 HadField = true;
5864 }
5865 }
5866
5867 return true;
5868}
5869
Oliver Stannard405bded2014-02-11 09:25:50 +00005870ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5871 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005872 bool IsEffectivelyAAPCS_VFP =
5873 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005874
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005875 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005876 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005877
Daniel Dunbar19964db2010-09-23 01:54:32 +00005878 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005879 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005880 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005881 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005882
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005883 // __fp16 gets returned as if it were an int or float, but with the top 16
5884 // bits unspecified. This is not done for OpenCL as it handles the half type
5885 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005886 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005887 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5888 llvm::Type::getFloatTy(getVMContext()) :
5889 llvm::Type::getInt32Ty(getVMContext());
5890 return ABIArgInfo::getDirect(ResType);
5891 }
5892
John McCalla1dee5302010-08-22 10:59:02 +00005893 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005894 // Treat an enum type as its underlying type.
5895 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5896 RetTy = EnumTy->getDecl()->getIntegerType();
5897
Tim Northover5a1558e2014-11-07 22:30:50 +00005898 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5899 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005900 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005901
5902 // Are we following APCS?
5903 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005904 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005905 return ABIArgInfo::getIgnore();
5906
Daniel Dunbareedf1512010-02-01 23:31:19 +00005907 // Complex types are all returned as packed integers.
5908 //
5909 // FIXME: Consider using 2 x vector types if the back end handles them
5910 // correctly.
5911 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005912 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5913 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005914
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005915 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005916 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005917 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005918 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005919 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005920 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005921 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005922 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5923 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005924 }
5925
5926 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005927 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005928 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005929
5930 // Otherwise this is an AAPCS variant.
5931
Chris Lattner458b2aa2010-07-29 02:16:43 +00005932 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005933 return ABIArgInfo::getIgnore();
5934
Bob Wilson1d9269a2011-11-02 04:51:36 +00005935 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005936 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005937 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005938 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005939 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005940 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005941 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005942 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005943 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005944 }
5945
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005946 // Aggregates <= 4 bytes are returned in r0; other aggregates
5947 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005948 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005949 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005950 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5951 // same size and alignment.
5952 if (getTarget().isRenderScriptTarget()) {
5953 return coerceToIntArray(RetTy, getContext(), getVMContext());
5954 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005955 if (getDataLayout().isBigEndian())
5956 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005957 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005958
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005959 // Return in the smallest viable integer type.
5960 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005961 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005962 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005963 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5964 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005965 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5966 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5967 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005968 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005969 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005970 }
5971
John McCall7f416cc2015-09-08 08:05:57 +00005972 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005973}
5974
Manman Renfef9e312012-10-16 19:18:39 +00005975/// isIllegalVector - check whether Ty is an illegal vector type.
5976bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005977 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5978 if (isAndroid()) {
5979 // Android shipped using Clang 3.1, which supported a slightly different
5980 // vector ABI. The primary differences were that 3-element vector types
5981 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5982 // accepts that legacy behavior for Android only.
5983 // Check whether VT is legal.
5984 unsigned NumElements = VT->getNumElements();
5985 // NumElements should be power of 2 or equal to 3.
5986 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5987 return true;
5988 } else {
5989 // Check whether VT is legal.
5990 unsigned NumElements = VT->getNumElements();
5991 uint64_t Size = getContext().getTypeSize(VT);
5992 // NumElements should be power of 2.
5993 if (!llvm::isPowerOf2_32(NumElements))
5994 return true;
5995 // Size should be greater than 32 bits.
5996 return Size <= 32;
5997 }
Manman Renfef9e312012-10-16 19:18:39 +00005998 }
5999 return false;
6000}
6001
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00006002bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6003 llvm::Type *eltTy,
6004 unsigned numElts) const {
6005 if (!llvm::isPowerOf2_32(numElts))
6006 return false;
6007 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6008 if (size > 64)
6009 return false;
6010 if (vectorSize.getQuantity() != 8 &&
6011 (vectorSize.getQuantity() != 16 || numElts == 1))
6012 return false;
6013 return true;
6014}
6015
Reid Klecknere9f6a712014-10-31 17:10:41 +00006016bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6017 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6018 // double, or 64-bit or 128-bit vectors.
6019 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6020 if (BT->getKind() == BuiltinType::Float ||
6021 BT->getKind() == BuiltinType::Double ||
6022 BT->getKind() == BuiltinType::LongDouble)
6023 return true;
6024 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6025 unsigned VecSize = getContext().getTypeSize(VT);
6026 if (VecSize == 64 || VecSize == 128)
6027 return true;
6028 }
6029 return false;
6030}
6031
6032bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6033 uint64_t Members) const {
6034 return Members <= 4;
6035}
6036
John McCall7f416cc2015-09-08 08:05:57 +00006037Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6038 QualType Ty) const {
6039 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006040
John McCall7f416cc2015-09-08 08:05:57 +00006041 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006042 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006043 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6044 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6045 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006046 }
6047
John McCall7f416cc2015-09-08 08:05:57 +00006048 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6049 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006050
John McCall7f416cc2015-09-08 08:05:57 +00006051 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6052 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006053 const Type *Base = nullptr;
6054 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006055 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6056 IsIndirect = true;
6057
Tim Northover5627d392015-10-30 16:30:45 +00006058 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6059 // allocated by the caller.
6060 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6061 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6062 !isHomogeneousAggregate(Ty, Base, Members)) {
6063 IsIndirect = true;
6064
John McCall7f416cc2015-09-08 08:05:57 +00006065 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006066 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6067 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006068 // Our callers should be prepared to handle an under-aligned address.
6069 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6070 getABIKind() == ARMABIInfo::AAPCS) {
6071 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6072 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006073 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6074 // ARMv7k allows type alignment up to 16 bytes.
6075 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6076 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006077 } else {
6078 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006079 }
John McCall7f416cc2015-09-08 08:05:57 +00006080 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006081
John McCall7f416cc2015-09-08 08:05:57 +00006082 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6083 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006084}
6085
Chris Lattner0cf24192010-06-28 20:05:43 +00006086//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006087// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006088//===----------------------------------------------------------------------===//
6089
6090namespace {
6091
Justin Holewinski83e96682012-05-24 17:43:12 +00006092class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006093public:
Justin Holewinski36837432013-03-30 14:38:24 +00006094 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006095
6096 ABIArgInfo classifyReturnType(QualType RetTy) const;
6097 ABIArgInfo classifyArgumentType(QualType Ty) const;
6098
Craig Topper4f12f102014-03-12 06:41:41 +00006099 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006100 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6101 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006102};
6103
Justin Holewinski83e96682012-05-24 17:43:12 +00006104class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006105public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006106 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6107 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006108
Eric Christopher162c91c2015-06-05 22:03:00 +00006109 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006110 CodeGen::CodeGenModule &M,
6111 ForDefinition_t IsForDefinition) const override;
6112
Justin Holewinski36837432013-03-30 14:38:24 +00006113private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006114 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6115 // resulting MDNode to the nvvm.annotations MDNode.
6116 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006117};
6118
Justin Holewinski83e96682012-05-24 17:43:12 +00006119ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006120 if (RetTy->isVoidType())
6121 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006122
6123 // note: this is different from default ABI
6124 if (!RetTy->isScalarType())
6125 return ABIArgInfo::getDirect();
6126
6127 // Treat an enum type as its underlying type.
6128 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6129 RetTy = EnumTy->getDecl()->getIntegerType();
6130
6131 return (RetTy->isPromotableIntegerType() ?
6132 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006133}
6134
Justin Holewinski83e96682012-05-24 17:43:12 +00006135ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006136 // Treat an enum type as its underlying type.
6137 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6138 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006139
Eli Bendersky95338a02014-10-29 13:43:21 +00006140 // Return aggregates type as indirect by value
6141 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006142 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006143
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006144 return (Ty->isPromotableIntegerType() ?
6145 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006146}
6147
Justin Holewinski83e96682012-05-24 17:43:12 +00006148void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006149 if (!getCXXABI().classifyReturnType(FI))
6150 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006151 for (auto &I : FI.arguments())
6152 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006153
6154 // Always honor user-specified calling convention.
6155 if (FI.getCallingConvention() != llvm::CallingConv::C)
6156 return;
6157
John McCall882987f2013-02-28 19:01:20 +00006158 FI.setEffectiveCallingConvention(getRuntimeCC());
6159}
6160
John McCall7f416cc2015-09-08 08:05:57 +00006161Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6162 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006163 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006164}
6165
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006166void NVPTXTargetCodeGenInfo::setTargetAttributes(
6167 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6168 ForDefinition_t IsForDefinition) const {
6169 if (!IsForDefinition)
6170 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006171 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006172 if (!FD) return;
6173
6174 llvm::Function *F = cast<llvm::Function>(GV);
6175
6176 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006177 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006178 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006179 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006180 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006181 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006182 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6183 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006184 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006185 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006186 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006187 }
Justin Holewinski38031972011-10-05 17:58:44 +00006188
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006189 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006190 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006191 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006192 // __global__ functions cannot be called from the device, we do not
6193 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006194 if (FD->hasAttr<CUDAGlobalAttr>()) {
6195 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6196 addNVVMMetadata(F, "kernel", 1);
6197 }
Artem Belevich7093e402015-04-21 22:55:54 +00006198 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006199 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006200 llvm::APSInt MaxThreads(32);
6201 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6202 if (MaxThreads > 0)
6203 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6204
6205 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6206 // not specified in __launch_bounds__ or if the user specified a 0 value,
6207 // we don't have to add a PTX directive.
6208 if (Attr->getMinBlocks()) {
6209 llvm::APSInt MinBlocks(32);
6210 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6211 if (MinBlocks > 0)
6212 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6213 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006214 }
6215 }
Justin Holewinski38031972011-10-05 17:58:44 +00006216 }
6217}
6218
Eli Benderskye06a2c42014-04-15 16:57:05 +00006219void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6220 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006221 llvm::Module *M = F->getParent();
6222 llvm::LLVMContext &Ctx = M->getContext();
6223
6224 // Get "nvvm.annotations" metadata node
6225 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6226
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006227 llvm::Metadata *MDVals[] = {
6228 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6229 llvm::ConstantAsMetadata::get(
6230 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006231 // Append metadata to nvvm.annotations
6232 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6233}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006234}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006235
6236//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006237// SystemZ ABI Implementation
6238//===----------------------------------------------------------------------===//
6239
6240namespace {
6241
Bryan Chane3f1ed52016-04-28 13:56:43 +00006242class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006243 bool HasVector;
6244
Ulrich Weigand47445072013-05-06 16:26:41 +00006245public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006246 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006247 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006248
6249 bool isPromotableIntegerType(QualType Ty) const;
6250 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006251 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006252 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006253 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006254
6255 ABIArgInfo classifyReturnType(QualType RetTy) const;
6256 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6257
Craig Topper4f12f102014-03-12 06:41:41 +00006258 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006259 if (!getCXXABI().classifyReturnType(FI))
6260 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006261 for (auto &I : FI.arguments())
6262 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006263 }
6264
John McCall7f416cc2015-09-08 08:05:57 +00006265 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6266 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006267
6268 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6269 ArrayRef<llvm::Type*> scalars,
6270 bool asReturnValue) const override {
6271 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6272 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006273 bool isSwiftErrorInRegister() const override {
6274 return true;
6275 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006276};
6277
6278class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6279public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006280 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6281 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006282};
6283
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006284}
Ulrich Weigand47445072013-05-06 16:26:41 +00006285
6286bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6287 // Treat an enum type as its underlying type.
6288 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6289 Ty = EnumTy->getDecl()->getIntegerType();
6290
6291 // Promotable integer types are required to be promoted by the ABI.
6292 if (Ty->isPromotableIntegerType())
6293 return true;
6294
6295 // 32-bit values must also be promoted.
6296 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6297 switch (BT->getKind()) {
6298 case BuiltinType::Int:
6299 case BuiltinType::UInt:
6300 return true;
6301 default:
6302 return false;
6303 }
6304 return false;
6305}
6306
6307bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006308 return (Ty->isAnyComplexType() ||
6309 Ty->isVectorType() ||
6310 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006311}
6312
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006313bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6314 return (HasVector &&
6315 Ty->isVectorType() &&
6316 getContext().getTypeSize(Ty) <= 128);
6317}
6318
Ulrich Weigand47445072013-05-06 16:26:41 +00006319bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6320 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6321 switch (BT->getKind()) {
6322 case BuiltinType::Float:
6323 case BuiltinType::Double:
6324 return true;
6325 default:
6326 return false;
6327 }
6328
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006329 return false;
6330}
6331
6332QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006333 if (const RecordType *RT = Ty->getAsStructureType()) {
6334 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006335 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006336
6337 // If this is a C++ record, check the bases first.
6338 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006339 for (const auto &I : CXXRD->bases()) {
6340 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006341
6342 // Empty bases don't affect things either way.
6343 if (isEmptyRecord(getContext(), Base, true))
6344 continue;
6345
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006346 if (!Found.isNull())
6347 return Ty;
6348 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006349 }
6350
6351 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006352 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006353 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006354 // Unlike isSingleElementStruct(), empty structure and array fields
6355 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006356 if (getContext().getLangOpts().CPlusPlus &&
6357 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6358 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006359
6360 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006361 // Nested structures still do though.
6362 if (!Found.isNull())
6363 return Ty;
6364 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006365 }
6366
6367 // Unlike isSingleElementStruct(), trailing padding is allowed.
6368 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006369 if (!Found.isNull())
6370 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006371 }
6372
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006373 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006374}
6375
John McCall7f416cc2015-09-08 08:05:57 +00006376Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6377 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006378 // Assume that va_list type is correct; should be pointer to LLVM type:
6379 // struct {
6380 // i64 __gpr;
6381 // i64 __fpr;
6382 // i8 *__overflow_arg_area;
6383 // i8 *__reg_save_area;
6384 // };
6385
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006386 // Every non-vector argument occupies 8 bytes and is passed by preference
6387 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6388 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006389 Ty = getContext().getCanonicalType(Ty);
6390 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006391 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006392 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006393 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006394 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006395 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006396 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006397 CharUnits UnpaddedSize;
6398 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006399 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006400 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6401 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006402 } else {
6403 if (AI.getCoerceToType())
6404 ArgTy = AI.getCoerceToType();
6405 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006406 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006407 UnpaddedSize = TyInfo.first;
6408 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006409 }
John McCall7f416cc2015-09-08 08:05:57 +00006410 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6411 if (IsVector && UnpaddedSize > PaddedSize)
6412 PaddedSize = CharUnits::fromQuantity(16);
6413 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006414
John McCall7f416cc2015-09-08 08:05:57 +00006415 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006416
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006417 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006418 llvm::Value *PaddedSizeV =
6419 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006420
6421 if (IsVector) {
6422 // Work out the address of a vector argument on the stack.
6423 // Vector arguments are always passed in the high bits of a
6424 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006425 Address OverflowArgAreaPtr =
6426 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006427 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006428 Address OverflowArgArea =
6429 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6430 TyInfo.second);
6431 Address MemAddr =
6432 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006433
6434 // Update overflow_arg_area_ptr pointer
6435 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006436 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6437 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006438 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6439
6440 return MemAddr;
6441 }
6442
John McCall7f416cc2015-09-08 08:05:57 +00006443 assert(PaddedSize.getQuantity() == 8);
6444
6445 unsigned MaxRegs, RegCountField, RegSaveIndex;
6446 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006447 if (InFPRs) {
6448 MaxRegs = 4; // Maximum of 4 FPR arguments
6449 RegCountField = 1; // __fpr
6450 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006451 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006452 } else {
6453 MaxRegs = 5; // Maximum of 5 GPR arguments
6454 RegCountField = 0; // __gpr
6455 RegSaveIndex = 2; // save offset for r2
6456 RegPadding = Padding; // values are passed in the low bits of a GPR
6457 }
6458
John McCall7f416cc2015-09-08 08:05:57 +00006459 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6460 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6461 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006462 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006463 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6464 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006465 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006466
6467 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6468 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6469 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6470 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6471
6472 // Emit code to load the value if it was passed in registers.
6473 CGF.EmitBlock(InRegBlock);
6474
6475 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006476 llvm::Value *ScaledRegCount =
6477 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6478 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006479 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6480 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006481 llvm::Value *RegOffset =
6482 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006483 Address RegSaveAreaPtr =
6484 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6485 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006486 llvm::Value *RegSaveArea =
6487 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006488 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6489 "raw_reg_addr"),
6490 PaddedSize);
6491 Address RegAddr =
6492 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006493
6494 // Update the register count
6495 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6496 llvm::Value *NewRegCount =
6497 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6498 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6499 CGF.EmitBranch(ContBlock);
6500
6501 // Emit code to load the value if it was passed in memory.
6502 CGF.EmitBlock(InMemBlock);
6503
6504 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006505 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6506 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6507 Address OverflowArgArea =
6508 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6509 PaddedSize);
6510 Address RawMemAddr =
6511 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6512 Address MemAddr =
6513 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006514
6515 // Update overflow_arg_area_ptr pointer
6516 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006517 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6518 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006519 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6520 CGF.EmitBranch(ContBlock);
6521
6522 // Return the appropriate result.
6523 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006524 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6525 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006526
6527 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006528 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6529 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006530
6531 return ResAddr;
6532}
6533
Ulrich Weigand47445072013-05-06 16:26:41 +00006534ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6535 if (RetTy->isVoidType())
6536 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006537 if (isVectorArgumentType(RetTy))
6538 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006539 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006540 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006541 return (isPromotableIntegerType(RetTy) ?
6542 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6543}
6544
6545ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6546 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006547 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006548 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006549
6550 // Integers and enums are extended to full register width.
6551 if (isPromotableIntegerType(Ty))
6552 return ABIArgInfo::getExtend();
6553
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006554 // Handle vector types and vector-like structure types. Note that
6555 // as opposed to float-like structure types, we do not allow any
6556 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006557 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006558 QualType SingleElementTy = GetSingleElementType(Ty);
6559 if (isVectorArgumentType(SingleElementTy) &&
6560 getContext().getTypeSize(SingleElementTy) == Size)
6561 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6562
6563 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006564 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006565 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006566
6567 // Handle small structures.
6568 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6569 // Structures with flexible arrays have variable length, so really
6570 // fail the size test above.
6571 const RecordDecl *RD = RT->getDecl();
6572 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006573 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006574
6575 // The structure is passed as an unextended integer, a float, or a double.
6576 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006577 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006578 assert(Size == 32 || Size == 64);
6579 if (Size == 32)
6580 PassTy = llvm::Type::getFloatTy(getVMContext());
6581 else
6582 PassTy = llvm::Type::getDoubleTy(getVMContext());
6583 } else
6584 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6585 return ABIArgInfo::getDirect(PassTy);
6586 }
6587
6588 // Non-structure compounds are passed indirectly.
6589 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006590 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006591
Craig Topper8a13c412014-05-21 05:09:00 +00006592 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006593}
6594
6595//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006596// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006597//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006598
6599namespace {
6600
6601class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6602public:
Chris Lattner2b037972010-07-29 02:01:43 +00006603 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6604 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006605 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006606 CodeGen::CodeGenModule &M,
6607 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006608};
6609
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006610}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006611
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006612void MSP430TargetCodeGenInfo::setTargetAttributes(
6613 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6614 ForDefinition_t IsForDefinition) const {
6615 if (!IsForDefinition)
6616 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006617 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006618 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6619 // Handle 'interrupt' attribute:
6620 llvm::Function *F = cast<llvm::Function>(GV);
6621
6622 // Step 1: Set ISR calling convention.
6623 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6624
6625 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006626 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006627
6628 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006629 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006630 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6631 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006632 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006633 }
6634}
6635
Chris Lattner0cf24192010-06-28 20:05:43 +00006636//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006637// MIPS ABI Implementation. This works for both little-endian and
6638// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006639//===----------------------------------------------------------------------===//
6640
John McCall943fae92010-05-27 06:19:26 +00006641namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006642class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006643 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006644 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6645 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006646 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006647 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006648 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006649 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006650public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006651 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006652 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006653 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006654
6655 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006656 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006657 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006658 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6659 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006660 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006661};
6662
John McCall943fae92010-05-27 06:19:26 +00006663class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006664 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006665public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006666 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6667 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006668 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006669
Craig Topper4f12f102014-03-12 06:41:41 +00006670 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006671 return 29;
6672 }
6673
Eric Christopher162c91c2015-06-05 22:03:00 +00006674 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006675 CodeGen::CodeGenModule &CGM,
6676 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006677 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006678 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006679 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006680
6681 if (FD->hasAttr<MipsLongCallAttr>())
6682 Fn->addFnAttr("long-call");
6683 else if (FD->hasAttr<MipsShortCallAttr>())
6684 Fn->addFnAttr("short-call");
6685
6686 // Other attributes do not have a meaning for declarations.
6687 if (!IsForDefinition)
6688 return;
6689
Reed Kotler3d5966f2013-03-13 20:40:30 +00006690 if (FD->hasAttr<Mips16Attr>()) {
6691 Fn->addFnAttr("mips16");
6692 }
6693 else if (FD->hasAttr<NoMips16Attr>()) {
6694 Fn->addFnAttr("nomips16");
6695 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006696
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006697 if (FD->hasAttr<MicroMipsAttr>())
6698 Fn->addFnAttr("micromips");
6699 else if (FD->hasAttr<NoMicroMipsAttr>())
6700 Fn->addFnAttr("nomicromips");
6701
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006702 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6703 if (!Attr)
6704 return;
6705
6706 const char *Kind;
6707 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006708 case MipsInterruptAttr::eic: Kind = "eic"; break;
6709 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6710 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6711 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6712 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6713 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6714 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6715 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6716 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6717 }
6718
6719 Fn->addFnAttr("interrupt", Kind);
6720
Reed Kotler373feca2013-01-16 17:10:28 +00006721 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006722
John McCall943fae92010-05-27 06:19:26 +00006723 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006724 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006725
Craig Topper4f12f102014-03-12 06:41:41 +00006726 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006727 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006728 }
John McCall943fae92010-05-27 06:19:26 +00006729};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006730}
John McCall943fae92010-05-27 06:19:26 +00006731
Eric Christopher7565e0d2015-05-29 23:09:49 +00006732void MipsABIInfo::CoerceToIntArgs(
6733 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006734 llvm::IntegerType *IntTy =
6735 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006736
6737 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6738 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6739 ArgList.push_back(IntTy);
6740
6741 // If necessary, add one more integer type to ArgList.
6742 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6743
6744 if (R)
6745 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006746}
6747
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006748// In N32/64, an aligned double precision floating point field is passed in
6749// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006750llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006751 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6752
6753 if (IsO32) {
6754 CoerceToIntArgs(TySize, ArgList);
6755 return llvm::StructType::get(getVMContext(), ArgList);
6756 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006757
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006758 if (Ty->isComplexType())
6759 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006760
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006761 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006762
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006763 // Unions/vectors are passed in integer registers.
6764 if (!RT || !RT->isStructureOrClassType()) {
6765 CoerceToIntArgs(TySize, ArgList);
6766 return llvm::StructType::get(getVMContext(), ArgList);
6767 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006768
6769 const RecordDecl *RD = RT->getDecl();
6770 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006771 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006772
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006773 uint64_t LastOffset = 0;
6774 unsigned idx = 0;
6775 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6776
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006777 // Iterate over fields in the struct/class and check if there are any aligned
6778 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006779 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6780 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006781 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006782 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6783
6784 if (!BT || BT->getKind() != BuiltinType::Double)
6785 continue;
6786
6787 uint64_t Offset = Layout.getFieldOffset(idx);
6788 if (Offset % 64) // Ignore doubles that are not aligned.
6789 continue;
6790
6791 // Add ((Offset - LastOffset) / 64) args of type i64.
6792 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6793 ArgList.push_back(I64);
6794
6795 // Add double type.
6796 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6797 LastOffset = Offset + 64;
6798 }
6799
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006800 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6801 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006802
6803 return llvm::StructType::get(getVMContext(), ArgList);
6804}
6805
Akira Hatanakaddd66342013-10-29 18:41:15 +00006806llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6807 uint64_t Offset) const {
6808 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006809 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006810
Akira Hatanakaddd66342013-10-29 18:41:15 +00006811 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006812}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006813
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006814ABIArgInfo
6815MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006816 Ty = useFirstFieldIfTransparentUnion(Ty);
6817
Akira Hatanaka1632af62012-01-09 19:31:25 +00006818 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006819 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006820 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006821
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006822 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6823 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006824 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6825 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006826
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006827 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006828 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006829 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006830 return ABIArgInfo::getIgnore();
6831
Mark Lacey3825e832013-10-06 01:33:34 +00006832 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006833 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006834 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006835 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006836
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006837 // If we have reached here, aggregates are passed directly by coercing to
6838 // another structure type. Padding is inserted if the offset of the
6839 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006840 ABIArgInfo ArgInfo =
6841 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6842 getPaddingType(OrigOffset, CurrOffset));
6843 ArgInfo.setInReg(true);
6844 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006845 }
6846
6847 // Treat an enum type as its underlying type.
6848 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6849 Ty = EnumTy->getDecl()->getIntegerType();
6850
Daniel Sanders5b445b32014-10-24 14:42:42 +00006851 // All integral types are promoted to the GPR width.
6852 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006853 return ABIArgInfo::getExtend();
6854
Akira Hatanakaddd66342013-10-29 18:41:15 +00006855 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006856 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006857}
6858
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006859llvm::Type*
6860MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006861 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006862 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006863
Akira Hatanakab6f74432012-02-09 18:49:26 +00006864 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006865 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006866 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6867 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006868
Akira Hatanakab6f74432012-02-09 18:49:26 +00006869 // N32/64 returns struct/classes in floating point registers if the
6870 // following conditions are met:
6871 // 1. The size of the struct/class is no larger than 128-bit.
6872 // 2. The struct/class has one or two fields all of which are floating
6873 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006874 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006875 //
6876 // Any other composite results are returned in integer registers.
6877 //
6878 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6879 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6880 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006881 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006882
Akira Hatanakab6f74432012-02-09 18:49:26 +00006883 if (!BT || !BT->isFloatingPoint())
6884 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006885
David Blaikie2d7c57e2012-04-30 02:36:29 +00006886 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006887 }
6888
6889 if (b == e)
6890 return llvm::StructType::get(getVMContext(), RTList,
6891 RD->hasAttr<PackedAttr>());
6892
6893 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006894 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006895 }
6896
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006897 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006898 return llvm::StructType::get(getVMContext(), RTList);
6899}
6900
Akira Hatanakab579fe52011-06-02 00:09:17 +00006901ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006902 uint64_t Size = getContext().getTypeSize(RetTy);
6903
Daniel Sandersed39f582014-09-04 13:28:14 +00006904 if (RetTy->isVoidType())
6905 return ABIArgInfo::getIgnore();
6906
6907 // O32 doesn't treat zero-sized structs differently from other structs.
6908 // However, N32/N64 ignores zero sized return values.
6909 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006910 return ABIArgInfo::getIgnore();
6911
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006912 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006913 if (Size <= 128) {
6914 if (RetTy->isAnyComplexType())
6915 return ABIArgInfo::getDirect();
6916
Daniel Sanderse5018b62014-09-04 15:05:39 +00006917 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006918 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006919 if (!IsO32 ||
6920 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6921 ABIArgInfo ArgInfo =
6922 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6923 ArgInfo.setInReg(true);
6924 return ArgInfo;
6925 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006926 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006927
John McCall7f416cc2015-09-08 08:05:57 +00006928 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006929 }
6930
6931 // Treat an enum type as its underlying type.
6932 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6933 RetTy = EnumTy->getDecl()->getIntegerType();
6934
6935 return (RetTy->isPromotableIntegerType() ?
6936 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6937}
6938
6939void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006940 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006941 if (!getCXXABI().classifyReturnType(FI))
6942 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006943
Eric Christopher7565e0d2015-05-29 23:09:49 +00006944 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006945 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006946
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006947 for (auto &I : FI.arguments())
6948 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006949}
6950
John McCall7f416cc2015-09-08 08:05:57 +00006951Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6952 QualType OrigTy) const {
6953 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006954
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006955 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6956 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006957 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006958 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006959 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006960 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006961 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006962 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006963 DidPromote = true;
6964 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6965 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006966 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006967
John McCall7f416cc2015-09-08 08:05:57 +00006968 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006969
John McCall7f416cc2015-09-08 08:05:57 +00006970 // The alignment of things in the argument area is never larger than
6971 // StackAlignInBytes.
6972 TyInfo.second =
6973 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6974
6975 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6976 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6977
6978 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6979 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6980
6981
6982 // If there was a promotion, "unpromote" into a temporary.
6983 // TODO: can we just use a pointer into a subset of the original slot?
6984 if (DidPromote) {
6985 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6986 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6987
6988 // Truncate down to the right width.
6989 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6990 : CGF.IntPtrTy);
6991 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6992 if (OrigTy->isPointerType())
6993 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6994
6995 CGF.Builder.CreateStore(V, Temp);
6996 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006997 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006998
John McCall7f416cc2015-09-08 08:05:57 +00006999 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00007000}
7001
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007002bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
7003 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007004
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007005 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7006 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7007 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00007008
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00007009 return false;
7010}
7011
John McCall943fae92010-05-27 06:19:26 +00007012bool
7013MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7014 llvm::Value *Address) const {
7015 // This information comes from gcc's implementation, which seems to
7016 // as canonical as it gets.
7017
John McCall943fae92010-05-27 06:19:26 +00007018 // Everything on MIPS is 4 bytes. Double-precision FP registers
7019 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007020 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007021
7022 // 0-31 are the general purpose registers, $0 - $31.
7023 // 32-63 are the floating-point registers, $f0 - $f31.
7024 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7025 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007026 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007027
7028 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7029 // They are one bit wide and ignored here.
7030
7031 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7032 // (coprocessor 1 is the FP unit)
7033 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7034 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7035 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007036 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007037 return false;
7038}
7039
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007040//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007041// AVR ABI Implementation.
7042//===----------------------------------------------------------------------===//
7043
7044namespace {
7045class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7046public:
7047 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7048 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7049
7050 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007051 CodeGen::CodeGenModule &CGM,
7052 ForDefinition_t IsForDefinition) const override {
7053 if (!IsForDefinition)
7054 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007055 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7056 if (!FD) return;
7057 auto *Fn = cast<llvm::Function>(GV);
7058
7059 if (FD->getAttr<AVRInterruptAttr>())
7060 Fn->addFnAttr("interrupt");
7061
7062 if (FD->getAttr<AVRSignalAttr>())
7063 Fn->addFnAttr("signal");
7064 }
7065};
7066}
7067
7068//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007069// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007070// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007071// handling.
7072//===----------------------------------------------------------------------===//
7073
7074namespace {
7075
7076class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7077public:
7078 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7079 : DefaultTargetCodeGenInfo(CGT) {}
7080
Eric Christopher162c91c2015-06-05 22:03:00 +00007081 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007082 CodeGen::CodeGenModule &M,
7083 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007084};
7085
Eric Christopher162c91c2015-06-05 22:03:00 +00007086void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007087 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7088 ForDefinition_t IsForDefinition) const {
7089 if (!IsForDefinition)
7090 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007091 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007092 if (!FD) return;
7093
7094 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007095
David Blaikiebbafb8a2012-03-11 07:00:24 +00007096 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007097 if (FD->hasAttr<OpenCLKernelAttr>()) {
7098 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007099 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007100 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7101 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007102 // Convert the reqd_work_group_size() attributes to metadata.
7103 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007104 llvm::NamedMDNode *OpenCLMetadata =
7105 M.getModule().getOrInsertNamedMetadata(
7106 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007107
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007108 SmallVector<llvm::Metadata *, 5> Operands;
7109 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007110
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007111 Operands.push_back(
7112 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7113 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7114 Operands.push_back(
7115 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7116 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7117 Operands.push_back(
7118 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7119 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007120
Eric Christopher7565e0d2015-05-29 23:09:49 +00007121 // Add a boolean constant operand for "required" (true) or "hint"
7122 // (false) for implementing the work_group_size_hint attr later.
7123 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007124 Operands.push_back(
7125 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007126 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7127 }
7128 }
7129 }
7130}
7131
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007132}
John McCall943fae92010-05-27 06:19:26 +00007133
Tony Linthicum76329bf2011-12-12 21:14:55 +00007134//===----------------------------------------------------------------------===//
7135// Hexagon ABI Implementation
7136//===----------------------------------------------------------------------===//
7137
7138namespace {
7139
7140class HexagonABIInfo : public ABIInfo {
7141
7142
7143public:
7144 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7145
7146private:
7147
7148 ABIArgInfo classifyReturnType(QualType RetTy) const;
7149 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7150
Craig Topper4f12f102014-03-12 06:41:41 +00007151 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007152
John McCall7f416cc2015-09-08 08:05:57 +00007153 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7154 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007155};
7156
7157class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7158public:
7159 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7160 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7161
Craig Topper4f12f102014-03-12 06:41:41 +00007162 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007163 return 29;
7164 }
7165};
7166
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007167}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007168
7169void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007170 if (!getCXXABI().classifyReturnType(FI))
7171 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007172 for (auto &I : FI.arguments())
7173 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007174}
7175
7176ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7177 if (!isAggregateTypeForABI(Ty)) {
7178 // Treat an enum type as its underlying type.
7179 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7180 Ty = EnumTy->getDecl()->getIntegerType();
7181
7182 return (Ty->isPromotableIntegerType() ?
7183 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7184 }
7185
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007186 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7187 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7188
Tony Linthicum76329bf2011-12-12 21:14:55 +00007189 // Ignore empty records.
7190 if (isEmptyRecord(getContext(), Ty, true))
7191 return ABIArgInfo::getIgnore();
7192
Tony Linthicum76329bf2011-12-12 21:14:55 +00007193 uint64_t Size = getContext().getTypeSize(Ty);
7194 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007195 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007196 // Pass in the smallest viable integer type.
7197 else if (Size > 32)
7198 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7199 else if (Size > 16)
7200 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7201 else if (Size > 8)
7202 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7203 else
7204 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7205}
7206
7207ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7208 if (RetTy->isVoidType())
7209 return ABIArgInfo::getIgnore();
7210
7211 // Large vector types should be returned via memory.
7212 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007213 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007214
7215 if (!isAggregateTypeForABI(RetTy)) {
7216 // Treat an enum type as its underlying type.
7217 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7218 RetTy = EnumTy->getDecl()->getIntegerType();
7219
7220 return (RetTy->isPromotableIntegerType() ?
7221 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7222 }
7223
Tony Linthicum76329bf2011-12-12 21:14:55 +00007224 if (isEmptyRecord(getContext(), RetTy, true))
7225 return ABIArgInfo::getIgnore();
7226
7227 // Aggregates <= 8 bytes are returned in r0; other aggregates
7228 // are returned indirectly.
7229 uint64_t Size = getContext().getTypeSize(RetTy);
7230 if (Size <= 64) {
7231 // Return in the smallest viable integer type.
7232 if (Size <= 8)
7233 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7234 if (Size <= 16)
7235 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7236 if (Size <= 32)
7237 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7238 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7239 }
7240
John McCall7f416cc2015-09-08 08:05:57 +00007241 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007242}
7243
John McCall7f416cc2015-09-08 08:05:57 +00007244Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7245 QualType Ty) const {
7246 // FIXME: Someone needs to audit that this handle alignment correctly.
7247 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7248 getContext().getTypeInfoInChars(Ty),
7249 CharUnits::fromQuantity(4),
7250 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007251}
7252
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007253//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007254// Lanai ABI Implementation
7255//===----------------------------------------------------------------------===//
7256
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007257namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007258class LanaiABIInfo : public DefaultABIInfo {
7259public:
7260 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7261
7262 bool shouldUseInReg(QualType Ty, CCState &State) const;
7263
7264 void computeInfo(CGFunctionInfo &FI) const override {
7265 CCState State(FI.getCallingConvention());
7266 // Lanai uses 4 registers to pass arguments unless the function has the
7267 // regparm attribute set.
7268 if (FI.getHasRegParm()) {
7269 State.FreeRegs = FI.getRegParm();
7270 } else {
7271 State.FreeRegs = 4;
7272 }
7273
7274 if (!getCXXABI().classifyReturnType(FI))
7275 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7276 for (auto &I : FI.arguments())
7277 I.info = classifyArgumentType(I.type, State);
7278 }
7279
Jacques Pienaare74d9132016-04-26 00:09:29 +00007280 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007281 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7282};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007283} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007284
7285bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7286 unsigned Size = getContext().getTypeSize(Ty);
7287 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7288
7289 if (SizeInRegs == 0)
7290 return false;
7291
7292 if (SizeInRegs > State.FreeRegs) {
7293 State.FreeRegs = 0;
7294 return false;
7295 }
7296
7297 State.FreeRegs -= SizeInRegs;
7298
7299 return true;
7300}
7301
Jacques Pienaare74d9132016-04-26 00:09:29 +00007302ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7303 CCState &State) const {
7304 if (!ByVal) {
7305 if (State.FreeRegs) {
7306 --State.FreeRegs; // Non-byval indirects just use one pointer.
7307 return getNaturalAlignIndirectInReg(Ty);
7308 }
7309 return getNaturalAlignIndirect(Ty, false);
7310 }
7311
7312 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007313 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007314 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7315 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7316 /*Realign=*/TypeAlign >
7317 MinABIStackAlignInBytes);
7318}
7319
Jacques Pienaard964cc22016-03-28 21:02:54 +00007320ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7321 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007322 // Check with the C++ ABI first.
7323 const RecordType *RT = Ty->getAs<RecordType>();
7324 if (RT) {
7325 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7326 if (RAA == CGCXXABI::RAA_Indirect) {
7327 return getIndirectResult(Ty, /*ByVal=*/false, State);
7328 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7329 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7330 }
7331 }
7332
7333 if (isAggregateTypeForABI(Ty)) {
7334 // Structures with flexible arrays are always indirect.
7335 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7336 return getIndirectResult(Ty, /*ByVal=*/true, State);
7337
7338 // Ignore empty structs/unions.
7339 if (isEmptyRecord(getContext(), Ty, true))
7340 return ABIArgInfo::getIgnore();
7341
7342 llvm::LLVMContext &LLVMContext = getVMContext();
7343 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7344 if (SizeInRegs <= State.FreeRegs) {
7345 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7346 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7347 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7348 State.FreeRegs -= SizeInRegs;
7349 return ABIArgInfo::getDirectInReg(Result);
7350 } else {
7351 State.FreeRegs = 0;
7352 }
7353 return getIndirectResult(Ty, true, State);
7354 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007355
7356 // Treat an enum type as its underlying type.
7357 if (const auto *EnumTy = Ty->getAs<EnumType>())
7358 Ty = EnumTy->getDecl()->getIntegerType();
7359
Jacques Pienaare74d9132016-04-26 00:09:29 +00007360 bool InReg = shouldUseInReg(Ty, State);
7361 if (Ty->isPromotableIntegerType()) {
7362 if (InReg)
7363 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007364 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007365 }
7366 if (InReg)
7367 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007368 return ABIArgInfo::getDirect();
7369}
7370
7371namespace {
7372class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7373public:
7374 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7375 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7376};
7377}
7378
7379//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007380// AMDGPU ABI Implementation
7381//===----------------------------------------------------------------------===//
7382
7383namespace {
7384
Matt Arsenault88d7da02016-08-22 19:25:59 +00007385class AMDGPUABIInfo final : public DefaultABIInfo {
Matt Arsenault88d7da02016-08-22 19:25:59 +00007386private:
Matt Arsenault3fe73952017-08-09 21:44:58 +00007387 static const unsigned MaxNumRegsForArgsRet = 16;
7388
Matt Arsenault3fe73952017-08-09 21:44:58 +00007389 unsigned numRegsForType(QualType Ty) const;
7390
7391 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7392 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7393 uint64_t Members) const override;
7394
7395public:
7396 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7397 DefaultABIInfo(CGT) {}
7398
7399 ABIArgInfo classifyReturnType(QualType RetTy) const;
7400 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7401 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
Matt Arsenault88d7da02016-08-22 19:25:59 +00007402
7403 void computeInfo(CGFunctionInfo &FI) const override;
7404};
7405
Matt Arsenault3fe73952017-08-09 21:44:58 +00007406bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7407 return true;
7408}
7409
7410bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7411 const Type *Base, uint64_t Members) const {
7412 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7413
7414 // Homogeneous Aggregates may occupy at most 16 registers.
7415 return Members * NumRegs <= MaxNumRegsForArgsRet;
7416}
7417
Matt Arsenault3fe73952017-08-09 21:44:58 +00007418/// Estimate number of registers the type will use when passed in registers.
7419unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7420 unsigned NumRegs = 0;
7421
7422 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7423 // Compute from the number of elements. The reported size is based on the
7424 // in-memory size, which includes the padding 4th element for 3-vectors.
7425 QualType EltTy = VT->getElementType();
7426 unsigned EltSize = getContext().getTypeSize(EltTy);
7427
7428 // 16-bit element vectors should be passed as packed.
7429 if (EltSize == 16)
7430 return (VT->getNumElements() + 1) / 2;
7431
7432 unsigned EltNumRegs = (EltSize + 31) / 32;
7433 return EltNumRegs * VT->getNumElements();
7434 }
7435
7436 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7437 const RecordDecl *RD = RT->getDecl();
7438 assert(!RD->hasFlexibleArrayMember());
7439
7440 for (const FieldDecl *Field : RD->fields()) {
7441 QualType FieldTy = Field->getType();
7442 NumRegs += numRegsForType(FieldTy);
7443 }
7444
7445 return NumRegs;
7446 }
7447
7448 return (getContext().getTypeSize(Ty) + 31) / 32;
7449}
7450
Matt Arsenault88d7da02016-08-22 19:25:59 +00007451void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
Matt Arsenault3fe73952017-08-09 21:44:58 +00007452 llvm::CallingConv::ID CC = FI.getCallingConvention();
7453
Matt Arsenault88d7da02016-08-22 19:25:59 +00007454 if (!getCXXABI().classifyReturnType(FI))
7455 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7456
Matt Arsenault3fe73952017-08-09 21:44:58 +00007457 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7458 for (auto &Arg : FI.arguments()) {
7459 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7460 Arg.info = classifyKernelArgumentType(Arg.type);
7461 } else {
7462 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7463 }
7464 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007465}
7466
Matt Arsenault3fe73952017-08-09 21:44:58 +00007467ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7468 if (isAggregateTypeForABI(RetTy)) {
7469 // Records with non-trivial destructors/copy-constructors should not be
7470 // returned by value.
7471 if (!getRecordArgABI(RetTy, getCXXABI())) {
7472 // Ignore empty structs/unions.
7473 if (isEmptyRecord(getContext(), RetTy, true))
7474 return ABIArgInfo::getIgnore();
7475
7476 // Lower single-element structs to just return a regular value.
7477 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7478 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7479
7480 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7481 const RecordDecl *RD = RT->getDecl();
7482 if (RD->hasFlexibleArrayMember())
7483 return DefaultABIInfo::classifyReturnType(RetTy);
7484 }
7485
7486 // Pack aggregates <= 4 bytes into single VGPR or pair.
7487 uint64_t Size = getContext().getTypeSize(RetTy);
7488 if (Size <= 16)
7489 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7490
7491 if (Size <= 32)
7492 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7493
7494 if (Size <= 64) {
7495 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7496 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7497 }
7498
7499 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7500 return ABIArgInfo::getDirect();
7501 }
Matt Arsenault88d7da02016-08-22 19:25:59 +00007502 }
7503
Matt Arsenault3fe73952017-08-09 21:44:58 +00007504 // Otherwise just do the default thing.
7505 return DefaultABIInfo::classifyReturnType(RetTy);
7506}
7507
7508/// For kernels all parameters are really passed in a special buffer. It doesn't
7509/// make sense to pass anything byval, so everything must be direct.
7510ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7511 Ty = useFirstFieldIfTransparentUnion(Ty);
7512
7513 // TODO: Can we omit empty structs?
7514
Matt Arsenault88d7da02016-08-22 19:25:59 +00007515 // Coerce single element structs to its element.
Matt Arsenault3fe73952017-08-09 21:44:58 +00007516 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7517 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Matt Arsenault88d7da02016-08-22 19:25:59 +00007518
7519 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7520 // individual elements, which confuses the Clover OpenCL backend; therefore we
7521 // have to set it to false here. Other args of getDirect() are just defaults.
7522 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7523}
7524
Matt Arsenault3fe73952017-08-09 21:44:58 +00007525ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7526 unsigned &NumRegsLeft) const {
7527 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7528
7529 Ty = useFirstFieldIfTransparentUnion(Ty);
7530
7531 if (isAggregateTypeForABI(Ty)) {
7532 // Records with non-trivial destructors/copy-constructors should not be
7533 // passed by value.
7534 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7535 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7536
7537 // Ignore empty structs/unions.
7538 if (isEmptyRecord(getContext(), Ty, true))
7539 return ABIArgInfo::getIgnore();
7540
7541 // Lower single-element structs to just pass a regular value. TODO: We
7542 // could do reasonable-size multiple-element structs too, using getExpand(),
7543 // though watch out for things like bitfields.
7544 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7545 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7546
7547 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7548 const RecordDecl *RD = RT->getDecl();
7549 if (RD->hasFlexibleArrayMember())
7550 return DefaultABIInfo::classifyArgumentType(Ty);
7551 }
7552
7553 // Pack aggregates <= 8 bytes into single VGPR or pair.
7554 uint64_t Size = getContext().getTypeSize(Ty);
7555 if (Size <= 64) {
7556 unsigned NumRegs = (Size + 31) / 32;
7557 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7558
7559 if (Size <= 16)
7560 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7561
7562 if (Size <= 32)
7563 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7564
7565 // XXX: Should this be i64 instead, and should the limit increase?
7566 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7567 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7568 }
7569
7570 if (NumRegsLeft > 0) {
7571 unsigned NumRegs = numRegsForType(Ty);
7572 if (NumRegsLeft >= NumRegs) {
7573 NumRegsLeft -= NumRegs;
7574 return ABIArgInfo::getDirect();
7575 }
7576 }
7577 }
7578
7579 // Otherwise just do the default thing.
7580 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7581 if (!ArgInfo.isIndirect()) {
7582 unsigned NumRegs = numRegsForType(Ty);
7583 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7584 }
7585
7586 return ArgInfo;
7587}
7588
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007589class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7590public:
7591 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007592 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007593 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007594 CodeGen::CodeGenModule &M,
7595 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007596 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007597
Yaxun Liu402804b2016-12-15 08:09:08 +00007598 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7599 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007600
7601 unsigned getASTAllocaAddressSpace() const override {
7602 return LangAS::FirstTargetAddressSpace +
7603 getABIInfo().getDataLayout().getAllocaAddrSpace();
7604 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00007605 unsigned getGlobalVarAddressSpace(CodeGenModule &CGM,
7606 const VarDecl *D) const override;
Yaxun Liu39195062017-08-04 18:16:31 +00007607 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7608 llvm::LLVMContext &C) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007609};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007610}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007611
Eric Christopher162c91c2015-06-05 22:03:00 +00007612void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007613 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7614 ForDefinition_t IsForDefinition) const {
7615 if (!IsForDefinition)
7616 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007617 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007618 if (!FD)
7619 return;
7620
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007621 llvm::Function *F = cast<llvm::Function>(GV);
7622
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007623 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7624 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7625 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7626 if (ReqdWGS || FlatWGS) {
7627 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7628 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7629 if (ReqdWGS && Min == 0 && Max == 0)
7630 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007631
7632 if (Min != 0) {
7633 assert(Min <= Max && "Min must be less than or equal Max");
7634
7635 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7636 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7637 } else
7638 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007639 }
7640
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007641 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7642 unsigned Min = Attr->getMin();
7643 unsigned Max = Attr->getMax();
7644
7645 if (Min != 0) {
7646 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7647
7648 std::string AttrVal = llvm::utostr(Min);
7649 if (Max != 0)
7650 AttrVal = AttrVal + "," + llvm::utostr(Max);
7651 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7652 } else
7653 assert(Max == 0 && "Max must be zero");
7654 }
7655
7656 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007657 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007658
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007659 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007660 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7661 }
7662
7663 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7664 uint32_t NumVGPR = Attr->getNumVGPR();
7665
7666 if (NumVGPR != 0)
7667 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007668 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007669}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007670
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007671unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7672 return llvm::CallingConv::AMDGPU_KERNEL;
7673}
7674
Yaxun Liu402804b2016-12-15 08:09:08 +00007675// Currently LLVM assumes null pointers always have value 0,
7676// which results in incorrectly transformed IR. Therefore, instead of
7677// emitting null pointers in private and local address spaces, a null
7678// pointer in generic address space is emitted which is casted to a
7679// pointer in local or private address space.
7680llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7681 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7682 QualType QT) const {
7683 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7684 return llvm::ConstantPointerNull::get(PT);
7685
7686 auto &Ctx = CGM.getContext();
7687 auto NPT = llvm::PointerType::get(PT->getElementType(),
7688 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7689 return llvm::ConstantExpr::getAddrSpaceCast(
7690 llvm::ConstantPointerNull::get(NPT), PT);
7691}
7692
Yaxun Liucbf647c2017-07-08 13:24:52 +00007693unsigned
7694AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7695 const VarDecl *D) const {
7696 assert(!CGM.getLangOpts().OpenCL &&
7697 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7698 "Address space agnostic languages only");
7699 unsigned DefaultGlobalAS =
7700 LangAS::FirstTargetAddressSpace +
7701 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
7702 if (!D)
7703 return DefaultGlobalAS;
7704
7705 unsigned AddrSpace = D->getType().getAddressSpace();
7706 assert(AddrSpace == LangAS::Default ||
7707 AddrSpace >= LangAS::FirstTargetAddressSpace);
7708 if (AddrSpace != LangAS::Default)
7709 return AddrSpace;
7710
7711 if (CGM.isTypeConstant(D->getType(), false)) {
7712 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7713 return ConstAS.getValue();
7714 }
7715 return DefaultGlobalAS;
7716}
7717
Yaxun Liu39195062017-08-04 18:16:31 +00007718llvm::SyncScope::ID
7719AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7720 llvm::LLVMContext &C) const {
7721 StringRef Name;
7722 switch (S) {
7723 case SyncScope::OpenCLWorkGroup:
7724 Name = "workgroup";
7725 break;
7726 case SyncScope::OpenCLDevice:
7727 Name = "agent";
7728 break;
7729 case SyncScope::OpenCLAllSVMDevices:
7730 Name = "";
7731 break;
7732 case SyncScope::OpenCLSubGroup:
7733 Name = "subgroup";
7734 }
7735 return C.getOrInsertSyncScopeID(Name);
7736}
7737
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007738//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007739// SPARC v8 ABI Implementation.
7740// Based on the SPARC Compliance Definition version 2.4.1.
7741//
7742// Ensures that complex values are passed in registers.
7743//
7744namespace {
7745class SparcV8ABIInfo : public DefaultABIInfo {
7746public:
7747 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7748
7749private:
7750 ABIArgInfo classifyReturnType(QualType RetTy) const;
7751 void computeInfo(CGFunctionInfo &FI) const override;
7752};
7753} // end anonymous namespace
7754
7755
7756ABIArgInfo
7757SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7758 if (Ty->isAnyComplexType()) {
7759 return ABIArgInfo::getDirect();
7760 }
7761 else {
7762 return DefaultABIInfo::classifyReturnType(Ty);
7763 }
7764}
7765
7766void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7767
7768 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7769 for (auto &Arg : FI.arguments())
7770 Arg.info = classifyArgumentType(Arg.type);
7771}
7772
7773namespace {
7774class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7775public:
7776 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7777 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7778};
7779} // end anonymous namespace
7780
7781//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007782// SPARC v9 ABI Implementation.
7783// Based on the SPARC Compliance Definition version 2.4.1.
7784//
7785// Function arguments a mapped to a nominal "parameter array" and promoted to
7786// registers depending on their type. Each argument occupies 8 or 16 bytes in
7787// the array, structs larger than 16 bytes are passed indirectly.
7788//
7789// One case requires special care:
7790//
7791// struct mixed {
7792// int i;
7793// float f;
7794// };
7795//
7796// When a struct mixed is passed by value, it only occupies 8 bytes in the
7797// parameter array, but the int is passed in an integer register, and the float
7798// is passed in a floating point register. This is represented as two arguments
7799// with the LLVM IR inreg attribute:
7800//
7801// declare void f(i32 inreg %i, float inreg %f)
7802//
7803// The code generator will only allocate 4 bytes from the parameter array for
7804// the inreg arguments. All other arguments are allocated a multiple of 8
7805// bytes.
7806//
7807namespace {
7808class SparcV9ABIInfo : public ABIInfo {
7809public:
7810 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7811
7812private:
7813 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007814 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007815 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7816 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007817
7818 // Coercion type builder for structs passed in registers. The coercion type
7819 // serves two purposes:
7820 //
7821 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7822 // in registers.
7823 // 2. Expose aligned floating point elements as first-level elements, so the
7824 // code generator knows to pass them in floating point registers.
7825 //
7826 // We also compute the InReg flag which indicates that the struct contains
7827 // aligned 32-bit floats.
7828 //
7829 struct CoerceBuilder {
7830 llvm::LLVMContext &Context;
7831 const llvm::DataLayout &DL;
7832 SmallVector<llvm::Type*, 8> Elems;
7833 uint64_t Size;
7834 bool InReg;
7835
7836 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7837 : Context(c), DL(dl), Size(0), InReg(false) {}
7838
7839 // Pad Elems with integers until Size is ToSize.
7840 void pad(uint64_t ToSize) {
7841 assert(ToSize >= Size && "Cannot remove elements");
7842 if (ToSize == Size)
7843 return;
7844
7845 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007846 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007847 if (Aligned > Size && Aligned <= ToSize) {
7848 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7849 Size = Aligned;
7850 }
7851
7852 // Add whole 64-bit words.
7853 while (Size + 64 <= ToSize) {
7854 Elems.push_back(llvm::Type::getInt64Ty(Context));
7855 Size += 64;
7856 }
7857
7858 // Final in-word padding.
7859 if (Size < ToSize) {
7860 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7861 Size = ToSize;
7862 }
7863 }
7864
7865 // Add a floating point element at Offset.
7866 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7867 // Unaligned floats are treated as integers.
7868 if (Offset % Bits)
7869 return;
7870 // The InReg flag is only required if there are any floats < 64 bits.
7871 if (Bits < 64)
7872 InReg = true;
7873 pad(Offset);
7874 Elems.push_back(Ty);
7875 Size = Offset + Bits;
7876 }
7877
7878 // Add a struct type to the coercion type, starting at Offset (in bits).
7879 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7880 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7881 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7882 llvm::Type *ElemTy = StrTy->getElementType(i);
7883 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7884 switch (ElemTy->getTypeID()) {
7885 case llvm::Type::StructTyID:
7886 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7887 break;
7888 case llvm::Type::FloatTyID:
7889 addFloat(ElemOffset, ElemTy, 32);
7890 break;
7891 case llvm::Type::DoubleTyID:
7892 addFloat(ElemOffset, ElemTy, 64);
7893 break;
7894 case llvm::Type::FP128TyID:
7895 addFloat(ElemOffset, ElemTy, 128);
7896 break;
7897 case llvm::Type::PointerTyID:
7898 if (ElemOffset % 64 == 0) {
7899 pad(ElemOffset);
7900 Elems.push_back(ElemTy);
7901 Size += 64;
7902 }
7903 break;
7904 default:
7905 break;
7906 }
7907 }
7908 }
7909
7910 // Check if Ty is a usable substitute for the coercion type.
7911 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007912 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007913 }
7914
7915 // Get the coercion type as a literal struct type.
7916 llvm::Type *getType() const {
7917 if (Elems.size() == 1)
7918 return Elems.front();
7919 else
7920 return llvm::StructType::get(Context, Elems);
7921 }
7922 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007923};
7924} // end anonymous namespace
7925
7926ABIArgInfo
7927SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7928 if (Ty->isVoidType())
7929 return ABIArgInfo::getIgnore();
7930
7931 uint64_t Size = getContext().getTypeSize(Ty);
7932
7933 // Anything too big to fit in registers is passed with an explicit indirect
7934 // pointer / sret pointer.
7935 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007936 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007937
7938 // Treat an enum type as its underlying type.
7939 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7940 Ty = EnumTy->getDecl()->getIntegerType();
7941
7942 // Integer types smaller than a register are extended.
7943 if (Size < 64 && Ty->isIntegerType())
7944 return ABIArgInfo::getExtend();
7945
7946 // Other non-aggregates go in registers.
7947 if (!isAggregateTypeForABI(Ty))
7948 return ABIArgInfo::getDirect();
7949
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007950 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7951 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7952 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007953 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007954
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007955 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007956 // Build a coercion type from the LLVM struct type.
7957 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7958 if (!StrTy)
7959 return ABIArgInfo::getDirect();
7960
7961 CoerceBuilder CB(getVMContext(), getDataLayout());
7962 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007963 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007964
7965 // Try to use the original type for coercion.
7966 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7967
7968 if (CB.InReg)
7969 return ABIArgInfo::getDirectInReg(CoerceTy);
7970 else
7971 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007972}
7973
John McCall7f416cc2015-09-08 08:05:57 +00007974Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7975 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007976 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7977 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7978 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7979 AI.setCoerceToType(ArgTy);
7980
John McCall7f416cc2015-09-08 08:05:57 +00007981 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007982
John McCall7f416cc2015-09-08 08:05:57 +00007983 CGBuilderTy &Builder = CGF.Builder;
7984 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7985 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7986
7987 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7988
7989 Address ArgAddr = Address::invalid();
7990 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007991 switch (AI.getKind()) {
7992 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007993 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007994 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007995 llvm_unreachable("Unsupported ABI kind for va_arg");
7996
John McCall7f416cc2015-09-08 08:05:57 +00007997 case ABIArgInfo::Extend: {
7998 Stride = SlotSize;
7999 CharUnits Offset = SlotSize - TypeInfo.first;
8000 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008001 break;
John McCall7f416cc2015-09-08 08:05:57 +00008002 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008003
John McCall7f416cc2015-09-08 08:05:57 +00008004 case ABIArgInfo::Direct: {
8005 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00008006 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008007 ArgAddr = Addr;
8008 break;
John McCall7f416cc2015-09-08 08:05:57 +00008009 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008010
8011 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008012 Stride = SlotSize;
8013 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8014 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8015 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008016 break;
8017
8018 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008019 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008020 }
8021
8022 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008023 llvm::Value *NextPtr =
8024 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8025 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00008026
John McCall7f416cc2015-09-08 08:05:57 +00008027 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008028}
8029
8030void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8031 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00008032 for (auto &I : FI.arguments())
8033 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008034}
8035
8036namespace {
8037class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8038public:
8039 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8040 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00008041
Craig Topper4f12f102014-03-12 06:41:41 +00008042 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00008043 return 14;
8044 }
8045
8046 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00008047 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008048};
8049} // end anonymous namespace
8050
Roman Divackyf02c9942014-02-24 18:46:27 +00008051bool
8052SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8053 llvm::Value *Address) const {
8054 // This is calculated from the LLVM and GCC tables and verified
8055 // against gcc output. AFAIK all ABIs use the same encoding.
8056
8057 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8058
8059 llvm::IntegerType *i8 = CGF.Int8Ty;
8060 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8061 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8062
8063 // 0-31: the 8-byte general-purpose registers
8064 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8065
8066 // 32-63: f0-31, the 4-byte floating-point registers
8067 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8068
8069 // Y = 64
8070 // PSR = 65
8071 // WIM = 66
8072 // TBR = 67
8073 // PC = 68
8074 // NPC = 69
8075 // FSR = 70
8076 // CSR = 71
8077 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00008078
Roman Divackyf02c9942014-02-24 18:46:27 +00008079 // 72-87: d0-15, the 8-byte floating-point registers
8080 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8081
8082 return false;
8083}
8084
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008085
Robert Lytton0e076492013-08-13 09:43:10 +00008086//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00008087// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00008088//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00008089
Robert Lytton0e076492013-08-13 09:43:10 +00008090namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008091
8092/// A SmallStringEnc instance is used to build up the TypeString by passing
8093/// it by reference between functions that append to it.
8094typedef llvm::SmallString<128> SmallStringEnc;
8095
8096/// TypeStringCache caches the meta encodings of Types.
8097///
8098/// The reason for caching TypeStrings is two fold:
8099/// 1. To cache a type's encoding for later uses;
8100/// 2. As a means to break recursive member type inclusion.
8101///
8102/// A cache Entry can have a Status of:
8103/// NonRecursive: The type encoding is not recursive;
8104/// Recursive: The type encoding is recursive;
8105/// Incomplete: An incomplete TypeString;
8106/// IncompleteUsed: An incomplete TypeString that has been used in a
8107/// Recursive type encoding.
8108///
8109/// A NonRecursive entry will have all of its sub-members expanded as fully
8110/// as possible. Whilst it may contain types which are recursive, the type
8111/// itself is not recursive and thus its encoding may be safely used whenever
8112/// the type is encountered.
8113///
8114/// A Recursive entry will have all of its sub-members expanded as fully as
8115/// possible. The type itself is recursive and it may contain other types which
8116/// are recursive. The Recursive encoding must not be used during the expansion
8117/// of a recursive type's recursive branch. For simplicity the code uses
8118/// IncompleteCount to reject all usage of Recursive encodings for member types.
8119///
8120/// An Incomplete entry is always a RecordType and only encodes its
8121/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8122/// are placed into the cache during type expansion as a means to identify and
8123/// handle recursive inclusion of types as sub-members. If there is recursion
8124/// the entry becomes IncompleteUsed.
8125///
8126/// During the expansion of a RecordType's members:
8127///
8128/// If the cache contains a NonRecursive encoding for the member type, the
8129/// cached encoding is used;
8130///
8131/// If the cache contains a Recursive encoding for the member type, the
8132/// cached encoding is 'Swapped' out, as it may be incorrect, and...
8133///
8134/// If the member is a RecordType, an Incomplete encoding is placed into the
8135/// cache to break potential recursive inclusion of itself as a sub-member;
8136///
8137/// Once a member RecordType has been expanded, its temporary incomplete
8138/// entry is removed from the cache. If a Recursive encoding was swapped out
8139/// it is swapped back in;
8140///
8141/// If an incomplete entry is used to expand a sub-member, the incomplete
8142/// entry is marked as IncompleteUsed. The cache keeps count of how many
8143/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8144///
8145/// If a member's encoding is found to be a NonRecursive or Recursive viz:
8146/// IncompleteUsedCount==0, the member's encoding is added to the cache.
8147/// Else the member is part of a recursive type and thus the recursion has
8148/// been exited too soon for the encoding to be correct for the member.
8149///
8150class TypeStringCache {
8151 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8152 struct Entry {
8153 std::string Str; // The encoded TypeString for the type.
8154 enum Status State; // Information about the encoding in 'Str'.
8155 std::string Swapped; // A temporary place holder for a Recursive encoding
8156 // during the expansion of RecordType's members.
8157 };
8158 std::map<const IdentifierInfo *, struct Entry> Map;
8159 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8160 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8161public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008162 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00008163 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8164 bool removeIncomplete(const IdentifierInfo *ID);
8165 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8166 bool IsRecursive);
8167 StringRef lookupStr(const IdentifierInfo *ID);
8168};
8169
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008170/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008171/// FieldEncoding is a helper for this ordering process.
8172class FieldEncoding {
8173 bool HasName;
8174 std::string Enc;
8175public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00008176 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008177 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008178 bool operator<(const FieldEncoding &rhs) const {
8179 if (HasName != rhs.HasName) return HasName;
8180 return Enc < rhs.Enc;
8181 }
8182};
8183
Robert Lytton7d1db152013-08-19 09:46:39 +00008184class XCoreABIInfo : public DefaultABIInfo {
8185public:
8186 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00008187 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8188 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00008189};
8190
Robert Lyttond21e2d72014-03-03 13:45:29 +00008191class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008192 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00008193public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00008194 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00008195 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008196 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8197 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008198};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008199
Robert Lytton2d196952013-10-11 10:29:34 +00008200} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008201
James Y Knight29b5f082016-02-24 02:59:33 +00008202// TODO: this implementation is likely now redundant with the default
8203// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008204Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8205 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008206 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008207
Robert Lytton2d196952013-10-11 10:29:34 +00008208 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008209 CharUnits SlotSize = CharUnits::fromQuantity(4);
8210 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008211
Robert Lytton2d196952013-10-11 10:29:34 +00008212 // Handle the argument.
8213 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008214 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008215 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8216 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8217 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008218 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008219
8220 Address Val = Address::invalid();
8221 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008222 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008223 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008224 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008225 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008226 llvm_unreachable("Unsupported ABI kind for va_arg");
8227 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008228 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8229 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008230 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008231 case ABIArgInfo::Extend:
8232 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008233 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8234 ArgSize = CharUnits::fromQuantity(
8235 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008236 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008237 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008238 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008239 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8240 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8241 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008242 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008243 }
Robert Lytton2d196952013-10-11 10:29:34 +00008244
8245 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008246 if (!ArgSize.isZero()) {
8247 llvm::Value *APN =
8248 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8249 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008250 }
John McCall7f416cc2015-09-08 08:05:57 +00008251
Robert Lytton2d196952013-10-11 10:29:34 +00008252 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008253}
Robert Lytton0e076492013-08-13 09:43:10 +00008254
Robert Lytton844aeeb2014-05-02 09:33:20 +00008255/// During the expansion of a RecordType, an incomplete TypeString is placed
8256/// into the cache as a means to identify and break recursion.
8257/// If there is a Recursive encoding in the cache, it is swapped out and will
8258/// be reinserted by removeIncomplete().
8259/// All other types of encoding should have been used rather than arriving here.
8260void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8261 std::string StubEnc) {
8262 if (!ID)
8263 return;
8264 Entry &E = Map[ID];
8265 assert( (E.Str.empty() || E.State == Recursive) &&
8266 "Incorrectly use of addIncomplete");
8267 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8268 E.Swapped.swap(E.Str); // swap out the Recursive
8269 E.Str.swap(StubEnc);
8270 E.State = Incomplete;
8271 ++IncompleteCount;
8272}
8273
8274/// Once the RecordType has been expanded, the temporary incomplete TypeString
8275/// must be removed from the cache.
8276/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8277/// Returns true if the RecordType was defined recursively.
8278bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8279 if (!ID)
8280 return false;
8281 auto I = Map.find(ID);
8282 assert(I != Map.end() && "Entry not present");
8283 Entry &E = I->second;
8284 assert( (E.State == Incomplete ||
8285 E.State == IncompleteUsed) &&
8286 "Entry must be an incomplete type");
8287 bool IsRecursive = false;
8288 if (E.State == IncompleteUsed) {
8289 // We made use of our Incomplete encoding, thus we are recursive.
8290 IsRecursive = true;
8291 --IncompleteUsedCount;
8292 }
8293 if (E.Swapped.empty())
8294 Map.erase(I);
8295 else {
8296 // Swap the Recursive back.
8297 E.Swapped.swap(E.Str);
8298 E.Swapped.clear();
8299 E.State = Recursive;
8300 }
8301 --IncompleteCount;
8302 return IsRecursive;
8303}
8304
8305/// Add the encoded TypeString to the cache only if it is NonRecursive or
8306/// Recursive (viz: all sub-members were expanded as fully as possible).
8307void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8308 bool IsRecursive) {
8309 if (!ID || IncompleteUsedCount)
8310 return; // No key or it is is an incomplete sub-type so don't add.
8311 Entry &E = Map[ID];
8312 if (IsRecursive && !E.Str.empty()) {
8313 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8314 "This is not the same Recursive entry");
8315 // The parent container was not recursive after all, so we could have used
8316 // this Recursive sub-member entry after all, but we assumed the worse when
8317 // we started viz: IncompleteCount!=0.
8318 return;
8319 }
8320 assert(E.Str.empty() && "Entry already present");
8321 E.Str = Str.str();
8322 E.State = IsRecursive? Recursive : NonRecursive;
8323}
8324
8325/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8326/// are recursively expanding a type (IncompleteCount != 0) and the cached
8327/// encoding is Recursive, return an empty StringRef.
8328StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8329 if (!ID)
8330 return StringRef(); // We have no key.
8331 auto I = Map.find(ID);
8332 if (I == Map.end())
8333 return StringRef(); // We have no encoding.
8334 Entry &E = I->second;
8335 if (E.State == Recursive && IncompleteCount)
8336 return StringRef(); // We don't use Recursive encodings for member types.
8337
8338 if (E.State == Incomplete) {
8339 // The incomplete type is being used to break out of recursion.
8340 E.State = IncompleteUsed;
8341 ++IncompleteUsedCount;
8342 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008343 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008344}
8345
8346/// The XCore ABI includes a type information section that communicates symbol
8347/// type information to the linker. The linker uses this information to verify
8348/// safety/correctness of things such as array bound and pointers et al.
8349/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8350/// This type information (TypeString) is emitted into meta data for all global
8351/// symbols: definitions, declarations, functions & variables.
8352///
8353/// The TypeString carries type, qualifier, name, size & value details.
8354/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008355/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008356/// The output is tested by test/CodeGen/xcore-stringtype.c.
8357///
8358static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8359 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8360
8361/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8362void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8363 CodeGen::CodeGenModule &CGM) const {
8364 SmallStringEnc Enc;
8365 if (getTypeString(Enc, D, CGM, TSC)) {
8366 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008367 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8368 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008369 llvm::NamedMDNode *MD =
8370 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8371 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8372 }
8373}
8374
Xiuli Pan972bea82016-03-24 03:57:17 +00008375//===----------------------------------------------------------------------===//
8376// SPIR ABI Implementation
8377//===----------------------------------------------------------------------===//
8378
8379namespace {
8380class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8381public:
8382 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8383 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008384 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008385};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008386
Xiuli Pan972bea82016-03-24 03:57:17 +00008387} // End anonymous namespace.
8388
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008389namespace clang {
8390namespace CodeGen {
8391void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8392 DefaultABIInfo SPIRABI(CGM.getTypes());
8393 SPIRABI.computeInfo(FI);
8394}
8395}
8396}
8397
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008398unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8399 return llvm::CallingConv::SPIR_KERNEL;
8400}
8401
Robert Lytton844aeeb2014-05-02 09:33:20 +00008402static bool appendType(SmallStringEnc &Enc, QualType QType,
8403 const CodeGen::CodeGenModule &CGM,
8404 TypeStringCache &TSC);
8405
8406/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008407/// Builds a SmallVector containing the encoded field types in declaration
8408/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008409static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8410 const RecordDecl *RD,
8411 const CodeGen::CodeGenModule &CGM,
8412 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008413 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008414 SmallStringEnc Enc;
8415 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008416 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008417 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008418 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008419 Enc += "b(";
8420 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008421 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008422 Enc += ':';
8423 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008424 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008425 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008426 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008427 Enc += ')';
8428 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008429 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008430 }
8431 return true;
8432}
8433
8434/// Appends structure and union types to Enc and adds encoding to cache.
8435/// Recursively calls appendType (via extractFieldType) for each field.
8436/// Union types have their fields ordered according to the ABI.
8437static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8438 const CodeGen::CodeGenModule &CGM,
8439 TypeStringCache &TSC, const IdentifierInfo *ID) {
8440 // Append the cached TypeString if we have one.
8441 StringRef TypeString = TSC.lookupStr(ID);
8442 if (!TypeString.empty()) {
8443 Enc += TypeString;
8444 return true;
8445 }
8446
8447 // Start to emit an incomplete TypeString.
8448 size_t Start = Enc.size();
8449 Enc += (RT->isUnionType()? 'u' : 's');
8450 Enc += '(';
8451 if (ID)
8452 Enc += ID->getName();
8453 Enc += "){";
8454
8455 // We collect all encoded fields and order as necessary.
8456 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008457 const RecordDecl *RD = RT->getDecl()->getDefinition();
8458 if (RD && !RD->field_empty()) {
8459 // An incomplete TypeString stub is placed in the cache for this RecordType
8460 // so that recursive calls to this RecordType will use it whilst building a
8461 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008462 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008463 std::string StubEnc(Enc.substr(Start).str());
8464 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8465 TSC.addIncomplete(ID, std::move(StubEnc));
8466 if (!extractFieldType(FE, RD, CGM, TSC)) {
8467 (void) TSC.removeIncomplete(ID);
8468 return false;
8469 }
8470 IsRecursive = TSC.removeIncomplete(ID);
8471 // The ABI requires unions to be sorted but not structures.
8472 // See FieldEncoding::operator< for sort algorithm.
8473 if (RT->isUnionType())
8474 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008475 // We can now complete the TypeString.
8476 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008477 for (unsigned I = 0; I != E; ++I) {
8478 if (I)
8479 Enc += ',';
8480 Enc += FE[I].str();
8481 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008482 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008483 Enc += '}';
8484 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8485 return true;
8486}
8487
8488/// Appends enum types to Enc and adds the encoding to the cache.
8489static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8490 TypeStringCache &TSC,
8491 const IdentifierInfo *ID) {
8492 // Append the cached TypeString if we have one.
8493 StringRef TypeString = TSC.lookupStr(ID);
8494 if (!TypeString.empty()) {
8495 Enc += TypeString;
8496 return true;
8497 }
8498
8499 size_t Start = Enc.size();
8500 Enc += "e(";
8501 if (ID)
8502 Enc += ID->getName();
8503 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008504
8505 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008506 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008507 SmallVector<FieldEncoding, 16> FE;
8508 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8509 ++I) {
8510 SmallStringEnc EnumEnc;
8511 EnumEnc += "m(";
8512 EnumEnc += I->getName();
8513 EnumEnc += "){";
8514 I->getInitVal().toString(EnumEnc);
8515 EnumEnc += '}';
8516 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8517 }
8518 std::sort(FE.begin(), FE.end());
8519 unsigned E = FE.size();
8520 for (unsigned I = 0; I != E; ++I) {
8521 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008522 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008523 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008524 }
8525 }
8526 Enc += '}';
8527 TSC.addIfComplete(ID, Enc.substr(Start), false);
8528 return true;
8529}
8530
8531/// Appends type's qualifier to Enc.
8532/// This is done prior to appending the type's encoding.
8533static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8534 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008535 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008536 int Lookup = 0;
8537 if (QT.isConstQualified())
8538 Lookup += 1<<0;
8539 if (QT.isRestrictQualified())
8540 Lookup += 1<<1;
8541 if (QT.isVolatileQualified())
8542 Lookup += 1<<2;
8543 Enc += Table[Lookup];
8544}
8545
8546/// Appends built-in types to Enc.
8547static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8548 const char *EncType;
8549 switch (BT->getKind()) {
8550 case BuiltinType::Void:
8551 EncType = "0";
8552 break;
8553 case BuiltinType::Bool:
8554 EncType = "b";
8555 break;
8556 case BuiltinType::Char_U:
8557 EncType = "uc";
8558 break;
8559 case BuiltinType::UChar:
8560 EncType = "uc";
8561 break;
8562 case BuiltinType::SChar:
8563 EncType = "sc";
8564 break;
8565 case BuiltinType::UShort:
8566 EncType = "us";
8567 break;
8568 case BuiltinType::Short:
8569 EncType = "ss";
8570 break;
8571 case BuiltinType::UInt:
8572 EncType = "ui";
8573 break;
8574 case BuiltinType::Int:
8575 EncType = "si";
8576 break;
8577 case BuiltinType::ULong:
8578 EncType = "ul";
8579 break;
8580 case BuiltinType::Long:
8581 EncType = "sl";
8582 break;
8583 case BuiltinType::ULongLong:
8584 EncType = "ull";
8585 break;
8586 case BuiltinType::LongLong:
8587 EncType = "sll";
8588 break;
8589 case BuiltinType::Float:
8590 EncType = "ft";
8591 break;
8592 case BuiltinType::Double:
8593 EncType = "d";
8594 break;
8595 case BuiltinType::LongDouble:
8596 EncType = "ld";
8597 break;
8598 default:
8599 return false;
8600 }
8601 Enc += EncType;
8602 return true;
8603}
8604
8605/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8606static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8607 const CodeGen::CodeGenModule &CGM,
8608 TypeStringCache &TSC) {
8609 Enc += "p(";
8610 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8611 return false;
8612 Enc += ')';
8613 return true;
8614}
8615
8616/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008617static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8618 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008619 const CodeGen::CodeGenModule &CGM,
8620 TypeStringCache &TSC, StringRef NoSizeEnc) {
8621 if (AT->getSizeModifier() != ArrayType::Normal)
8622 return false;
8623 Enc += "a(";
8624 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8625 CAT->getSize().toStringUnsigned(Enc);
8626 else
8627 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8628 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008629 // The Qualifiers should be attached to the type rather than the array.
8630 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008631 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8632 return false;
8633 Enc += ')';
8634 return true;
8635}
8636
8637/// Appends a function encoding to Enc, calling appendType for the return type
8638/// and the arguments.
8639static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8640 const CodeGen::CodeGenModule &CGM,
8641 TypeStringCache &TSC) {
8642 Enc += "f{";
8643 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8644 return false;
8645 Enc += "}(";
8646 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8647 // N.B. we are only interested in the adjusted param types.
8648 auto I = FPT->param_type_begin();
8649 auto E = FPT->param_type_end();
8650 if (I != E) {
8651 do {
8652 if (!appendType(Enc, *I, CGM, TSC))
8653 return false;
8654 ++I;
8655 if (I != E)
8656 Enc += ',';
8657 } while (I != E);
8658 if (FPT->isVariadic())
8659 Enc += ",va";
8660 } else {
8661 if (FPT->isVariadic())
8662 Enc += "va";
8663 else
8664 Enc += '0';
8665 }
8666 }
8667 Enc += ')';
8668 return true;
8669}
8670
8671/// Handles the type's qualifier before dispatching a call to handle specific
8672/// type encodings.
8673static bool appendType(SmallStringEnc &Enc, QualType QType,
8674 const CodeGen::CodeGenModule &CGM,
8675 TypeStringCache &TSC) {
8676
8677 QualType QT = QType.getCanonicalType();
8678
Robert Lytton6adb20f2014-06-05 09:06:21 +00008679 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8680 // The Qualifiers should be attached to the type rather than the array.
8681 // Thus we don't call appendQualifier() here.
8682 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8683
Robert Lytton844aeeb2014-05-02 09:33:20 +00008684 appendQualifier(Enc, QT);
8685
8686 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8687 return appendBuiltinType(Enc, BT);
8688
Robert Lytton844aeeb2014-05-02 09:33:20 +00008689 if (const PointerType *PT = QT->getAs<PointerType>())
8690 return appendPointerType(Enc, PT, CGM, TSC);
8691
8692 if (const EnumType *ET = QT->getAs<EnumType>())
8693 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8694
8695 if (const RecordType *RT = QT->getAsStructureType())
8696 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8697
8698 if (const RecordType *RT = QT->getAsUnionType())
8699 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8700
8701 if (const FunctionType *FT = QT->getAs<FunctionType>())
8702 return appendFunctionType(Enc, FT, CGM, TSC);
8703
8704 return false;
8705}
8706
8707static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8708 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8709 if (!D)
8710 return false;
8711
8712 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8713 if (FD->getLanguageLinkage() != CLanguageLinkage)
8714 return false;
8715 return appendType(Enc, FD->getType(), CGM, TSC);
8716 }
8717
8718 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8719 if (VD->getLanguageLinkage() != CLanguageLinkage)
8720 return false;
8721 QualType QT = VD->getType().getCanonicalType();
8722 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8723 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008724 // The Qualifiers should be attached to the type rather than the array.
8725 // Thus we don't call appendQualifier() here.
8726 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008727 }
8728 return appendType(Enc, QT, CGM, TSC);
8729 }
8730 return false;
8731}
8732
8733
Robert Lytton0e076492013-08-13 09:43:10 +00008734//===----------------------------------------------------------------------===//
8735// Driver code
8736//===----------------------------------------------------------------------===//
8737
Rafael Espindola9f834732014-09-19 01:54:22 +00008738bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008739 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008740}
8741
Chris Lattner2b037972010-07-29 02:01:43 +00008742const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008743 if (TheTargetCodeGenInfo)
8744 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008745
Reid Kleckner9305fd12016-04-13 23:37:17 +00008746 // Helper to set the unique_ptr while still keeping the return value.
8747 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8748 this->TheTargetCodeGenInfo.reset(P);
8749 return *P;
8750 };
8751
John McCallc8e01702013-04-16 22:48:15 +00008752 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008753 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008754 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008755 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008756
Derek Schuff09338a22012-09-06 17:37:28 +00008757 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008758 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008759 case llvm::Triple::mips:
8760 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008761 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008762 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8763 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008764
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008765 case llvm::Triple::mips64:
8766 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008767 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008768
Dylan McKaye8232d72017-02-08 05:09:26 +00008769 case llvm::Triple::avr:
8770 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8771
Tim Northover25e8a672014-05-24 12:51:25 +00008772 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008773 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008774 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008775 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008776 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008777 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008778 return SetCGInfo(
8779 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008780
Reid Kleckner9305fd12016-04-13 23:37:17 +00008781 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008782 }
8783
Dan Gohmanc2853072015-09-03 22:51:53 +00008784 case llvm::Triple::wasm32:
8785 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008786 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008787
Daniel Dunbard59655c2009-09-12 00:59:49 +00008788 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008789 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008790 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008791 case llvm::Triple::thumbeb: {
8792 if (Triple.getOS() == llvm::Triple::Win32) {
8793 return SetCGInfo(
8794 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008795 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008796
Reid Kleckner9305fd12016-04-13 23:37:17 +00008797 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8798 StringRef ABIStr = getTarget().getABI();
8799 if (ABIStr == "apcs-gnu")
8800 Kind = ARMABIInfo::APCS;
8801 else if (ABIStr == "aapcs16")
8802 Kind = ARMABIInfo::AAPCS16_VFP;
8803 else if (CodeGenOpts.FloatABI == "hard" ||
8804 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008805 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008806 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008807 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008808 Kind = ARMABIInfo::AAPCS_VFP;
8809
8810 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8811 }
8812
John McCallea8d8bb2010-03-11 00:10:12 +00008813 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008814 return SetCGInfo(
8815 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008816 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008817 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008818 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008819 if (getTarget().getABI() == "elfv2")
8820 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008821 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008822 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008823
Hal Finkel415c2a32016-10-02 02:10:45 +00008824 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8825 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008826 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008827 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008828 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008829 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008830 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008831 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008832 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008833 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008834 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008835
Hal Finkel415c2a32016-10-02 02:10:45 +00008836 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8837 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008838 }
John McCallea8d8bb2010-03-11 00:10:12 +00008839
Peter Collingbournec947aae2012-05-20 23:28:41 +00008840 case llvm::Triple::nvptx:
8841 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008842 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008843
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008844 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008845 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008846
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008847 case llvm::Triple::systemz: {
8848 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008849 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008850 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008851
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008852 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008853 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008854 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008855
Eli Friedman33465822011-07-08 23:31:17 +00008856 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008857 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008858 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008859 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008860 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008861
John McCall1fe2a8c2013-06-18 02:46:29 +00008862 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008863 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8864 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8865 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008866 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008867 return SetCGInfo(new X86_32TargetCodeGenInfo(
8868 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8869 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8870 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008871 }
Eli Friedman33465822011-07-08 23:31:17 +00008872 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008873
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008874 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008875 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008876 X86AVXABILevel AVXLevel =
8877 (ABI == "avx512"
8878 ? X86AVXABILevel::AVX512
8879 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008880
Chris Lattner04dc9572010-08-31 16:44:54 +00008881 switch (Triple.getOS()) {
8882 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008883 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008884 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008885 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008886 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008887 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008888 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008889 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008890 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008891 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008892 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008893 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008894 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008895 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008896 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008897 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008898 case llvm::Triple::sparc:
8899 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008900 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008901 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008902 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008903 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008904 case llvm::Triple::spir:
8905 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008906 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008907 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008908}