blob: 12341431ac0c21abe8eb0eb4f01c0ebe3d561151 [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"
Daniel Dunbare3532f82009-08-24 08:52:16 +000025#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000028#include "llvm/Support/raw_ostream.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include <algorithm> // std::sort
Robert Lytton844aeeb2014-05-02 09:33:20 +000030
Anton Korobeynikov244360d2009-06-05 22:08:42 +000031using namespace clang;
32using namespace CodeGen;
33
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +000034// Helper for coercing an aggregate argument or return value into an integer
35// array of the same size (including padding) and alignment. This alternate
36// coercion happens only for the RenderScript ABI and can be removed after
37// runtimes that rely on it are no longer supported.
38//
39// RenderScript assumes that the size of the argument / return value in the IR
40// is the same as the size of the corresponding qualified type. This helper
41// coerces the aggregate type into an array of the same size (including
42// padding). This coercion is used in lieu of expansion of struct members or
43// other canonical coercions that return a coerced-type of larger size.
44//
45// Ty - The argument / return value type
46// Context - The associated ASTContext
47// LLVMContext - The associated LLVMContext
48static ABIArgInfo coerceToIntArray(QualType Ty,
49 ASTContext &Context,
50 llvm::LLVMContext &LLVMContext) {
51 // Alignment and Size are measured in bits.
52 const uint64_t Size = Context.getTypeSize(Ty);
53 const uint64_t Alignment = Context.getTypeAlign(Ty);
54 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
55 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
56 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
57}
58
John McCall943fae92010-05-27 06:19:26 +000059static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
60 llvm::Value *Array,
61 llvm::Value *Value,
62 unsigned FirstIndex,
63 unsigned LastIndex) {
64 // Alternatively, we could emit this as a loop in the source.
65 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000066 llvm::Value *Cell =
67 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000068 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000069 }
70}
71
John McCalla1dee5302010-08-22 10:59:02 +000072static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000073 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000074 T->isMemberFunctionPointerType();
75}
76
John McCall7f416cc2015-09-08 08:05:57 +000077ABIArgInfo
78ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
79 llvm::Type *Padding) const {
80 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
81 ByRef, Realign, Padding);
82}
83
84ABIArgInfo
85ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
86 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
87 /*ByRef*/ false, Realign);
88}
89
Charles Davisc7d5c942015-09-17 20:55:33 +000090Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
91 QualType Ty) const {
92 return Address::invalid();
93}
94
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000095ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000096
John McCall12f23522016-04-04 18:33:08 +000097/// Does the given lowering require more than the given number of
98/// registers when expanded?
99///
100/// This is intended to be the basis of a reasonable basic implementation
101/// of should{Pass,Return}IndirectlyForSwift.
102///
103/// For most targets, a limit of four total registers is reasonable; this
104/// limits the amount of code required in order to move around the value
105/// in case it wasn't produced immediately prior to the call by the caller
106/// (or wasn't produced in exactly the right registers) or isn't used
107/// immediately within the callee. But some targets may need to further
108/// limit the register count due to an inability to support that many
109/// return registers.
110static bool occupiesMoreThan(CodeGenTypes &cgt,
111 ArrayRef<llvm::Type*> scalarTypes,
112 unsigned maxAllRegisters) {
113 unsigned intCount = 0, fpCount = 0;
114 for (llvm::Type *type : scalarTypes) {
115 if (type->isPointerTy()) {
116 intCount++;
117 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
118 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
119 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
120 } else {
121 assert(type->isVectorTy() || type->isFloatingPointTy());
122 fpCount++;
123 }
124 }
125
126 return (intCount + fpCount > maxAllRegisters);
127}
128
129bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
130 llvm::Type *eltTy,
131 unsigned numElts) const {
132 // The default implementation of this assumes that the target guarantees
133 // 128-bit SIMD support but nothing more.
134 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
135}
136
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000137static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +0000138 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000139 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
140 if (!RD)
141 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000142 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000143}
144
145static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +0000146 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000147 const RecordType *RT = T->getAs<RecordType>();
148 if (!RT)
149 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +0000150 return getRecordArgABI(RT, CXXABI);
151}
152
Reid Klecknerb1be6832014-11-15 01:41:41 +0000153/// Pass transparent unions as if they were the type of the first element. Sema
154/// should ensure that all elements of the union have the same "machine type".
155static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
156 if (const RecordType *UT = Ty->getAsUnionType()) {
157 const RecordDecl *UD = UT->getDecl();
158 if (UD->hasAttr<TransparentUnionAttr>()) {
159 assert(!UD->field_empty() && "sema created an empty transparent union");
160 return UD->field_begin()->getType();
161 }
162 }
163 return Ty;
164}
165
Mark Lacey3825e832013-10-06 01:33:34 +0000166CGCXXABI &ABIInfo::getCXXABI() const {
167 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000168}
169
Chris Lattner2b037972010-07-29 02:01:43 +0000170ASTContext &ABIInfo::getContext() const {
171 return CGT.getContext();
172}
173
174llvm::LLVMContext &ABIInfo::getVMContext() const {
175 return CGT.getLLVMContext();
176}
177
Micah Villmowdd31ca12012-10-08 16:25:52 +0000178const llvm::DataLayout &ABIInfo::getDataLayout() const {
179 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000180}
181
John McCallc8e01702013-04-16 22:48:15 +0000182const TargetInfo &ABIInfo::getTarget() const {
183 return CGT.getTarget();
184}
Chris Lattner2b037972010-07-29 02:01:43 +0000185
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000186bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
187
Reid Klecknere9f6a712014-10-31 17:10:41 +0000188bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
189 return false;
190}
191
192bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
193 uint64_t Members) const {
194 return false;
195}
196
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000197bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
198 return false;
199}
200
Yaron Kerencdae9412016-01-29 19:38:18 +0000201LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000202 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000203 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000204 switch (TheKind) {
205 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000206 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000207 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000208 Ty->print(OS);
209 else
210 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000211 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000212 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000213 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000214 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000215 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000216 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000217 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000218 case InAlloca:
219 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
220 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000221 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000222 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000223 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000224 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000225 break;
226 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000227 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000228 break;
John McCallf26e73d2016-03-11 04:30:43 +0000229 case CoerceAndExpand:
230 OS << "CoerceAndExpand Type=";
231 getCoerceAndExpandType()->print(OS);
232 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000233 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000234 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000235}
236
Petar Jovanovic402257b2015-12-04 00:26:47 +0000237// Dynamically round a pointer up to a multiple of the given alignment.
238static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
239 llvm::Value *Ptr,
240 CharUnits Align) {
241 llvm::Value *PtrAsInt = Ptr;
242 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
243 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
244 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
245 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
246 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
247 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
248 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
249 Ptr->getType(),
250 Ptr->getName() + ".aligned");
251 return PtrAsInt;
252}
253
John McCall7f416cc2015-09-08 08:05:57 +0000254/// Emit va_arg for a platform using the common void* representation,
255/// where arguments are simply emitted in an array of slots on the stack.
256///
257/// This version implements the core direct-value passing rules.
258///
259/// \param SlotSize - The size and alignment of a stack slot.
260/// Each argument will be allocated to a multiple of this number of
261/// slots, and all the slots will be aligned to this value.
262/// \param AllowHigherAlign - The slot alignment is not a cap;
263/// an argument type with an alignment greater than the slot size
264/// will be emitted on a higher-alignment address, potentially
265/// leaving one or more empty slots behind as padding. If this
266/// is false, the returned address might be less-aligned than
267/// DirectAlign.
268static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
269 Address VAListAddr,
270 llvm::Type *DirectTy,
271 CharUnits DirectSize,
272 CharUnits DirectAlign,
273 CharUnits SlotSize,
274 bool AllowHigherAlign) {
275 // Cast the element type to i8* if necessary. Some platforms define
276 // va_list as a struct containing an i8* instead of just an i8*.
277 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
278 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
279
280 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
281
282 // If the CC aligns values higher than the slot size, do so if needed.
283 Address Addr = Address::invalid();
284 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000285 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
286 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000287 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000288 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000289 }
290
291 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000292 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000293 llvm::Value *NextPtr =
294 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
295 "argp.next");
296 CGF.Builder.CreateStore(NextPtr, VAListAddr);
297
298 // If the argument is smaller than a slot, and this is a big-endian
299 // target, the argument will be right-adjusted in its slot.
Strahinja Petrovic515a1eb2016-06-24 12:12:41 +0000300 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
301 !DirectTy->isStructTy()) {
John McCall7f416cc2015-09-08 08:05:57 +0000302 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
303 }
304
305 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
306 return Addr;
307}
308
309/// Emit va_arg for a platform using the common void* representation,
310/// where arguments are simply emitted in an array of slots on the stack.
311///
312/// \param IsIndirect - Values of this type are passed indirectly.
313/// \param ValueInfo - The size and alignment of this type, generally
314/// computed with getContext().getTypeInfoInChars(ValueTy).
315/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
316/// Each argument will be allocated to a multiple of this number of
317/// slots, and all the slots will be aligned to this value.
318/// \param AllowHigherAlign - The slot alignment is not a cap;
319/// an argument type with an alignment greater than the slot size
320/// will be emitted on a higher-alignment address, potentially
321/// leaving one or more empty slots behind as padding.
322static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
323 QualType ValueTy, bool IsIndirect,
324 std::pair<CharUnits, CharUnits> ValueInfo,
325 CharUnits SlotSizeAndAlign,
326 bool AllowHigherAlign) {
327 // The size and alignment of the value that was passed directly.
328 CharUnits DirectSize, DirectAlign;
329 if (IsIndirect) {
330 DirectSize = CGF.getPointerSize();
331 DirectAlign = CGF.getPointerAlign();
332 } else {
333 DirectSize = ValueInfo.first;
334 DirectAlign = ValueInfo.second;
335 }
336
337 // Cast the address we've calculated to the right type.
338 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
339 if (IsIndirect)
340 DirectTy = DirectTy->getPointerTo(0);
341
342 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
343 DirectSize, DirectAlign,
344 SlotSizeAndAlign,
345 AllowHigherAlign);
346
347 if (IsIndirect) {
348 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
349 }
350
351 return Addr;
352
353}
354
355static Address emitMergePHI(CodeGenFunction &CGF,
356 Address Addr1, llvm::BasicBlock *Block1,
357 Address Addr2, llvm::BasicBlock *Block2,
358 const llvm::Twine &Name = "") {
359 assert(Addr1.getType() == Addr2.getType());
360 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
361 PHI->addIncoming(Addr1.getPointer(), Block1);
362 PHI->addIncoming(Addr2.getPointer(), Block2);
363 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
364 return Address(PHI, Align);
365}
366
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000367TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
368
John McCall3480ef22011-08-30 01:42:09 +0000369// If someone can figure out a general rule for this, that would be great.
370// It's probably just doomed to be platform-dependent, though.
371unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
372 // Verified for:
373 // x86-64 FreeBSD, Linux, Darwin
374 // x86-32 FreeBSD, Linux, Darwin
375 // PowerPC Linux, Darwin
376 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000377 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000378 return 32;
379}
380
John McCalla729c622012-02-17 03:33:10 +0000381bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
382 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000383 // The following conventions are known to require this to be false:
384 // x86_stdcall
385 // MIPS
386 // For everything else, we just prefer false unless we opt out.
387 return false;
388}
389
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000390void
391TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
392 llvm::SmallString<24> &Opt) const {
393 // This assumes the user is passing a library name like "rt" instead of a
394 // filename like "librt.a/so", and that they don't care whether it's static or
395 // dynamic.
396 Opt = "-l";
397 Opt += Lib;
398}
399
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000400unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +0000401 // OpenCL kernels are called via an explicit runtime API with arguments
402 // set with clSetKernelArg(), not as normal sub-functions.
403 // Return SPIR_KERNEL by default as the kernel calling convention to
404 // ensure the fingerprint is fixed such way that each OpenCL argument
405 // gets one matching argument in the produced kernel function argument
406 // list to enable feasible implementation of clSetKernelArg() with
407 // aggregates etc. In case we would use the default C calling conv here,
408 // clSetKernelArg() might break depending on the target-specific
409 // conventions; different targets might split structs passed as values
410 // to multiple function arguments etc.
411 return llvm::CallingConv::SPIR_KERNEL;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +0000412}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000413
Yaxun Liu402804b2016-12-15 08:09:08 +0000414llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
415 llvm::PointerType *T, QualType QT) const {
416 return llvm::ConstantPointerNull::get(T);
417}
418
Yaxun Liucbf647c2017-07-08 13:24:52 +0000419unsigned TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
420 const VarDecl *D) const {
421 assert(!CGM.getLangOpts().OpenCL &&
422 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
423 "Address space agnostic languages only");
Yaxun Liu7bce6422017-07-08 19:13:41 +0000424 return D ? D->getType().getAddressSpace()
425 : static_cast<unsigned>(LangAS::Default);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000426}
427
Yaxun Liu402804b2016-12-15 08:09:08 +0000428llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000429 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, unsigned SrcAddr,
430 unsigned DestAddr, llvm::Type *DestTy, bool isNonNull) const {
Yaxun Liu402804b2016-12-15 08:09:08 +0000431 // Since target may map different address spaces in AST to the same address
432 // space, an address space conversion may end up as a bitcast.
Yaxun Liucbf647c2017-07-08 13:24:52 +0000433 if (auto *C = dyn_cast<llvm::Constant>(Src))
434 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000435 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
Yaxun Liu402804b2016-12-15 08:09:08 +0000436}
437
Yaxun Liucbf647c2017-07-08 13:24:52 +0000438llvm::Constant *
439TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
440 unsigned SrcAddr, unsigned DestAddr,
441 llvm::Type *DestTy) const {
442 // Since target may map different address spaces in AST to the same address
443 // space, an address space conversion may end up as a bitcast.
444 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
445}
446
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000447static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000448
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000449/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000450/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000451static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
452 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000453 if (FD->isUnnamedBitfield())
454 return true;
455
456 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000457
Eli Friedman0b3f2012011-11-18 03:47:20 +0000458 // Constant arrays of empty records count as empty, strip them off.
459 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000460 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000461 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
462 if (AT->getSize() == 0)
463 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000464 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000465 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000466
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000467 const RecordType *RT = FT->getAs<RecordType>();
468 if (!RT)
469 return false;
470
471 // C++ record fields are never empty, at least in the Itanium ABI.
472 //
473 // FIXME: We should use a predicate for whether this behavior is true in the
474 // current ABI.
475 if (isa<CXXRecordDecl>(RT->getDecl()))
476 return false;
477
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000478 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000479}
480
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000481/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000482/// fields. Note that a structure with a flexible array member is not
483/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000484static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000485 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000486 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000487 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000488 const RecordDecl *RD = RT->getDecl();
489 if (RD->hasFlexibleArrayMember())
490 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000491
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000492 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000493 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000494 for (const auto &I : CXXRD->bases())
495 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000496 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000497
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000498 for (const auto *I : RD->fields())
499 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000500 return false;
501 return true;
502}
503
504/// isSingleElementStruct - Determine if a structure is a "single
505/// element struct", i.e. it has exactly one non-empty field or
506/// exactly one field which is itself a single element
507/// struct. Structures with flexible array members are never
508/// considered single element structs.
509///
510/// \return The field declaration for the single non-empty field, if
511/// it exists.
512static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000513 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000514 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000515 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000516
517 const RecordDecl *RD = RT->getDecl();
518 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000519 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000520
Craig Topper8a13c412014-05-21 05:09:00 +0000521 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000522
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000523 // If this is a C++ record, check the bases first.
524 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000525 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000526 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000527 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000528 continue;
529
530 // If we already found an element then this isn't a single-element struct.
531 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000532 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000533
534 // If this is non-empty and not a single element struct, the composite
535 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000536 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000537 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000538 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000539 }
540 }
541
542 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000543 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000544 QualType FT = FD->getType();
545
546 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000547 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000548 continue;
549
550 // If we already found an element then this isn't a single-element
551 // struct.
552 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000553 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000554
555 // Treat single element arrays as the element.
556 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
557 if (AT->getSize().getZExtValue() != 1)
558 break;
559 FT = AT->getElementType();
560 }
561
John McCalla1dee5302010-08-22 10:59:02 +0000562 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000563 Found = FT.getTypePtr();
564 } else {
565 Found = isSingleElementStruct(FT, Context);
566 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000567 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000568 }
569 }
570
Eli Friedmanee945342011-11-18 01:25:50 +0000571 // We don't consider a struct a single-element struct if it has
572 // padding beyond the element type.
573 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000574 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000575
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000576 return Found;
577}
578
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000579namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000580Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
581 const ABIArgInfo &AI) {
582 // This default implementation defers to the llvm backend's va_arg
583 // instruction. It can handle only passing arguments directly
584 // (typically only handled in the backend for primitive types), or
585 // aggregates passed indirectly by pointer (NOTE: if the "byval"
586 // flag has ABI impact in the callee, this implementation cannot
587 // work.)
588
589 // Only a few cases are covered here at the moment -- those needed
590 // by the default abi.
591 llvm::Value *Val;
592
593 if (AI.isIndirect()) {
594 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000595 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000596 assert(
597 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000598 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000599
600 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
601 CharUnits TyAlignForABI = TyInfo.second;
602
603 llvm::Type *BaseTy =
604 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
605 llvm::Value *Addr =
606 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
607 return Address(Addr, TyAlignForABI);
608 } else {
609 assert((AI.isDirect() || AI.isExtend()) &&
610 "Unexpected ArgInfo Kind in generic VAArg emitter!");
611
612 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000613 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000614 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000615 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000616 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000617 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000618 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000619 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000620
621 Address Temp = CGF.CreateMemTemp(Ty, "varet");
622 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
623 CGF.Builder.CreateStore(Val, Temp);
624 return Temp;
625 }
626}
627
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000628/// DefaultABIInfo - The default implementation for ABI specific
629/// details. This implementation provides information which results in
630/// self-consistent and sensible LLVM IR generation, but does not
631/// conform to any particular ABI.
632class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000633public:
634 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000635
Chris Lattner458b2aa2010-07-29 02:16:43 +0000636 ABIArgInfo classifyReturnType(QualType RetTy) const;
637 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000638
Craig Topper4f12f102014-03-12 06:41:41 +0000639 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000640 if (!getCXXABI().classifyReturnType(FI))
641 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000642 for (auto &I : FI.arguments())
643 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000644 }
645
John McCall7f416cc2015-09-08 08:05:57 +0000646 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000647 QualType Ty) const override {
648 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
649 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000650};
651
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000652class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
653public:
Chris Lattner2b037972010-07-29 02:01:43 +0000654 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
655 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000656};
657
Chris Lattner458b2aa2010-07-29 02:16:43 +0000658ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000659 Ty = useFirstFieldIfTransparentUnion(Ty);
660
661 if (isAggregateTypeForABI(Ty)) {
662 // Records with non-trivial destructors/copy-constructors should not be
663 // passed by value.
664 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000665 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000666
John McCall7f416cc2015-09-08 08:05:57 +0000667 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000668 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000669
Chris Lattner9723d6c2010-03-11 18:19:55 +0000670 // Treat an enum type as its underlying type.
671 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
672 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000673
Chris Lattner9723d6c2010-03-11 18:19:55 +0000674 return (Ty->isPromotableIntegerType() ?
675 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000676}
677
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000678ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
679 if (RetTy->isVoidType())
680 return ABIArgInfo::getIgnore();
681
682 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000683 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000684
685 // Treat an enum type as its underlying type.
686 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
687 RetTy = EnumTy->getDecl()->getIntegerType();
688
689 return (RetTy->isPromotableIntegerType() ?
690 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
691}
692
Derek Schuff09338a22012-09-06 17:37:28 +0000693//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000694// WebAssembly ABI Implementation
695//
696// This is a very simple ABI that relies a lot on DefaultABIInfo.
697//===----------------------------------------------------------------------===//
698
699class WebAssemblyABIInfo final : public DefaultABIInfo {
700public:
701 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
702 : DefaultABIInfo(CGT) {}
703
704private:
705 ABIArgInfo classifyReturnType(QualType RetTy) const;
706 ABIArgInfo classifyArgumentType(QualType Ty) const;
707
708 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000709 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000710 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000711 void computeInfo(CGFunctionInfo &FI) const override {
712 if (!getCXXABI().classifyReturnType(FI))
713 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
714 for (auto &Arg : FI.arguments())
715 Arg.info = classifyArgumentType(Arg.type);
716 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000717
718 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
719 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000720};
721
722class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
723public:
724 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
725 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
726};
727
728/// \brief Classify argument of given type \p Ty.
729ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
730 Ty = useFirstFieldIfTransparentUnion(Ty);
731
732 if (isAggregateTypeForABI(Ty)) {
733 // Records with non-trivial destructors/copy-constructors should not be
734 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000735 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000736 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000737 // Ignore empty structs/unions.
738 if (isEmptyRecord(getContext(), Ty, true))
739 return ABIArgInfo::getIgnore();
740 // Lower single-element structs to just pass a regular value. TODO: We
741 // could do reasonable-size multiple-element structs too, using getExpand(),
742 // though watch out for things like bitfields.
743 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
744 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000745 }
746
747 // Otherwise just do the default thing.
748 return DefaultABIInfo::classifyArgumentType(Ty);
749}
750
751ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
752 if (isAggregateTypeForABI(RetTy)) {
753 // Records with non-trivial destructors/copy-constructors should not be
754 // returned by value.
755 if (!getRecordArgABI(RetTy, getCXXABI())) {
756 // Ignore empty structs/unions.
757 if (isEmptyRecord(getContext(), RetTy, true))
758 return ABIArgInfo::getIgnore();
759 // Lower single-element structs to just return a regular value. TODO: We
760 // could do reasonable-size multiple-element structs too, using
761 // ABIArgInfo::getDirect().
762 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
763 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
764 }
765 }
766
767 // Otherwise just do the default thing.
768 return DefaultABIInfo::classifyReturnType(RetTy);
769}
770
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000771Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
772 QualType Ty) const {
773 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
774 getContext().getTypeInfoInChars(Ty),
775 CharUnits::fromQuantity(4),
776 /*AllowHigherAlign=*/ true);
777}
778
Dan Gohmanc2853072015-09-03 22:51:53 +0000779//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000780// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000781//
782// This is a simplified version of the x86_32 ABI. Arguments and return values
783// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000784//===----------------------------------------------------------------------===//
785
786class PNaClABIInfo : public ABIInfo {
787 public:
788 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
789
790 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000791 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000792
Craig Topper4f12f102014-03-12 06:41:41 +0000793 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000794 Address EmitVAArg(CodeGenFunction &CGF,
795 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000796};
797
798class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
799 public:
800 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
801 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
802};
803
804void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000805 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000806 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
807
Reid Kleckner40ca9132014-05-13 22:05:45 +0000808 for (auto &I : FI.arguments())
809 I.info = classifyArgumentType(I.type);
810}
Derek Schuff09338a22012-09-06 17:37:28 +0000811
John McCall7f416cc2015-09-08 08:05:57 +0000812Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
813 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000814 // The PNaCL ABI is a bit odd, in that varargs don't use normal
815 // function classification. Structs get passed directly for varargs
816 // functions, through a rewriting transform in
817 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
818 // this target to actually support a va_arg instructions with an
819 // aggregate type, unlike other targets.
820 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000821}
822
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000823/// \brief Classify argument of given type \p Ty.
824ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000825 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000826 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000827 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
828 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000829 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
830 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000831 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000832 } else if (Ty->isFloatingType()) {
833 // Floating-point types don't go inreg.
834 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000835 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000836
837 return (Ty->isPromotableIntegerType() ?
838 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000839}
840
841ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
842 if (RetTy->isVoidType())
843 return ABIArgInfo::getIgnore();
844
Eli Benderskye20dad62013-04-04 22:49:35 +0000845 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000846 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000847 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000848
849 // Treat an enum type as its underlying type.
850 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
851 RetTy = EnumTy->getDecl()->getIntegerType();
852
853 return (RetTy->isPromotableIntegerType() ?
854 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
855}
856
Chad Rosier651c1832013-03-25 21:00:27 +0000857/// IsX86_MMXType - Return true if this is an MMX type.
858bool IsX86_MMXType(llvm::Type *IRType) {
859 // 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 +0000860 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
861 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
862 IRType->getScalarSizeInBits() != 64;
863}
864
Jay Foad7c57be32011-07-11 09:56:20 +0000865static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000866 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000867 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000868 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
869 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
870 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000871 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000872 }
873
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000874 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000875 }
876
877 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000878 return Ty;
879}
880
Reid Kleckner80944df2014-10-31 22:00:51 +0000881/// Returns true if this type can be passed in SSE registers with the
882/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
883static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
884 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Erich Keanede1b2a92017-07-21 18:50:36 +0000885 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
886 if (BT->getKind() == BuiltinType::LongDouble) {
887 if (&Context.getTargetInfo().getLongDoubleFormat() ==
888 &llvm::APFloat::x87DoubleExtended())
889 return false;
890 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000891 return true;
Erich Keanede1b2a92017-07-21 18:50:36 +0000892 }
Reid Kleckner80944df2014-10-31 22:00:51 +0000893 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
894 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
895 // registers specially.
896 unsigned VecSize = Context.getTypeSize(VT);
897 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
898 return true;
899 }
900 return false;
901}
902
903/// Returns true if this aggregate is small enough to be passed in SSE registers
904/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
905static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
906 return NumMembers <= 4;
907}
908
Erich Keane521ed962017-01-05 00:20:51 +0000909/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
910static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
911 auto AI = ABIArgInfo::getDirect(T);
912 AI.setInReg(true);
913 AI.setCanBeFlattened(false);
914 return AI;
915}
916
Chris Lattner0cf24192010-06-28 20:05:43 +0000917//===----------------------------------------------------------------------===//
918// X86-32 ABI Implementation
919//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000920
Reid Kleckner661f35b2014-01-18 01:12:41 +0000921/// \brief Similar to llvm::CCState, but for Clang.
922struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000923 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000924
925 unsigned CC;
926 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000927 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000928};
929
Erich Keane521ed962017-01-05 00:20:51 +0000930enum {
931 // Vectorcall only allows the first 6 parameters to be passed in registers.
932 VectorcallMaxParamNumAsReg = 6
933};
934
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000935/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000936class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000937 enum Class {
938 Integer,
939 Float
940 };
941
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000942 static const unsigned MinABIStackAlignInBytes = 4;
943
David Chisnallde3a0692009-08-17 23:08:21 +0000944 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000945 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000946 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000947 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000948 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000949 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000950
951 static bool isRegisterSize(unsigned Size) {
952 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
953 }
954
Reid Kleckner80944df2014-10-31 22:00:51 +0000955 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
956 // FIXME: Assumes vectorcall is in use.
957 return isX86VectorTypeForVectorCall(getContext(), Ty);
958 }
959
960 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
961 uint64_t NumMembers) const override {
962 // FIXME: Assumes vectorcall is in use.
963 return isX86VectorCallAggregateSmallEnough(NumMembers);
964 }
965
Reid Kleckner40ca9132014-05-13 22:05:45 +0000966 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000967
Daniel Dunbar557893d2010-04-21 19:10:51 +0000968 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
969 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000970 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
971
John McCall7f416cc2015-09-08 08:05:57 +0000972 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000973
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000974 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000975 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000976
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000977 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000978 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000979 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane4bd39302017-06-21 16:37:22 +0000980
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000981 /// \brief Updates the number of available free registers, returns
982 /// true if any registers were allocated.
983 bool updateFreeRegs(QualType Ty, CCState &State) const;
984
985 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
986 bool &NeedsPadding) const;
987 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000988
Reid Kleckner04046052016-05-02 17:41:07 +0000989 bool canExpandIndirectArgument(QualType Ty) const;
990
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000991 /// \brief Rewrite the function info so that all memory arguments use
992 /// inalloca.
993 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
994
995 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000996 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000997 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +0000998 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
999 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001000
Rafael Espindola75419dc2012-07-23 23:30:29 +00001001public:
1002
Craig Topper4f12f102014-03-12 06:41:41 +00001003 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00001004 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1005 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001006
Michael Kupersteindc745202015-10-19 07:52:25 +00001007 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1008 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001009 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +00001010 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +00001011 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1012 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001013 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +00001014 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +00001015 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +00001016
1017 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
1018 ArrayRef<llvm::Type*> scalars,
1019 bool asReturnValue) const override {
1020 // LLVM's x86-32 lowering currently only assigns up to three
1021 // integer registers and three fp registers. Oddly, it'll use up to
1022 // four vector registers for vectors, but those can overlap with the
1023 // scalar registers.
1024 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1025 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00001026
1027 bool isSwiftErrorInRegister() const override {
1028 // x86-32 lowering does not support passing swifterror in a register.
1029 return false;
1030 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001031};
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001032
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001033class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1034public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001035 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1036 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001037 unsigned NumRegisterParameters, bool SoftFloatABI)
1038 : TargetCodeGenInfo(new X86_32ABIInfo(
1039 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1040 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001041
John McCall1fe2a8c2013-06-18 02:46:29 +00001042 static bool isStructReturnInRegABI(
1043 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1044
Eric Christopher162c91c2015-06-05 22:03:00 +00001045 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001046 CodeGen::CodeGenModule &CGM,
1047 ForDefinition_t IsForDefinition) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001048
Craig Topper4f12f102014-03-12 06:41:41 +00001049 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001050 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001051 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001052 return 4;
1053 }
1054
1055 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001056 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001057
Jay Foad7c57be32011-07-11 09:56:20 +00001058 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001059 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001060 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001061 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1062 }
1063
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001064 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1065 std::string &Constraints,
1066 std::vector<llvm::Type *> &ResultRegTypes,
1067 std::vector<llvm::Type *> &ResultTruncRegTypes,
1068 std::vector<LValue> &ResultRegDests,
1069 std::string &AsmString,
1070 unsigned NumOutputs) const override;
1071
Craig Topper4f12f102014-03-12 06:41:41 +00001072 llvm::Constant *
1073 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001074 unsigned Sig = (0xeb << 0) | // jmp rel8
1075 (0x06 << 8) | // .+0x08
1076 ('F' << 16) |
1077 ('T' << 24);
1078 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1079 }
John McCall01391782016-02-05 21:37:38 +00001080
1081 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1082 return "movl\t%ebp, %ebp"
1083 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1084 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001085};
1086
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001087}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001088
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001089/// Rewrite input constraint references after adding some output constraints.
1090/// In the case where there is one output and one input and we add one output,
1091/// we need to replace all operand references greater than or equal to 1:
1092/// mov $0, $1
1093/// mov eax, $1
1094/// The result will be:
1095/// mov $0, $2
1096/// mov eax, $2
1097static void rewriteInputConstraintReferences(unsigned FirstIn,
1098 unsigned NumNewOuts,
1099 std::string &AsmString) {
1100 std::string Buf;
1101 llvm::raw_string_ostream OS(Buf);
1102 size_t Pos = 0;
1103 while (Pos < AsmString.size()) {
1104 size_t DollarStart = AsmString.find('$', Pos);
1105 if (DollarStart == std::string::npos)
1106 DollarStart = AsmString.size();
1107 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1108 if (DollarEnd == std::string::npos)
1109 DollarEnd = AsmString.size();
1110 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1111 Pos = DollarEnd;
1112 size_t NumDollars = DollarEnd - DollarStart;
1113 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1114 // We have an operand reference.
1115 size_t DigitStart = Pos;
1116 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1117 if (DigitEnd == std::string::npos)
1118 DigitEnd = AsmString.size();
1119 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1120 unsigned OperandIndex;
1121 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1122 if (OperandIndex >= FirstIn)
1123 OperandIndex += NumNewOuts;
1124 OS << OperandIndex;
1125 } else {
1126 OS << OperandStr;
1127 }
1128 Pos = DigitEnd;
1129 }
1130 }
1131 AsmString = std::move(OS.str());
1132}
1133
1134/// Add output constraints for EAX:EDX because they are return registers.
1135void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1136 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1137 std::vector<llvm::Type *> &ResultRegTypes,
1138 std::vector<llvm::Type *> &ResultTruncRegTypes,
1139 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1140 unsigned NumOutputs) const {
1141 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1142
1143 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1144 // larger.
1145 if (!Constraints.empty())
1146 Constraints += ',';
1147 if (RetWidth <= 32) {
1148 Constraints += "={eax}";
1149 ResultRegTypes.push_back(CGF.Int32Ty);
1150 } else {
1151 // Use the 'A' constraint for EAX:EDX.
1152 Constraints += "=A";
1153 ResultRegTypes.push_back(CGF.Int64Ty);
1154 }
1155
1156 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1157 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1158 ResultTruncRegTypes.push_back(CoerceTy);
1159
1160 // Coerce the integer by bitcasting the return slot pointer.
1161 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1162 CoerceTy->getPointerTo()));
1163 ResultRegDests.push_back(ReturnSlot);
1164
1165 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1166}
1167
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001168/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001169/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001170bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1171 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001172 uint64_t Size = Context.getTypeSize(Ty);
1173
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001174 // For i386, type must be register sized.
1175 // For the MCU ABI, it only needs to be <= 8-byte
1176 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1177 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001178
1179 if (Ty->isVectorType()) {
1180 // 64- and 128- bit vectors inside structures are not returned in
1181 // registers.
1182 if (Size == 64 || Size == 128)
1183 return false;
1184
1185 return true;
1186 }
1187
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001188 // If this is a builtin, pointer, enum, complex type, member pointer, or
1189 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001190 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001191 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001192 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001193 return true;
1194
1195 // Arrays are treated like records.
1196 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001197 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001198
1199 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001200 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001201 if (!RT) return false;
1202
Anders Carlsson40446e82010-01-27 03:25:19 +00001203 // FIXME: Traverse bases here too.
1204
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001205 // Structure types are passed in register if all fields would be
1206 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001207 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001208 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001209 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001210 continue;
1211
1212 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001213 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001214 return false;
1215 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001216 return true;
1217}
1218
Reid Kleckner04046052016-05-02 17:41:07 +00001219static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1220 // Treat complex types as the element type.
1221 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1222 Ty = CTy->getElementType();
1223
1224 // Check for a type which we know has a simple scalar argument-passing
1225 // convention without any padding. (We're specifically looking for 32
1226 // and 64-bit integer and integer-equivalents, float, and double.)
1227 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1228 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1229 return false;
1230
1231 uint64_t Size = Context.getTypeSize(Ty);
1232 return Size == 32 || Size == 64;
1233}
1234
Reid Kleckner791bbf62017-01-13 17:18:19 +00001235static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1236 uint64_t &Size) {
1237 for (const auto *FD : RD->fields()) {
1238 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1239 // argument is smaller than 32-bits, expanding the struct will create
1240 // alignment padding.
1241 if (!is32Or64BitBasicType(FD->getType(), Context))
1242 return false;
1243
1244 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1245 // how to expand them yet, and the predicate for telling if a bitfield still
1246 // counts as "basic" is more complicated than what we were doing previously.
1247 if (FD->isBitField())
1248 return false;
1249
1250 Size += Context.getTypeSize(FD->getType());
1251 }
1252 return true;
1253}
1254
1255static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1256 uint64_t &Size) {
1257 // Don't do this if there are any non-empty bases.
1258 for (const CXXBaseSpecifier &Base : RD->bases()) {
1259 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1260 Size))
1261 return false;
1262 }
1263 if (!addFieldSizes(Context, RD, Size))
1264 return false;
1265 return true;
1266}
1267
Reid Kleckner04046052016-05-02 17:41:07 +00001268/// Test whether an argument type which is to be passed indirectly (on the
1269/// stack) would have the equivalent layout if it was expanded into separate
1270/// arguments. If so, we prefer to do the latter to avoid inhibiting
1271/// optimizations.
1272bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1273 // We can only expand structure types.
1274 const RecordType *RT = Ty->getAs<RecordType>();
1275 if (!RT)
1276 return false;
1277 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001278 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001279 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001280 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001281 // On non-Windows, we have to conservatively match our old bitcode
1282 // prototypes in order to be ABI-compatible at the bitcode level.
1283 if (!CXXRD->isCLike())
1284 return false;
1285 } else {
1286 // Don't do this for dynamic classes.
1287 if (CXXRD->isDynamicClass())
1288 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001289 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001290 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001291 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001292 } else {
1293 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001294 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001295 }
1296
1297 // We can do this if there was no alignment padding.
1298 return Size == getContext().getTypeSize(Ty);
1299}
1300
John McCall7f416cc2015-09-08 08:05:57 +00001301ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001302 // If the return value is indirect, then the hidden argument is consuming one
1303 // integer register.
1304 if (State.FreeRegs) {
1305 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001306 if (!IsMCUABI)
1307 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001308 }
John McCall7f416cc2015-09-08 08:05:57 +00001309 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001310}
1311
Eric Christopher7565e0d2015-05-29 23:09:49 +00001312ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1313 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001314 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001315 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001316
Reid Kleckner80944df2014-10-31 22:00:51 +00001317 const Type *Base = nullptr;
1318 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001319 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1320 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001321 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1322 // The LLVM struct type for such an aggregate should lower properly.
1323 return ABIArgInfo::getDirect();
1324 }
1325
Chris Lattner458b2aa2010-07-29 02:16:43 +00001326 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001327 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001328 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001329 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001330
1331 // 128-bit vectors are a special case; they are returned in
1332 // registers and we need to make sure to pick a type the LLVM
1333 // backend will like.
1334 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001335 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001336 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001337
1338 // Always return in register if it fits in a general purpose
1339 // register, or if it is 64 bits and has a single element.
1340 if ((Size == 8 || Size == 16 || Size == 32) ||
1341 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001342 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001343 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001344
John McCall7f416cc2015-09-08 08:05:57 +00001345 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001346 }
1347
1348 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001349 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001350
John McCalla1dee5302010-08-22 10:59:02 +00001351 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001352 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001353 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001354 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001355 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001356 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001357
David Chisnallde3a0692009-08-17 23:08:21 +00001358 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001359 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001360 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001361
Denis Zobnin380b2242016-02-11 11:26:03 +00001362 // Ignore empty structs/unions.
1363 if (isEmptyRecord(getContext(), RetTy, true))
1364 return ABIArgInfo::getIgnore();
1365
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001366 // Small structures which are register sized are generally returned
1367 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001368 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001369 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001370
1371 // As a special-case, if the struct is a "single-element" struct, and
1372 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001373 // floating-point register. (MSVC does not apply this special case.)
1374 // We apply a similar transformation for pointer types to improve the
1375 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001376 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001377 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001378 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001379 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1380
1381 // FIXME: We should be able to narrow this integer in cases with dead
1382 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001383 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001384 }
1385
John McCall7f416cc2015-09-08 08:05:57 +00001386 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001387 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001388
Chris Lattner458b2aa2010-07-29 02:16:43 +00001389 // Treat an enum type as its underlying type.
1390 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1391 RetTy = EnumTy->getDecl()->getIntegerType();
1392
1393 return (RetTy->isPromotableIntegerType() ?
1394 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001395}
1396
Eli Friedman7919bea2012-06-05 19:40:46 +00001397static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1398 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1399}
1400
Daniel Dunbared23de32010-09-16 20:42:00 +00001401static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1402 const RecordType *RT = Ty->getAs<RecordType>();
1403 if (!RT)
1404 return 0;
1405 const RecordDecl *RD = RT->getDecl();
1406
1407 // If this is a C++ record, check the bases first.
1408 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001409 for (const auto &I : CXXRD->bases())
1410 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001411 return false;
1412
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001413 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001414 QualType FT = i->getType();
1415
Eli Friedman7919bea2012-06-05 19:40:46 +00001416 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001417 return true;
1418
1419 if (isRecordWithSSEVectorType(Context, FT))
1420 return true;
1421 }
1422
1423 return false;
1424}
1425
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001426unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1427 unsigned Align) const {
1428 // Otherwise, if the alignment is less than or equal to the minimum ABI
1429 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001430 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001431 return 0; // Use default alignment.
1432
1433 // On non-Darwin, the stack type alignment is always 4.
1434 if (!IsDarwinVectorABI) {
1435 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001436 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001437 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001438
Daniel Dunbared23de32010-09-16 20:42:00 +00001439 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001440 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1441 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001442 return 16;
1443
1444 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001445}
1446
Rafael Espindola703c47f2012-10-19 05:04:37 +00001447ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001448 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001449 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001450 if (State.FreeRegs) {
1451 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001452 if (!IsMCUABI)
1453 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001454 }
John McCall7f416cc2015-09-08 08:05:57 +00001455 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001456 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001457
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001458 // Compute the byval alignment.
1459 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1460 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1461 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001462 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001463
1464 // If the stack alignment is less than the type alignment, realign the
1465 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001466 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001467 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1468 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001469}
1470
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001471X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1472 const Type *T = isSingleElementStruct(Ty, getContext());
1473 if (!T)
1474 T = Ty.getTypePtr();
1475
1476 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1477 BuiltinType::Kind K = BT->getKind();
1478 if (K == BuiltinType::Float || K == BuiltinType::Double)
1479 return Float;
1480 }
1481 return Integer;
1482}
1483
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001484bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001485 if (!IsSoftFloatABI) {
1486 Class C = classify(Ty);
1487 if (C == Float)
1488 return false;
1489 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001490
Rafael Espindola077dd592012-10-24 01:58:58 +00001491 unsigned Size = getContext().getTypeSize(Ty);
1492 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001493
1494 if (SizeInRegs == 0)
1495 return false;
1496
Michael Kuperstein68901882015-10-25 08:18:20 +00001497 if (!IsMCUABI) {
1498 if (SizeInRegs > State.FreeRegs) {
1499 State.FreeRegs = 0;
1500 return false;
1501 }
1502 } else {
1503 // The MCU psABI allows passing parameters in-reg even if there are
1504 // earlier parameters that are passed on the stack. Also,
1505 // it does not allow passing >8-byte structs in-register,
1506 // even if there are 3 free registers available.
1507 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1508 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001509 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001510
Reid Kleckner661f35b2014-01-18 01:12:41 +00001511 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001512 return true;
1513}
1514
1515bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1516 bool &InReg,
1517 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001518 // On Windows, aggregates other than HFAs are never passed in registers, and
1519 // they do not consume register slots. Homogenous floating-point aggregates
1520 // (HFAs) have already been dealt with at this point.
1521 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1522 return false;
1523
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001524 NeedsPadding = false;
1525 InReg = !IsMCUABI;
1526
1527 if (!updateFreeRegs(Ty, State))
1528 return false;
1529
1530 if (IsMCUABI)
1531 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001532
Reid Kleckner80944df2014-10-31 22:00:51 +00001533 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001534 State.CC == llvm::CallingConv::X86_VectorCall ||
1535 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001536 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001537 NeedsPadding = true;
1538
Rafael Espindola077dd592012-10-24 01:58:58 +00001539 return false;
1540 }
1541
Rafael Espindola703c47f2012-10-19 05:04:37 +00001542 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001543}
1544
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001545bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1546 if (!updateFreeRegs(Ty, State))
1547 return false;
1548
1549 if (IsMCUABI)
1550 return false;
1551
1552 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001553 State.CC == llvm::CallingConv::X86_VectorCall ||
1554 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001555 if (getContext().getTypeSize(Ty) > 32)
1556 return false;
1557
1558 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1559 Ty->isReferenceType());
1560 }
1561
1562 return true;
1563}
1564
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001565ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1566 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001567 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001568
Reid Klecknerb1be6832014-11-15 01:41:41 +00001569 Ty = useFirstFieldIfTransparentUnion(Ty);
1570
Reid Kleckner80944df2014-10-31 22:00:51 +00001571 // Check with the C++ ABI first.
1572 const RecordType *RT = Ty->getAs<RecordType>();
1573 if (RT) {
1574 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1575 if (RAA == CGCXXABI::RAA_Indirect) {
1576 return getIndirectResult(Ty, false, State);
1577 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1578 // The field index doesn't matter, we'll fix it up later.
1579 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1580 }
1581 }
1582
Erich Keane4bd39302017-06-21 16:37:22 +00001583 // Regcall uses the concept of a homogenous vector aggregate, similar
1584 // to other targets.
Reid Kleckner80944df2014-10-31 22:00:51 +00001585 const Type *Base = nullptr;
1586 uint64_t NumElts = 0;
Erich Keane4bd39302017-06-21 16:37:22 +00001587 if (State.CC == llvm::CallingConv::X86_RegCall &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001588 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001589
Erich Keane4bd39302017-06-21 16:37:22 +00001590 if (State.FreeSSERegs >= NumElts) {
1591 State.FreeSSERegs -= NumElts;
1592 if (Ty->isBuiltinType() || Ty->isVectorType())
Reid Kleckner80944df2014-10-31 22:00:51 +00001593 return ABIArgInfo::getDirect();
Erich Keane4bd39302017-06-21 16:37:22 +00001594 return ABIArgInfo::getExpand();
Reid Kleckner80944df2014-10-31 22:00:51 +00001595 }
Erich Keane4bd39302017-06-21 16:37:22 +00001596 return getIndirectResult(Ty, /*ByVal=*/false, State);
Reid Kleckner80944df2014-10-31 22:00:51 +00001597 }
1598
1599 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001600 // Structures with flexible arrays are always indirect.
1601 // FIXME: This should not be byval!
1602 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1603 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001604
Reid Kleckner04046052016-05-02 17:41:07 +00001605 // Ignore empty structs/unions on non-Windows.
1606 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001607 return ABIArgInfo::getIgnore();
1608
Rafael Espindolafad28de2012-10-24 01:59:00 +00001609 llvm::LLVMContext &LLVMContext = getVMContext();
1610 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001611 bool NeedsPadding = false;
1612 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001613 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001614 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001615 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001616 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001617 if (InReg)
1618 return ABIArgInfo::getDirectInReg(Result);
1619 else
1620 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001621 }
Craig Topper8a13c412014-05-21 05:09:00 +00001622 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001623
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001624 // Expand small (<= 128-bit) record types when we know that the stack layout
1625 // of those arguments will match the struct. This is important because the
1626 // LLVM backend isn't smart enough to remove byval, which inhibits many
1627 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001628 // Don't do this for the MCU if there are still free integer registers
1629 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001630 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1631 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001632 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001633 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001634 State.CC == llvm::CallingConv::X86_VectorCall ||
1635 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001636 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001637
Reid Kleckner661f35b2014-01-18 01:12:41 +00001638 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001639 }
1640
Chris Lattnerd774ae92010-08-26 20:05:13 +00001641 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001642 // On Darwin, some vectors are passed in memory, we handle this by passing
1643 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001644 if (IsDarwinVectorABI) {
1645 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001646 if ((Size == 8 || Size == 16 || Size == 32) ||
1647 (Size == 64 && VT->getNumElements() == 1))
1648 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1649 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001650 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001651
Chad Rosier651c1832013-03-25 21:00:27 +00001652 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1653 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001654
Chris Lattnerd774ae92010-08-26 20:05:13 +00001655 return ABIArgInfo::getDirect();
1656 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001657
1658
Chris Lattner458b2aa2010-07-29 02:16:43 +00001659 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1660 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001661
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001662 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001663
1664 if (Ty->isPromotableIntegerType()) {
1665 if (InReg)
1666 return ABIArgInfo::getExtendInReg();
1667 return ABIArgInfo::getExtend();
1668 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001669
Rafael Espindola703c47f2012-10-19 05:04:37 +00001670 if (InReg)
1671 return ABIArgInfo::getDirectInReg();
1672 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001673}
1674
Erich Keane521ed962017-01-05 00:20:51 +00001675void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1676 bool &UsedInAlloca) const {
Erich Keane4bd39302017-06-21 16:37:22 +00001677 // Vectorcall x86 works subtly different than in x64, so the format is
1678 // a bit different than the x64 version. First, all vector types (not HVAs)
1679 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1680 // This differs from the x64 implementation, where the first 6 by INDEX get
1681 // registers.
1682 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1683 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1684 // first take up the remaining YMM/XMM registers. If insufficient registers
1685 // remain but an integer register (ECX/EDX) is available, it will be passed
1686 // in that, else, on the stack.
Erich Keane521ed962017-01-05 00:20:51 +00001687 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001688 // First pass do all the vector types.
1689 const Type *Base = nullptr;
1690 uint64_t NumElts = 0;
1691 const QualType& Ty = I.type;
1692 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1693 isHomogeneousAggregate(Ty, Base, NumElts)) {
1694 if (State.FreeSSERegs >= NumElts) {
1695 State.FreeSSERegs -= NumElts;
1696 I.info = ABIArgInfo::getDirect();
1697 } else {
1698 I.info = classifyArgumentType(Ty, State);
1699 }
1700 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1701 }
Erich Keane521ed962017-01-05 00:20:51 +00001702 }
Erich Keane4bd39302017-06-21 16:37:22 +00001703
Erich Keane521ed962017-01-05 00:20:51 +00001704 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00001705 // Second pass, do the rest!
1706 const Type *Base = nullptr;
1707 uint64_t NumElts = 0;
1708 const QualType& Ty = I.type;
1709 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1710
1711 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1712 // Assign true HVAs (non vector/native FP types).
1713 if (State.FreeSSERegs >= NumElts) {
1714 State.FreeSSERegs -= NumElts;
1715 I.info = getDirectX86Hva();
1716 } else {
1717 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1718 }
1719 } else if (!IsHva) {
1720 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1721 I.info = classifyArgumentType(Ty, State);
1722 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1723 }
Erich Keane521ed962017-01-05 00:20:51 +00001724 }
1725}
1726
Rafael Espindolaa6472962012-07-24 00:01:07 +00001727void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001728 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001729 if (IsMCUABI)
1730 State.FreeRegs = 3;
1731 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001732 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001733 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1734 State.FreeRegs = 2;
1735 State.FreeSSERegs = 6;
1736 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001737 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001738 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1739 State.FreeRegs = 5;
1740 State.FreeSSERegs = 8;
1741 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001742 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001743
Reid Kleckner677539d2014-07-10 01:58:55 +00001744 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001745 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001746 } else if (FI.getReturnInfo().isIndirect()) {
1747 // The C++ ABI is not aware of register usage, so we have to check if the
1748 // return value was sret and put it in a register ourselves if appropriate.
1749 if (State.FreeRegs) {
1750 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001751 if (!IsMCUABI)
1752 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001753 }
1754 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001755
Peter Collingbournef7706832014-12-12 23:41:25 +00001756 // The chain argument effectively gives us another free register.
1757 if (FI.isChainCall())
1758 ++State.FreeRegs;
1759
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001760 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001761 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1762 computeVectorCallArgs(FI, State, UsedInAlloca);
1763 } else {
1764 // If not vectorcall, revert to normal behavior.
1765 for (auto &I : FI.arguments()) {
1766 I.info = classifyArgumentType(I.type, State);
1767 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1768 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001769 }
1770
1771 // If we needed to use inalloca for any argument, do a second pass and rewrite
1772 // all the memory arguments to use inalloca.
1773 if (UsedInAlloca)
1774 rewriteWithInAlloca(FI);
1775}
1776
1777void
1778X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001779 CharUnits &StackOffset, ABIArgInfo &Info,
1780 QualType Type) const {
1781 // Arguments are always 4-byte-aligned.
1782 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1783
1784 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001785 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1786 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001787 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001788
John McCall7f416cc2015-09-08 08:05:57 +00001789 // Insert padding bytes to respect alignment.
1790 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001791 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001792 if (StackOffset != FieldEnd) {
1793 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001794 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001795 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001796 FrameFields.push_back(Ty);
1797 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001798}
1799
Reid Kleckner852361d2014-07-26 00:12:26 +00001800static bool isArgInAlloca(const ABIArgInfo &Info) {
1801 // Leave ignored and inreg arguments alone.
1802 switch (Info.getKind()) {
1803 case ABIArgInfo::InAlloca:
1804 return true;
1805 case ABIArgInfo::Indirect:
1806 assert(Info.getIndirectByVal());
1807 return true;
1808 case ABIArgInfo::Ignore:
1809 return false;
1810 case ABIArgInfo::Direct:
1811 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001812 if (Info.getInReg())
1813 return false;
1814 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001815 case ABIArgInfo::Expand:
1816 case ABIArgInfo::CoerceAndExpand:
1817 // These are aggregate types which are never passed in registers when
1818 // inalloca is involved.
1819 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001820 }
1821 llvm_unreachable("invalid enum");
1822}
1823
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001824void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1825 assert(IsWin32StructABI && "inalloca only supported on win32");
1826
1827 // Build a packed struct type for all of the arguments in memory.
1828 SmallVector<llvm::Type *, 6> FrameFields;
1829
John McCall7f416cc2015-09-08 08:05:57 +00001830 // The stack alignment is always 4.
1831 CharUnits StackAlign = CharUnits::fromQuantity(4);
1832
1833 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001834 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1835
1836 // Put 'this' into the struct before 'sret', if necessary.
1837 bool IsThisCall =
1838 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1839 ABIArgInfo &Ret = FI.getReturnInfo();
1840 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1841 isArgInAlloca(I->info)) {
1842 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1843 ++I;
1844 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001845
1846 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001847 if (Ret.isIndirect() && !Ret.getInReg()) {
1848 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1849 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001850 // On Windows, the hidden sret parameter is always returned in eax.
1851 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001852 }
1853
1854 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001855 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001856 ++I;
1857
1858 // Put arguments passed in memory into the struct.
1859 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001860 if (isArgInAlloca(I->info))
1861 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001862 }
1863
1864 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001865 /*isPacked=*/true),
1866 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001867}
1868
John McCall7f416cc2015-09-08 08:05:57 +00001869Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1870 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001871
John McCall7f416cc2015-09-08 08:05:57 +00001872 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001873
John McCall7f416cc2015-09-08 08:05:57 +00001874 // x86-32 changes the alignment of certain arguments on the stack.
1875 //
1876 // Just messing with TypeInfo like this works because we never pass
1877 // anything indirectly.
1878 TypeInfo.second = CharUnits::fromQuantity(
1879 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001880
John McCall7f416cc2015-09-08 08:05:57 +00001881 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1882 TypeInfo, CharUnits::fromQuantity(4),
1883 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001884}
1885
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001886bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1887 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1888 assert(Triple.getArch() == llvm::Triple::x86);
1889
1890 switch (Opts.getStructReturnConvention()) {
1891 case CodeGenOptions::SRCK_Default:
1892 break;
1893 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1894 return false;
1895 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1896 return true;
1897 }
1898
Michael Kupersteind749f232015-10-27 07:46:22 +00001899 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001900 return true;
1901
1902 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001903 case llvm::Triple::DragonFly:
1904 case llvm::Triple::FreeBSD:
1905 case llvm::Triple::OpenBSD:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001906 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001907 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001908 default:
1909 return false;
1910 }
1911}
1912
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001913void X86_32TargetCodeGenInfo::setTargetAttributes(
1914 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
1915 ForDefinition_t IsForDefinition) const {
1916 if (!IsForDefinition)
1917 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001918 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001919 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1920 // Get the LLVM function.
1921 llvm::Function *Fn = cast<llvm::Function>(GV);
1922
1923 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001924 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001925 B.addStackAlignmentAttr(16);
Reid Kleckneree4930b2017-05-02 22:07:37 +00001926 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Charles Davis4ea31ab2010-02-13 15:54:06 +00001927 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001928 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1929 llvm::Function *Fn = cast<llvm::Function>(GV);
1930 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1931 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001932 }
1933}
1934
John McCallbeec5a02010-03-06 00:35:14 +00001935bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1936 CodeGen::CodeGenFunction &CGF,
1937 llvm::Value *Address) const {
1938 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001939
Chris Lattnerece04092012-02-07 00:39:47 +00001940 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001941
John McCallbeec5a02010-03-06 00:35:14 +00001942 // 0-7 are the eight integer registers; the order is different
1943 // on Darwin (for EH), but the range is the same.
1944 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001945 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001946
John McCallc8e01702013-04-16 22:48:15 +00001947 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001948 // 12-16 are st(0..4). Not sure why we stop at 4.
1949 // These have size 16, which is sizeof(long double) on
1950 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001951 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001952 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001953
John McCallbeec5a02010-03-06 00:35:14 +00001954 } else {
1955 // 9 is %eflags, which doesn't get a size on Darwin for some
1956 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001957 Builder.CreateAlignedStore(
1958 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1959 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001960
1961 // 11-16 are st(0..5). Not sure why we stop at 5.
1962 // These have size 12, which is sizeof(long double) on
1963 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001964 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001965 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1966 }
John McCallbeec5a02010-03-06 00:35:14 +00001967
1968 return false;
1969}
1970
Chris Lattner0cf24192010-06-28 20:05:43 +00001971//===----------------------------------------------------------------------===//
1972// X86-64 ABI Implementation
1973//===----------------------------------------------------------------------===//
1974
1975
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001976namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001977/// The AVX ABI level for X86 targets.
1978enum class X86AVXABILevel {
1979 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001980 AVX,
1981 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001982};
1983
1984/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1985static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1986 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001987 case X86AVXABILevel::AVX512:
1988 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001989 case X86AVXABILevel::AVX:
1990 return 256;
1991 case X86AVXABILevel::None:
1992 return 128;
1993 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001994 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001995}
1996
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001997/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001998class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001999 enum Class {
2000 Integer = 0,
2001 SSE,
2002 SSEUp,
2003 X87,
2004 X87Up,
2005 ComplexX87,
2006 NoClass,
2007 Memory
2008 };
2009
2010 /// merge - Implement the X86_64 ABI merging algorithm.
2011 ///
2012 /// Merge an accumulating classification \arg Accum with a field
2013 /// classification \arg Field.
2014 ///
2015 /// \param Accum - The accumulating classification. This should
2016 /// always be either NoClass or the result of a previous merge
2017 /// call. In addition, this should never be Memory (the caller
2018 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002019 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002020
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002021 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2022 ///
2023 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2024 /// final MEMORY or SSE classes when necessary.
2025 ///
2026 /// \param AggregateSize - The size of the current aggregate in
2027 /// the classification process.
2028 ///
2029 /// \param Lo - The classification for the parts of the type
2030 /// residing in the low word of the containing object.
2031 ///
2032 /// \param Hi - The classification for the parts of the type
2033 /// residing in the higher words of the containing object.
2034 ///
2035 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2036
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002037 /// classify - Determine the x86_64 register classes in which the
2038 /// given type T should be passed.
2039 ///
2040 /// \param Lo - The classification for the parts of the type
2041 /// residing in the low word of the containing object.
2042 ///
2043 /// \param Hi - The classification for the parts of the type
2044 /// residing in the high word of the containing object.
2045 ///
2046 /// \param OffsetBase - The bit offset of this type in the
2047 /// containing object. Some parameters are classified different
2048 /// depending on whether they straddle an eightbyte boundary.
2049 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002050 /// \param isNamedArg - Whether the argument in question is a "named"
2051 /// argument, as used in AMD64-ABI 3.5.7.
2052 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002053 /// If a word is unused its result will be NoClass; if a type should
2054 /// be passed in Memory then at least the classification of \arg Lo
2055 /// will be Memory.
2056 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002057 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002058 ///
2059 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2060 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002061 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2062 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002063
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002064 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002065 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2066 unsigned IROffset, QualType SourceTy,
2067 unsigned SourceOffset) const;
2068 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2069 unsigned IROffset, QualType SourceTy,
2070 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002071
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002072 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002073 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002074 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002075
2076 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002077 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002078 ///
2079 /// \param freeIntRegs - The number of free integer registers remaining
2080 /// available.
2081 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002082
Chris Lattner458b2aa2010-07-29 02:16:43 +00002083 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002084
Erich Keane757d3172016-11-02 18:29:35 +00002085 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2086 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002087 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002088
Erich Keane757d3172016-11-02 18:29:35 +00002089 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2090 unsigned &NeededSSE) const;
2091
2092 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2093 unsigned &NeededSSE) const;
2094
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002095 bool IsIllegalVectorType(QualType Ty) const;
2096
John McCalle0fda732011-04-21 01:20:55 +00002097 /// The 0.98 ABI revision clarified a lot of ambiguities,
2098 /// unfortunately in ways that were not always consistent with
2099 /// certain previous compilers. In particular, platforms which
2100 /// required strict binary compatibility with older versions of GCC
2101 /// may need to exempt themselves.
2102 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002103 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002104 }
2105
David Majnemere2ae2282016-03-04 05:26:16 +00002106 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2107 // compilers require us to classify it as INTEGER.
2108 bool classifyIntegerMMXAsSSE() const {
2109 const llvm::Triple &Triple = getTarget().getTriple();
2110 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2111 return false;
2112 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2113 return false;
2114 return true;
2115 }
2116
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002117 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002118 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2119 // 64-bit hardware.
2120 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002121
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002122public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002123 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002124 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002125 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002126 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002127
John McCalla729c622012-02-17 03:33:10 +00002128 bool isPassedUsingAVXType(QualType type) const {
2129 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002130 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002131 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2132 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002133 if (info.isDirect()) {
2134 llvm::Type *ty = info.getCoerceToType();
2135 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2136 return (vectorTy->getBitWidth() > 128);
2137 }
2138 return false;
2139 }
2140
Craig Topper4f12f102014-03-12 06:41:41 +00002141 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002142
John McCall7f416cc2015-09-08 08:05:57 +00002143 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2144 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002145 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2146 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002147
2148 bool has64BitPointers() const {
2149 return Has64BitPointers;
2150 }
John McCall12f23522016-04-04 18:33:08 +00002151
2152 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2153 ArrayRef<llvm::Type*> scalars,
2154 bool asReturnValue) const override {
2155 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2156 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002157 bool isSwiftErrorInRegister() const override {
2158 return true;
2159 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002160};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002161
Chris Lattner04dc9572010-08-31 16:44:54 +00002162/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002163class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002164public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002165 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002166 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002167 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002168
Craig Topper4f12f102014-03-12 06:41:41 +00002169 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002170
John McCall7f416cc2015-09-08 08:05:57 +00002171 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2172 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002173
2174 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2175 // FIXME: Assumes vectorcall is in use.
2176 return isX86VectorTypeForVectorCall(getContext(), Ty);
2177 }
2178
2179 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2180 uint64_t NumMembers) const override {
2181 // FIXME: Assumes vectorcall is in use.
2182 return isX86VectorCallAggregateSmallEnough(NumMembers);
2183 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002184
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002185 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2186 ArrayRef<llvm::Type *> scalars,
2187 bool asReturnValue) const override {
2188 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2189 }
2190
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002191 bool isSwiftErrorInRegister() const override {
2192 return true;
2193 }
2194
Reid Kleckner11a17192015-10-28 22:29:52 +00002195private:
Erich Keane521ed962017-01-05 00:20:51 +00002196 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2197 bool IsVectorCall, bool IsRegCall) const;
2198 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2199 const ABIArgInfo &current) const;
2200 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2201 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002202
Erich Keane521ed962017-01-05 00:20:51 +00002203 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002204};
2205
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002206class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2207public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002208 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002209 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002210
John McCalla729c622012-02-17 03:33:10 +00002211 const X86_64ABIInfo &getABIInfo() const {
2212 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2213 }
2214
Craig Topper4f12f102014-03-12 06:41:41 +00002215 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002216 return 7;
2217 }
2218
2219 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002220 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002221 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002222
John McCall943fae92010-05-27 06:19:26 +00002223 // 0-15 are the 16 integer registers.
2224 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002225 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002226 return false;
2227 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002228
Jay Foad7c57be32011-07-11 09:56:20 +00002229 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002230 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002231 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002232 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2233 }
2234
John McCalla729c622012-02-17 03:33:10 +00002235 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002236 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002237 // The default CC on x86-64 sets %al to the number of SSA
2238 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002239 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002240 // that when AVX types are involved: the ABI explicitly states it is
2241 // undefined, and it doesn't work in practice because of how the ABI
2242 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002243 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002244 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002245 for (CallArgList::const_iterator
2246 it = args.begin(), ie = args.end(); it != ie; ++it) {
2247 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2248 HasAVXType = true;
2249 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002250 }
2251 }
John McCalla729c622012-02-17 03:33:10 +00002252
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002253 if (!HasAVXType)
2254 return true;
2255 }
John McCallcbc038a2011-09-21 08:08:30 +00002256
John McCalla729c622012-02-17 03:33:10 +00002257 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002258 }
2259
Craig Topper4f12f102014-03-12 06:41:41 +00002260 llvm::Constant *
2261 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002262 unsigned Sig;
2263 if (getABIInfo().has64BitPointers())
2264 Sig = (0xeb << 0) | // jmp rel8
2265 (0x0a << 8) | // .+0x0c
2266 ('F' << 16) |
2267 ('T' << 24);
2268 else
2269 Sig = (0xeb << 0) | // jmp rel8
2270 (0x06 << 8) | // .+0x08
2271 ('F' << 16) |
2272 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002273 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2274 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002275
2276 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002277 CodeGen::CodeGenModule &CGM,
2278 ForDefinition_t IsForDefinition) const override {
2279 if (!IsForDefinition)
2280 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002281 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2282 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2283 llvm::Function *Fn = cast<llvm::Function>(GV);
2284 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2285 }
2286 }
2287 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002288};
2289
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002290class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2291public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002292 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2293 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002294
2295 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002296 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002297 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002298 // If the argument contains a space, enclose it in quotes.
2299 if (Lib.find(" ") != StringRef::npos)
2300 Opt += "\"" + Lib.str() + "\"";
2301 else
2302 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002303 }
2304};
2305
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002306static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002307 // If the argument does not end in .lib, automatically add the suffix.
2308 // If the argument contains a space, enclose it in quotes.
2309 // This matches the behavior of MSVC.
2310 bool Quote = (Lib.find(" ") != StringRef::npos);
2311 std::string ArgStr = Quote ? "\"" : "";
2312 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002313 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002314 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002315 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002316 return ArgStr;
2317}
2318
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002319class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2320public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002321 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002322 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2323 unsigned NumRegisterParameters)
2324 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002325 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002326
Eric Christopher162c91c2015-06-05 22:03:00 +00002327 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002328 CodeGen::CodeGenModule &CGM,
2329 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002330
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002331 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002332 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002333 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002334 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002335 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002336
2337 void getDetectMismatchOption(llvm::StringRef Name,
2338 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002339 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002340 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002341 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002342};
2343
Hans Wennborg77dc2362015-01-20 19:45:50 +00002344static void addStackProbeSizeTargetAttribute(const Decl *D,
2345 llvm::GlobalValue *GV,
2346 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002347 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002348 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2349 llvm::Function *Fn = cast<llvm::Function>(GV);
2350
Eric Christopher7565e0d2015-05-29 23:09:49 +00002351 Fn->addFnAttr("stack-probe-size",
2352 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002353 }
2354 }
2355}
2356
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002357void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2358 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2359 ForDefinition_t IsForDefinition) const {
2360 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2361 if (!IsForDefinition)
2362 return;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002363 addStackProbeSizeTargetAttribute(D, GV, CGM);
2364}
2365
Chris Lattner04dc9572010-08-31 16:44:54 +00002366class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2367public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002368 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2369 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002370 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002371
Eric Christopher162c91c2015-06-05 22:03:00 +00002372 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002373 CodeGen::CodeGenModule &CGM,
2374 ForDefinition_t IsForDefinition) const override;
Hans Wennborg77dc2362015-01-20 19:45:50 +00002375
Craig Topper4f12f102014-03-12 06:41:41 +00002376 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002377 return 7;
2378 }
2379
2380 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002381 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002382 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002383
Chris Lattner04dc9572010-08-31 16:44:54 +00002384 // 0-15 are the 16 integer registers.
2385 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002386 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002387 return false;
2388 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002389
2390 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002391 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002392 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002393 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002394 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002395
2396 void getDetectMismatchOption(llvm::StringRef Name,
2397 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002398 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002399 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002400 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002401};
2402
Simon Atanasyan1a116db2017-07-20 20:34:18 +00002403void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2404 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
2405 ForDefinition_t IsForDefinition) const {
2406 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
2407 if (!IsForDefinition)
2408 return;
Alexey Bataevd51e9932016-01-15 04:06:31 +00002409 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2410 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2411 llvm::Function *Fn = cast<llvm::Function>(GV);
2412 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2413 }
2414 }
2415
Hans Wennborg77dc2362015-01-20 19:45:50 +00002416 addStackProbeSizeTargetAttribute(D, GV, CGM);
2417}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002418}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002419
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002420void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2421 Class &Hi) const {
2422 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2423 //
2424 // (a) If one of the classes is Memory, the whole argument is passed in
2425 // memory.
2426 //
2427 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2428 // memory.
2429 //
2430 // (c) If the size of the aggregate exceeds two eightbytes and the first
2431 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2432 // argument is passed in memory. NOTE: This is necessary to keep the
2433 // ABI working for processors that don't support the __m256 type.
2434 //
2435 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2436 //
2437 // Some of these are enforced by the merging logic. Others can arise
2438 // only with unions; for example:
2439 // union { _Complex double; unsigned; }
2440 //
2441 // Note that clauses (b) and (c) were added in 0.98.
2442 //
2443 if (Hi == Memory)
2444 Lo = Memory;
2445 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2446 Lo = Memory;
2447 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2448 Lo = Memory;
2449 if (Hi == SSEUp && Lo != SSE)
2450 Hi = SSE;
2451}
2452
Chris Lattnerd776fb12010-06-28 21:43:59 +00002453X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2455 // classified recursively so that always two fields are
2456 // considered. The resulting class is calculated according to
2457 // the classes of the fields in the eightbyte:
2458 //
2459 // (a) If both classes are equal, this is the resulting class.
2460 //
2461 // (b) If one of the classes is NO_CLASS, the resulting class is
2462 // the other class.
2463 //
2464 // (c) If one of the classes is MEMORY, the result is the MEMORY
2465 // class.
2466 //
2467 // (d) If one of the classes is INTEGER, the result is the
2468 // INTEGER.
2469 //
2470 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2471 // MEMORY is used as class.
2472 //
2473 // (f) Otherwise class SSE is used.
2474
2475 // Accum should never be memory (we should have returned) or
2476 // ComplexX87 (because this cannot be passed in a structure).
2477 assert((Accum != Memory && Accum != ComplexX87) &&
2478 "Invalid accumulated classification during merge.");
2479 if (Accum == Field || Field == NoClass)
2480 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002481 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002482 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002483 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002484 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002485 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002486 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002487 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2488 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002489 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002490 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002491}
2492
Chris Lattner5c740f12010-06-30 19:14:05 +00002493void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002494 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002495 // FIXME: This code can be simplified by introducing a simple value class for
2496 // Class pairs with appropriate constructor methods for the various
2497 // situations.
2498
2499 // FIXME: Some of the split computations are wrong; unaligned vectors
2500 // shouldn't be passed in registers for example, so there is no chance they
2501 // can straddle an eightbyte. Verify & simplify.
2502
2503 Lo = Hi = NoClass;
2504
2505 Class &Current = OffsetBase < 64 ? Lo : Hi;
2506 Current = Memory;
2507
John McCall9dd450b2009-09-21 23:43:11 +00002508 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002509 BuiltinType::Kind k = BT->getKind();
2510
2511 if (k == BuiltinType::Void) {
2512 Current = NoClass;
2513 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2514 Lo = Integer;
2515 Hi = Integer;
2516 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2517 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002518 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002519 Current = SSE;
2520 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002521 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002522 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002523 Lo = SSE;
2524 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002525 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002526 Lo = X87;
2527 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002528 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002529 Current = SSE;
2530 } else
2531 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002532 }
2533 // FIXME: _Decimal32 and _Decimal64 are SSE.
2534 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002535 return;
2536 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002537
Chris Lattnerd776fb12010-06-28 21:43:59 +00002538 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002539 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002540 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002541 return;
2542 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002543
Chris Lattnerd776fb12010-06-28 21:43:59 +00002544 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002545 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002546 return;
2547 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002548
Chris Lattnerd776fb12010-06-28 21:43:59 +00002549 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002550 if (Ty->isMemberFunctionPointerType()) {
2551 if (Has64BitPointers) {
2552 // If Has64BitPointers, this is an {i64, i64}, so classify both
2553 // Lo and Hi now.
2554 Lo = Hi = Integer;
2555 } else {
2556 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2557 // straddles an eightbyte boundary, Hi should be classified as well.
2558 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2559 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2560 if (EB_FuncPtr != EB_ThisAdj) {
2561 Lo = Hi = Integer;
2562 } else {
2563 Current = Integer;
2564 }
2565 }
2566 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002567 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002568 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002569 return;
2570 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002571
Chris Lattnerd776fb12010-06-28 21:43:59 +00002572 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002573 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002574 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2575 // gcc passes the following as integer:
2576 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2577 // 2 bytes - <2 x char>, <1 x short>
2578 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002579 Current = Integer;
2580
2581 // If this type crosses an eightbyte boundary, it should be
2582 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002583 uint64_t EB_Lo = (OffsetBase) / 64;
2584 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2585 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002586 Hi = Lo;
2587 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002588 QualType ElementType = VT->getElementType();
2589
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002590 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002591 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002592 return;
2593
David Majnemere2ae2282016-03-04 05:26:16 +00002594 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2595 // pass them as integer. For platforms where clang is the de facto
2596 // platform compiler, we must continue to use integer.
2597 if (!classifyIntegerMMXAsSSE() &&
2598 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2599 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2600 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2601 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002602 Current = Integer;
2603 else
2604 Current = SSE;
2605
2606 // If this type crosses an eightbyte boundary, it should be
2607 // split.
2608 if (OffsetBase && OffsetBase != 64)
2609 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002610 } else if (Size == 128 ||
2611 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002612 // Arguments of 256-bits are split into four eightbyte chunks. The
2613 // least significant one belongs to class SSE and all the others to class
2614 // SSEUP. The original Lo and Hi design considers that types can't be
2615 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2616 // This design isn't correct for 256-bits, but since there're no cases
2617 // where the upper parts would need to be inspected, avoid adding
2618 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002619 //
2620 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2621 // registers if they are "named", i.e. not part of the "..." of a
2622 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002623 //
2624 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2625 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002626 Lo = SSE;
2627 Hi = SSEUp;
2628 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002629 return;
2630 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002631
Chris Lattnerd776fb12010-06-28 21:43:59 +00002632 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002633 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002634
Chris Lattner2b037972010-07-29 02:01:43 +00002635 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002636 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002637 if (Size <= 64)
2638 Current = Integer;
2639 else if (Size <= 128)
2640 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002641 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002643 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002644 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002645 } else if (ET == getContext().LongDoubleTy) {
2646 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002647 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002648 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002649 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002650 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002651 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002652 Lo = Hi = SSE;
2653 else
2654 llvm_unreachable("unexpected long double representation!");
2655 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002656
2657 // If this complex type crosses an eightbyte boundary then it
2658 // should be split.
2659 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002660 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661 if (Hi == NoClass && EB_Real != EB_Imag)
2662 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002663
Chris Lattnerd776fb12010-06-28 21:43:59 +00002664 return;
2665 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002666
Chris Lattner2b037972010-07-29 02:01:43 +00002667 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002668 // Arrays are treated like structures.
2669
Chris Lattner2b037972010-07-29 02:01:43 +00002670 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002671
2672 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002673 // than eight eightbytes, ..., it has class MEMORY.
2674 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002675 return;
2676
2677 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2678 // fields, it has class MEMORY.
2679 //
2680 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002681 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682 return;
2683
2684 // Otherwise implement simplified merge. We could be smarter about
2685 // this, but it isn't worth it and would be harder to verify.
2686 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002687 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002689
2690 // The only case a 256-bit wide vector could be used is when the array
2691 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2692 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002693 //
2694 if (Size > 128 &&
2695 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002696 return;
2697
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002698 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2699 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002700 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002701 Lo = merge(Lo, FieldLo);
2702 Hi = merge(Hi, FieldHi);
2703 if (Lo == Memory || Hi == Memory)
2704 break;
2705 }
2706
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002707 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002708 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002709 return;
2710 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002711
Chris Lattnerd776fb12010-06-28 21:43:59 +00002712 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002713 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002714
2715 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002716 // than eight eightbytes, ..., it has class MEMORY.
2717 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002718 return;
2719
Anders Carlsson20759ad2009-09-16 15:53:40 +00002720 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2721 // copy constructor or a non-trivial destructor, it is passed by invisible
2722 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002723 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002724 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002725
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002726 const RecordDecl *RD = RT->getDecl();
2727
2728 // Assume variable sized types are passed in memory.
2729 if (RD->hasFlexibleArrayMember())
2730 return;
2731
Chris Lattner2b037972010-07-29 02:01:43 +00002732 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002733
2734 // Reset Lo class, this will be recomputed.
2735 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002736
2737 // If this is a C++ record, classify the bases first.
2738 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002739 for (const auto &I : CXXRD->bases()) {
2740 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002741 "Unexpected base class!");
2742 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002743 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002744
2745 // Classify this field.
2746 //
2747 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2748 // single eightbyte, each is classified separately. Each eightbyte gets
2749 // initialized to class NO_CLASS.
2750 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002751 uint64_t Offset =
2752 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002753 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002754 Lo = merge(Lo, FieldLo);
2755 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002756 if (Lo == Memory || Hi == Memory) {
2757 postMerge(Size, Lo, Hi);
2758 return;
2759 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002760 }
2761 }
2762
2763 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002764 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002765 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002766 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002767 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2768 bool BitField = i->isBitField();
2769
David Majnemerb439dfe2016-08-15 07:20:40 +00002770 // Ignore padding bit-fields.
2771 if (BitField && i->isUnnamedBitfield())
2772 continue;
2773
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002774 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2775 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002776 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002777 // The only case a 256-bit wide vector could be used is when the struct
2778 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2779 // to work for sizes wider than 128, early check and fallback to memory.
2780 //
David Majnemerb229cb02016-08-15 06:39:18 +00002781 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2782 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002783 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002784 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002785 return;
2786 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002787 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002788 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002789 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002790 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002791 return;
2792 }
2793
2794 // Classify this field.
2795 //
2796 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2797 // exceeds a single eightbyte, each is classified
2798 // separately. Each eightbyte gets initialized to class
2799 // NO_CLASS.
2800 Class FieldLo, FieldHi;
2801
2802 // Bit-fields require special handling, they do not force the
2803 // structure to be passed in memory even if unaligned, and
2804 // therefore they can straddle an eightbyte.
2805 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002806 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002807 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002808 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002809
2810 uint64_t EB_Lo = Offset / 64;
2811 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002812
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002813 if (EB_Lo) {
2814 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2815 FieldLo = NoClass;
2816 FieldHi = Integer;
2817 } else {
2818 FieldLo = Integer;
2819 FieldHi = EB_Hi ? Integer : NoClass;
2820 }
2821 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002822 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002823 Lo = merge(Lo, FieldLo);
2824 Hi = merge(Hi, FieldHi);
2825 if (Lo == Memory || Hi == Memory)
2826 break;
2827 }
2828
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002829 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002830 }
2831}
2832
Chris Lattner22a931e2010-06-29 06:01:59 +00002833ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002834 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2835 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002836 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002837 // Treat an enum type as its underlying type.
2838 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2839 Ty = EnumTy->getDecl()->getIntegerType();
2840
2841 return (Ty->isPromotableIntegerType() ?
2842 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2843 }
2844
John McCall7f416cc2015-09-08 08:05:57 +00002845 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002846}
2847
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002848bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2849 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2850 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002851 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002852 if (Size <= 64 || Size > LargestVector)
2853 return true;
2854 }
2855
2856 return false;
2857}
2858
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002859ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2860 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002861 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2862 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002863 //
2864 // This assumption is optimistic, as there could be free registers available
2865 // when we need to pass this argument in memory, and LLVM could try to pass
2866 // the argument in the free register. This does not seem to happen currently,
2867 // but this code would be much safer if we could mark the argument with
2868 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002869 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002870 // Treat an enum type as its underlying type.
2871 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2872 Ty = EnumTy->getDecl()->getIntegerType();
2873
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002874 return (Ty->isPromotableIntegerType() ?
2875 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002876 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002877
Mark Lacey3825e832013-10-06 01:33:34 +00002878 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002879 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002880
Chris Lattner44c2b902011-05-22 23:21:23 +00002881 // Compute the byval alignment. We specify the alignment of the byval in all
2882 // cases so that the mid-level optimizer knows the alignment of the byval.
2883 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002884
2885 // Attempt to avoid passing indirect results using byval when possible. This
2886 // is important for good codegen.
2887 //
2888 // We do this by coercing the value into a scalar type which the backend can
2889 // handle naturally (i.e., without using byval).
2890 //
2891 // For simplicity, we currently only do this when we have exhausted all of the
2892 // free integer registers. Doing this when there are free integer registers
2893 // would require more care, as we would have to ensure that the coerced value
2894 // did not claim the unused register. That would require either reording the
2895 // arguments to the function (so that any subsequent inreg values came first),
2896 // or only doing this optimization when there were no following arguments that
2897 // might be inreg.
2898 //
2899 // We currently expect it to be rare (particularly in well written code) for
2900 // arguments to be passed on the stack when there are still free integer
2901 // registers available (this would typically imply large structs being passed
2902 // by value), so this seems like a fair tradeoff for now.
2903 //
2904 // We can revisit this if the backend grows support for 'onstack' parameter
2905 // attributes. See PR12193.
2906 if (freeIntRegs == 0) {
2907 uint64_t Size = getContext().getTypeSize(Ty);
2908
2909 // If this type fits in an eightbyte, coerce it into the matching integral
2910 // type, which will end up on the stack (with alignment 8).
2911 if (Align == 8 && Size <= 64)
2912 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2913 Size));
2914 }
2915
John McCall7f416cc2015-09-08 08:05:57 +00002916 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002917}
2918
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002919/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2920/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002921llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002922 // Wrapper structs/arrays that only contain vectors are passed just like
2923 // vectors; strip them off if present.
2924 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2925 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002926
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002927 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002928 if (isa<llvm::VectorType>(IRType) ||
2929 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002930 return IRType;
2931
2932 // We couldn't find the preferred IR vector type for 'Ty'.
2933 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002934 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002935
2936 // Return a LLVM IR vector type based on the size of 'Ty'.
2937 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2938 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002939}
2940
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002941/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2942/// is known to either be off the end of the specified type or being in
2943/// alignment padding. The user type specified is known to be at most 128 bits
2944/// in size, and have passed through X86_64ABIInfo::classify with a successful
2945/// classification that put one of the two halves in the INTEGER class.
2946///
2947/// It is conservatively correct to return false.
2948static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2949 unsigned EndBit, ASTContext &Context) {
2950 // If the bytes being queried are off the end of the type, there is no user
2951 // data hiding here. This handles analysis of builtins, vectors and other
2952 // types that don't contain interesting padding.
2953 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2954 if (TySize <= StartBit)
2955 return true;
2956
Chris Lattner98076a22010-07-29 07:43:55 +00002957 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2958 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2959 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2960
2961 // Check each element to see if the element overlaps with the queried range.
2962 for (unsigned i = 0; i != NumElts; ++i) {
2963 // If the element is after the span we care about, then we're done..
2964 unsigned EltOffset = i*EltSize;
2965 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002966
Chris Lattner98076a22010-07-29 07:43:55 +00002967 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2968 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2969 EndBit-EltOffset, Context))
2970 return false;
2971 }
2972 // If it overlaps no elements, then it is safe to process as padding.
2973 return true;
2974 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002975
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002976 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2977 const RecordDecl *RD = RT->getDecl();
2978 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002979
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002980 // If this is a C++ record, check the bases first.
2981 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002982 for (const auto &I : CXXRD->bases()) {
2983 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002984 "Unexpected base class!");
2985 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002986 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002987
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002988 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002989 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002990 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002991
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002992 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002993 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002994 EndBit-BaseOffset, Context))
2995 return false;
2996 }
2997 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002998
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002999 // Verify that no field has data that overlaps the region of interest. Yes
3000 // this could be sped up a lot by being smarter about queried fields,
3001 // however we're only looking at structs up to 16 bytes, so we don't care
3002 // much.
3003 unsigned idx = 0;
3004 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3005 i != e; ++i, ++idx) {
3006 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003007
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003008 // If we found a field after the region we care about, then we're done.
3009 if (FieldOffset >= EndBit) break;
3010
3011 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3012 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3013 Context))
3014 return false;
3015 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003016
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003017 // If nothing in this record overlapped the area of interest, then we're
3018 // clean.
3019 return true;
3020 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003021
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003022 return false;
3023}
3024
Chris Lattnere556a712010-07-29 18:39:32 +00003025/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3026/// float member at the specified offset. For example, {int,{float}} has a
3027/// float at offset 4. It is conservatively correct for this routine to return
3028/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003029static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003030 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003031 // Base case if we find a float.
3032 if (IROffset == 0 && IRType->isFloatTy())
3033 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003034
Chris Lattnere556a712010-07-29 18:39:32 +00003035 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003036 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003037 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3038 unsigned Elt = SL->getElementContainingOffset(IROffset);
3039 IROffset -= SL->getElementOffset(Elt);
3040 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3041 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003042
Chris Lattnere556a712010-07-29 18:39:32 +00003043 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003044 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3045 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003046 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3047 IROffset -= IROffset/EltSize*EltSize;
3048 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3049 }
3050
3051 return false;
3052}
3053
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003054
3055/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3056/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003057llvm::Type *X86_64ABIInfo::
3058GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003059 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003060 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003061 // pass as float if the last 4 bytes is just padding. This happens for
3062 // structs that contain 3 floats.
3063 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3064 SourceOffset*8+64, getContext()))
3065 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003066
Chris Lattnere556a712010-07-29 18:39:32 +00003067 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3068 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3069 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003070 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3071 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003072 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003073
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003074 return llvm::Type::getDoubleTy(getVMContext());
3075}
3076
3077
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003078/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3079/// an 8-byte GPR. This means that we either have a scalar or we are talking
3080/// about the high or low part of an up-to-16-byte struct. This routine picks
3081/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003082/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3083/// etc).
3084///
3085/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3086/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3087/// the 8-byte value references. PrefType may be null.
3088///
Alp Toker9907f082014-07-09 14:06:35 +00003089/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003090/// an offset into this that we're processing (which is always either 0 or 8).
3091///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003092llvm::Type *X86_64ABIInfo::
3093GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003094 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003095 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3096 // returning an 8-byte unit starting with it. See if we can safely use it.
3097 if (IROffset == 0) {
3098 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003099 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3100 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003101 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003102
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003103 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3104 // goodness in the source type is just tail padding. This is allowed to
3105 // kick in for struct {double,int} on the int, but not on
3106 // struct{double,int,int} because we wouldn't return the second int. We
3107 // have to do this analysis on the source type because we can't depend on
3108 // unions being lowered a specific way etc.
3109 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003110 IRType->isIntegerTy(32) ||
3111 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3112 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3113 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003114
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003115 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3116 SourceOffset*8+64, getContext()))
3117 return IRType;
3118 }
3119 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003120
Chris Lattner2192fe52011-07-18 04:24:23 +00003121 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003122 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003123 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003124 if (IROffset < SL->getSizeInBytes()) {
3125 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3126 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003127
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003128 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3129 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003130 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003131 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003132
Chris Lattner2192fe52011-07-18 04:24:23 +00003133 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003134 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003135 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003136 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003137 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3138 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003139 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003140
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003141 // Okay, we don't have any better idea of what to pass, so we pass this in an
3142 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003143 unsigned TySizeInBytes =
3144 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003145
Chris Lattner3f763422010-07-29 17:34:39 +00003146 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003147
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003148 // It is always safe to classify this as an integer type up to i64 that
3149 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003150 return llvm::IntegerType::get(getVMContext(),
3151 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003152}
3153
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003154
3155/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3156/// be used as elements of a two register pair to pass or return, return a
3157/// first class aggregate to represent them. For example, if the low part of
3158/// a by-value argument should be passed as i32* and the high part as float,
3159/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003160static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003161GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003162 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003163 // In order to correctly satisfy the ABI, we need to the high part to start
3164 // at offset 8. If the high and low parts we inferred are both 4-byte types
3165 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3166 // the second element at offset 8. Check for this:
3167 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3168 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003169 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003170 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003171
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003172 // To handle this, we have to increase the size of the low part so that the
3173 // second element will start at an 8 byte offset. We can't increase the size
3174 // of the second element because it might make us access off the end of the
3175 // struct.
3176 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003177 // There are usually two sorts of types the ABI generation code can produce
3178 // for the low part of a pair that aren't 8 bytes in size: float or
3179 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3180 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003181 // Promote these to a larger type.
3182 if (Lo->isFloatTy())
3183 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3184 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003185 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3186 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003187 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3188 }
3189 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003190
Serge Guelton1d993272017-05-09 19:31:30 +00003191 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003192
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003193 // Verify that the second element is at an 8-byte offset.
3194 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3195 "Invalid x86-64 argument pair!");
3196 return Result;
3197}
3198
Chris Lattner31faff52010-07-28 23:06:14 +00003199ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003200classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003201 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3202 // classification algorithm.
3203 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003204 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003205
3206 // Check some invariants.
3207 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003208 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3209
Craig Topper8a13c412014-05-21 05:09:00 +00003210 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003211 switch (Lo) {
3212 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003213 if (Hi == NoClass)
3214 return ABIArgInfo::getIgnore();
3215 // If the low part is just padding, it takes no register, leave ResType
3216 // null.
3217 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3218 "Unknown missing lo part");
3219 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003220
3221 case SSEUp:
3222 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003223 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003224
3225 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3226 // hidden argument.
3227 case Memory:
3228 return getIndirectReturnResult(RetTy);
3229
3230 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3231 // available register of the sequence %rax, %rdx is used.
3232 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003233 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003234
Chris Lattner1f3a0632010-07-29 21:42:50 +00003235 // If we have a sign or zero extended integer, make sure to return Extend
3236 // so that the parameter gets the right LLVM IR attributes.
3237 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3238 // Treat an enum type as its underlying type.
3239 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3240 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003241
Chris Lattner1f3a0632010-07-29 21:42:50 +00003242 if (RetTy->isIntegralOrEnumerationType() &&
3243 RetTy->isPromotableIntegerType())
3244 return ABIArgInfo::getExtend();
3245 }
Chris Lattner31faff52010-07-28 23:06:14 +00003246 break;
3247
3248 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3249 // available SSE register of the sequence %xmm0, %xmm1 is used.
3250 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003251 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003252 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003253
3254 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3255 // returned on the X87 stack in %st0 as 80-bit x87 number.
3256 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003257 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003258 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003259
3260 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3261 // part of the value is returned in %st0 and the imaginary part in
3262 // %st1.
3263 case ComplexX87:
3264 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003265 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Serge Guelton1d993272017-05-09 19:31:30 +00003266 llvm::Type::getX86_FP80Ty(getVMContext()));
Chris Lattner31faff52010-07-28 23:06:14 +00003267 break;
3268 }
3269
Craig Topper8a13c412014-05-21 05:09:00 +00003270 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003271 switch (Hi) {
3272 // Memory was handled previously and X87 should
3273 // never occur as a hi class.
3274 case Memory:
3275 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003276 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003277
3278 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003279 case NoClass:
3280 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003281
Chris Lattner52b3c132010-09-01 00:20:33 +00003282 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003283 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003284 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3285 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003286 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003287 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003288 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003289 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3290 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003291 break;
3292
3293 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003294 // is passed in the next available eightbyte chunk if the last used
3295 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003296 //
Chris Lattner57540c52011-04-15 05:22:18 +00003297 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003298 case SSEUp:
3299 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003300 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003301 break;
3302
3303 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3304 // returned together with the previous X87 value in %st0.
3305 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003306 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003307 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003308 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003309 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003310 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003311 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003312 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3313 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003314 }
Chris Lattner31faff52010-07-28 23:06:14 +00003315 break;
3316 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003317
Chris Lattner52b3c132010-09-01 00:20:33 +00003318 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003319 // known to pass in the high eightbyte of the result. We do this by forming a
3320 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003321 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003322 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003323
Chris Lattner1f3a0632010-07-29 21:42:50 +00003324 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003325}
3326
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003327ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003328 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3329 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003330 const
3331{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003332 Ty = useFirstFieldIfTransparentUnion(Ty);
3333
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003334 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003335 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003336
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003337 // Check some invariants.
3338 // FIXME: Enforce these by construction.
3339 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003340 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3341
3342 neededInt = 0;
3343 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003344 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003345 switch (Lo) {
3346 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003347 if (Hi == NoClass)
3348 return ABIArgInfo::getIgnore();
3349 // If the low part is just padding, it takes no register, leave ResType
3350 // null.
3351 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3352 "Unknown missing lo part");
3353 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003354
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003355 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3356 // on the stack.
3357 case Memory:
3358
3359 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3360 // COMPLEX_X87, it is passed in memory.
3361 case X87:
3362 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003363 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003364 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003365 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003366
3367 case SSEUp:
3368 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003369 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003370
3371 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3372 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3373 // and %r9 is used.
3374 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003375 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003376
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003377 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003378 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003379
3380 // If we have a sign or zero extended integer, make sure to return Extend
3381 // so that the parameter gets the right LLVM IR attributes.
3382 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3383 // Treat an enum type as its underlying type.
3384 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3385 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003386
Chris Lattner1f3a0632010-07-29 21:42:50 +00003387 if (Ty->isIntegralOrEnumerationType() &&
3388 Ty->isPromotableIntegerType())
3389 return ABIArgInfo::getExtend();
3390 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003391
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003392 break;
3393
3394 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3395 // available SSE register is used, the registers are taken in the
3396 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003397 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003398 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003399 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003400 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003401 break;
3402 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003403 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003404
Craig Topper8a13c412014-05-21 05:09:00 +00003405 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003406 switch (Hi) {
3407 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003408 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003409 // which is passed in memory.
3410 case Memory:
3411 case X87:
3412 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003413 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003414
3415 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003416
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003417 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003418 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003419 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003420 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003421
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003422 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3423 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003424 break;
3425
3426 // X87Up generally doesn't occur here (long double is passed in
3427 // memory), except in situations involving unions.
3428 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003429 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003430 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003431
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003432 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3433 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003434
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003435 ++neededSSE;
3436 break;
3437
3438 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3439 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003440 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003441 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003442 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003443 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003444 break;
3445 }
3446
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003447 // If a high part was specified, merge it together with the low part. It is
3448 // known to pass in the high eightbyte of the result. We do this by forming a
3449 // first class struct aggregate with the high and low part: {low, high}
3450 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003451 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003452
Chris Lattner1f3a0632010-07-29 21:42:50 +00003453 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003454}
3455
Erich Keane757d3172016-11-02 18:29:35 +00003456ABIArgInfo
3457X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3458 unsigned &NeededSSE) const {
3459 auto RT = Ty->getAs<RecordType>();
3460 assert(RT && "classifyRegCallStructType only valid with struct types");
3461
3462 if (RT->getDecl()->hasFlexibleArrayMember())
3463 return getIndirectReturnResult(Ty);
3464
3465 // Sum up bases
3466 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3467 if (CXXRD->isDynamicClass()) {
3468 NeededInt = NeededSSE = 0;
3469 return getIndirectReturnResult(Ty);
3470 }
3471
3472 for (const auto &I : CXXRD->bases())
3473 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3474 .isIndirect()) {
3475 NeededInt = NeededSSE = 0;
3476 return getIndirectReturnResult(Ty);
3477 }
3478 }
3479
3480 // Sum up members
3481 for (const auto *FD : RT->getDecl()->fields()) {
3482 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3483 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3484 .isIndirect()) {
3485 NeededInt = NeededSSE = 0;
3486 return getIndirectReturnResult(Ty);
3487 }
3488 } else {
3489 unsigned LocalNeededInt, LocalNeededSSE;
3490 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3491 LocalNeededSSE, true)
3492 .isIndirect()) {
3493 NeededInt = NeededSSE = 0;
3494 return getIndirectReturnResult(Ty);
3495 }
3496 NeededInt += LocalNeededInt;
3497 NeededSSE += LocalNeededSSE;
3498 }
3499 }
3500
3501 return ABIArgInfo::getDirect();
3502}
3503
3504ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3505 unsigned &NeededInt,
3506 unsigned &NeededSSE) const {
3507
3508 NeededInt = 0;
3509 NeededSSE = 0;
3510
3511 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3512}
3513
Chris Lattner22326a12010-07-29 02:31:05 +00003514void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003515
Erich Keane757d3172016-11-02 18:29:35 +00003516 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003517
3518 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003519 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3520 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3521 unsigned NeededInt, NeededSSE;
3522
Erich Keanede1b2a92017-07-21 18:50:36 +00003523 if (!getCXXABI().classifyReturnType(FI)) {
3524 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3525 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3526 FI.getReturnInfo() =
3527 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3528 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3529 FreeIntRegs -= NeededInt;
3530 FreeSSERegs -= NeededSSE;
3531 } else {
3532 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3533 }
3534 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3535 // Complex Long Double Type is passed in Memory when Regcall
3536 // calling convention is used.
3537 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3538 if (getContext().getCanonicalType(CT->getElementType()) ==
3539 getContext().LongDoubleTy)
3540 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3541 } else
3542 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3543 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003544
3545 // If the return value is indirect, then the hidden argument is consuming one
3546 // integer register.
3547 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003548 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003549
Peter Collingbournef7706832014-12-12 23:41:25 +00003550 // The chain argument effectively gives us another free register.
3551 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003552 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003553
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003554 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003555 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3556 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003557 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003558 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003559 it != ie; ++it, ++ArgNo) {
3560 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003561
Erich Keane757d3172016-11-02 18:29:35 +00003562 if (IsRegCall && it->type->isStructureOrClassType())
3563 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3564 else
3565 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3566 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003567
3568 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3569 // eightbyte of an argument, the whole argument is passed on the
3570 // stack. If registers have already been assigned for some
3571 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003572 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3573 FreeIntRegs -= NeededInt;
3574 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003575 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003576 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003577 }
3578 }
3579}
3580
John McCall7f416cc2015-09-08 08:05:57 +00003581static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3582 Address VAListAddr, QualType Ty) {
3583 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3584 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003585 llvm::Value *overflow_arg_area =
3586 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3587
3588 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3589 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003590 // It isn't stated explicitly in the standard, but in practice we use
3591 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003592 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3593 if (Align > CharUnits::fromQuantity(8)) {
3594 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3595 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003596 }
3597
3598 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003599 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003600 llvm::Value *Res =
3601 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003602 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003603
3604 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3605 // l->overflow_arg_area + sizeof(type).
3606 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3607 // an 8 byte boundary.
3608
3609 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003610 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003611 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003612 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3613 "overflow_arg_area.next");
3614 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3615
3616 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003617 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003618}
3619
John McCall7f416cc2015-09-08 08:05:57 +00003620Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3621 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003622 // Assume that va_list type is correct; should be pointer to LLVM type:
3623 // struct {
3624 // i32 gp_offset;
3625 // i32 fp_offset;
3626 // i8* overflow_arg_area;
3627 // i8* reg_save_area;
3628 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003629 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003630
John McCall7f416cc2015-09-08 08:05:57 +00003631 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003632 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003633 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003634
3635 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3636 // in the registers. If not go to step 7.
3637 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003638 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003639
3640 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3641 // general purpose registers needed to pass type and num_fp to hold
3642 // the number of floating point registers needed.
3643
3644 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3645 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3646 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3647 //
3648 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3649 // register save space).
3650
Craig Topper8a13c412014-05-21 05:09:00 +00003651 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003652 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3653 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003654 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003655 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003656 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3657 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003658 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003659 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3660 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003661 }
3662
3663 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003664 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003665 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3666 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003667 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3668 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003669 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3670 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003671 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3672 }
3673
3674 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3675 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3676 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3677 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3678
3679 // Emit code to load the value if it was passed in registers.
3680
3681 CGF.EmitBlock(InRegBlock);
3682
3683 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3684 // an offset of l->gp_offset and/or l->fp_offset. This may require
3685 // copying to a temporary location in case the parameter is passed
3686 // in different register classes or requires an alignment greater
3687 // than 8 for general purpose registers and 16 for XMM registers.
3688 //
3689 // FIXME: This really results in shameful code when we end up needing to
3690 // collect arguments from different places; often what should result in a
3691 // simple assembling of a structure from scattered addresses has many more
3692 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003693 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003694 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3695 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3696 "reg_save_area");
3697
3698 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003699 if (neededInt && neededSSE) {
3700 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003701 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003702 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003703 Address Tmp = CGF.CreateMemTemp(Ty);
3704 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003705 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003706 llvm::Type *TyLo = ST->getElementType(0);
3707 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003708 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003709 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003710 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3711 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003712 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3713 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003714 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3715 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003716
John McCall7f416cc2015-09-08 08:05:57 +00003717 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003718 // FIXME: Our choice of alignment here and below is probably pessimistic.
3719 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3720 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3721 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003722 CGF.Builder.CreateStore(V,
3723 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3724
3725 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003726 V = CGF.Builder.CreateAlignedLoad(
3727 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3728 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003729 CharUnits Offset = CharUnits::fromQuantity(
3730 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3731 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3732
3733 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003734 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003735 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3736 CharUnits::fromQuantity(8));
3737 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003738
3739 // Copy to a temporary if necessary to ensure the appropriate alignment.
3740 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003741 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003742 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003743 CharUnits TyAlign = SizeAlign.second;
3744
3745 // Copy into a temporary if the type is more aligned than the
3746 // register save area.
3747 if (TyAlign.getQuantity() > 8) {
3748 Address Tmp = CGF.CreateMemTemp(Ty);
3749 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003750 RegAddr = Tmp;
3751 }
John McCall7f416cc2015-09-08 08:05:57 +00003752
Chris Lattner0cf24192010-06-28 20:05:43 +00003753 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003754 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3755 CharUnits::fromQuantity(16));
3756 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003757 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003758 assert(neededSSE == 2 && "Invalid number of needed registers!");
3759 // SSE registers are spaced 16 bytes apart in the register save
3760 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003761 // The ABI isn't explicit about this, but it seems reasonable
3762 // to assume that the slots are 16-byte aligned, since the stack is
3763 // naturally 16-byte aligned and the prologue is expected to store
3764 // all the SSE registers to the RSA.
3765 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3766 CharUnits::fromQuantity(16));
3767 Address RegAddrHi =
3768 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3769 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003770 llvm::Type *DoubleTy = CGF.DoubleTy;
Serge Guelton1d993272017-05-09 19:31:30 +00003771 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy);
John McCall7f416cc2015-09-08 08:05:57 +00003772 llvm::Value *V;
3773 Address Tmp = CGF.CreateMemTemp(Ty);
3774 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3775 V = CGF.Builder.CreateLoad(
3776 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3777 CGF.Builder.CreateStore(V,
3778 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3779 V = CGF.Builder.CreateLoad(
3780 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3781 CGF.Builder.CreateStore(V,
3782 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3783
3784 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003785 }
3786
3787 // AMD64-ABI 3.5.7p5: Step 5. Set:
3788 // l->gp_offset = l->gp_offset + num_gp * 8
3789 // l->fp_offset = l->fp_offset + num_fp * 16.
3790 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003791 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003792 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3793 gp_offset_p);
3794 }
3795 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003796 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003797 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3798 fp_offset_p);
3799 }
3800 CGF.EmitBranch(ContBlock);
3801
3802 // Emit code to load the value if it was passed in memory.
3803
3804 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003805 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003806
3807 // Return the appropriate result.
3808
3809 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003810 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3811 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003812 return ResAddr;
3813}
3814
Charles Davisc7d5c942015-09-17 20:55:33 +00003815Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3816 QualType Ty) const {
3817 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3818 CGF.getContext().getTypeInfoInChars(Ty),
3819 CharUnits::fromQuantity(8),
3820 /*allowHigherAlign*/ false);
3821}
3822
Erich Keane521ed962017-01-05 00:20:51 +00003823ABIArgInfo
3824WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3825 const ABIArgInfo &current) const {
3826 // Assumes vectorCall calling convention.
3827 const Type *Base = nullptr;
3828 uint64_t NumElts = 0;
3829
3830 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3831 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3832 FreeSSERegs -= NumElts;
3833 return getDirectX86Hva();
3834 }
3835 return current;
3836}
3837
Reid Kleckner80944df2014-10-31 22:00:51 +00003838ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003839 bool IsReturnType, bool IsVectorCall,
3840 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003841
3842 if (Ty->isVoidType())
3843 return ABIArgInfo::getIgnore();
3844
3845 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3846 Ty = EnumTy->getDecl()->getIntegerType();
3847
Reid Kleckner80944df2014-10-31 22:00:51 +00003848 TypeInfo Info = getContext().getTypeInfo(Ty);
3849 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003850 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003851
Reid Kleckner9005f412014-05-02 00:51:20 +00003852 const RecordType *RT = Ty->getAs<RecordType>();
3853 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003854 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003855 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003856 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003857 }
3858
3859 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003860 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003861
Reid Kleckner9005f412014-05-02 00:51:20 +00003862 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003863
Reid Kleckner80944df2014-10-31 22:00:51 +00003864 const Type *Base = nullptr;
3865 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003866 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3867 // other targets.
3868 if ((IsVectorCall || IsRegCall) &&
3869 isHomogeneousAggregate(Ty, Base, NumElts)) {
3870 if (IsRegCall) {
3871 if (FreeSSERegs >= NumElts) {
3872 FreeSSERegs -= NumElts;
3873 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3874 return ABIArgInfo::getDirect();
3875 return ABIArgInfo::getExpand();
3876 }
3877 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3878 } else if (IsVectorCall) {
3879 if (FreeSSERegs >= NumElts &&
3880 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3881 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003882 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003883 } else if (IsReturnType) {
3884 return ABIArgInfo::getExpand();
3885 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3886 // HVAs are delayed and reclassified in the 2nd step.
3887 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3888 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003889 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003890 }
3891
Reid Klecknerec87fec2014-05-02 01:17:12 +00003892 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003893 // If the member pointer is represented by an LLVM int or ptr, pass it
3894 // directly.
3895 llvm::Type *LLTy = CGT.ConvertType(Ty);
3896 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3897 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003898 }
3899
Michael Kuperstein4f818702015-02-24 09:35:58 +00003900 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003901 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3902 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003903 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003904 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003905
Reid Kleckner9005f412014-05-02 00:51:20 +00003906 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003907 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003908 }
3909
Julien Lerouge10dcff82014-08-27 00:36:55 +00003910 // Bool type is always extended to the ABI, other builtin types are not
3911 // extended.
3912 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3913 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003914 return ABIArgInfo::getExtend();
3915
Reid Kleckner11a17192015-10-28 22:29:52 +00003916 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3917 // passes them indirectly through memory.
3918 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3919 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003920 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003921 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3922 }
3923
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003924 return ABIArgInfo::getDirect();
3925}
3926
Erich Keane521ed962017-01-05 00:20:51 +00003927void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3928 unsigned FreeSSERegs,
3929 bool IsVectorCall,
3930 bool IsRegCall) const {
3931 unsigned Count = 0;
3932 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003933 // Vectorcall in x64 only permits the first 6 arguments to be passed
3934 // as XMM/YMM registers.
Erich Keane521ed962017-01-05 00:20:51 +00003935 if (Count < VectorcallMaxParamNumAsReg)
3936 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3937 else {
3938 // Since these cannot be passed in registers, pretend no registers
3939 // are left.
3940 unsigned ZeroSSERegsAvail = 0;
3941 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3942 IsVectorCall, IsRegCall);
3943 }
3944 ++Count;
3945 }
3946
Erich Keane521ed962017-01-05 00:20:51 +00003947 for (auto &I : FI.arguments()) {
Erich Keane4bd39302017-06-21 16:37:22 +00003948 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
Erich Keane521ed962017-01-05 00:20:51 +00003949 }
3950}
3951
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003952void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003953 bool IsVectorCall =
3954 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003955 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003956
Erich Keane757d3172016-11-02 18:29:35 +00003957 unsigned FreeSSERegs = 0;
3958 if (IsVectorCall) {
3959 // We can use up to 4 SSE return registers with vectorcall.
3960 FreeSSERegs = 4;
3961 } else if (IsRegCall) {
3962 // RegCall gives us 16 SSE registers.
3963 FreeSSERegs = 16;
3964 }
3965
Reid Kleckner80944df2014-10-31 22:00:51 +00003966 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003967 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3968 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003969
Erich Keane757d3172016-11-02 18:29:35 +00003970 if (IsVectorCall) {
3971 // We can use up to 6 SSE register parameters with vectorcall.
3972 FreeSSERegs = 6;
3973 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00003974 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00003975 FreeSSERegs = 16;
3976 }
3977
Erich Keane521ed962017-01-05 00:20:51 +00003978 if (IsVectorCall) {
3979 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3980 } else {
3981 for (auto &I : FI.arguments())
3982 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3983 }
3984
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003985}
3986
John McCall7f416cc2015-09-08 08:05:57 +00003987Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3988 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003989
3990 bool IsIndirect = false;
3991
3992 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3993 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3994 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3995 uint64_t Width = getContext().getTypeSize(Ty);
3996 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3997 }
3998
3999 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00004000 CGF.getContext().getTypeInfoInChars(Ty),
4001 CharUnits::fromQuantity(8),
4002 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00004003}
Chris Lattner0cf24192010-06-28 20:05:43 +00004004
John McCallea8d8bb2010-03-11 00:10:12 +00004005// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00004006namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00004007/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4008class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004009bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00004010public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004011 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4012 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00004013
John McCall7f416cc2015-09-08 08:05:57 +00004014 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4015 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00004016};
4017
4018class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4019public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004020 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4021 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004022
Craig Topper4f12f102014-03-12 06:41:41 +00004023 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00004024 // This is recovered from gcc output.
4025 return 1; // r1 is the dedicated stack pointer
4026 }
4027
4028 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004029 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00004030};
4031
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004032}
John McCallea8d8bb2010-03-11 00:10:12 +00004033
James Y Knight29b5f082016-02-24 02:59:33 +00004034// TODO: this implementation is now likely redundant with
4035// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004036Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4037 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004038 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004039 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4040 // TODO: Implement this. For now ignore.
4041 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004042 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004043 }
4044
John McCall7f416cc2015-09-08 08:05:57 +00004045 // struct __va_list_tag {
4046 // unsigned char gpr;
4047 // unsigned char fpr;
4048 // unsigned short reserved;
4049 // void *overflow_arg_area;
4050 // void *reg_save_area;
4051 // };
4052
Roman Divacky8a12d842014-11-03 18:32:54 +00004053 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004054 bool isInt =
4055 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004056 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004057
4058 // All aggregates are passed indirectly? That doesn't seem consistent
4059 // with the argument-lowering code.
4060 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004061
4062 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004063
4064 // The calling convention either uses 1-2 GPRs or 1 FPR.
4065 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004066 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004067 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4068 } else {
4069 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004070 }
John McCall7f416cc2015-09-08 08:05:57 +00004071
4072 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4073
4074 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004075 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004076 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4077 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4078 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004079
Eric Christopher7565e0d2015-05-29 23:09:49 +00004080 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004081 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004082
4083 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4084 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4085 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4086
4087 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4088
John McCall7f416cc2015-09-08 08:05:57 +00004089 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4090 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004091
John McCall7f416cc2015-09-08 08:05:57 +00004092 // Case 1: consume registers.
4093 Address RegAddr = Address::invalid();
4094 {
4095 CGF.EmitBlock(UsingRegs);
4096
4097 Address RegSaveAreaPtr =
4098 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4099 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4100 CharUnits::fromQuantity(8));
4101 assert(RegAddr.getElementType() == CGF.Int8Ty);
4102
4103 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004104 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004105 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4106 CharUnits::fromQuantity(32));
4107 }
4108
4109 // Get the address of the saved value by scaling the number of
4110 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004111 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004112 llvm::Value *RegOffset =
4113 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4114 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4115 RegAddr.getPointer(), RegOffset),
4116 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4117 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4118
4119 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004120 NumRegs =
4121 Builder.CreateAdd(NumRegs,
4122 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004123 Builder.CreateStore(NumRegs, NumRegsAddr);
4124
4125 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004126 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004127
John McCall7f416cc2015-09-08 08:05:57 +00004128 // Case 2: consume space in the overflow area.
4129 Address MemAddr = Address::invalid();
4130 {
4131 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004132
Roman Divacky039b9702016-02-20 08:31:24 +00004133 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4134
John McCall7f416cc2015-09-08 08:05:57 +00004135 // Everything in the overflow area is rounded up to a size of at least 4.
4136 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4137
4138 CharUnits Size;
4139 if (!isIndirect) {
4140 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004141 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004142 } else {
4143 Size = CGF.getPointerSize();
4144 }
4145
4146 Address OverflowAreaAddr =
4147 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004148 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004149 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004150 // Round up address of argument to alignment
4151 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4152 if (Align > OverflowAreaAlign) {
4153 llvm::Value *Ptr = OverflowArea.getPointer();
4154 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4155 Align);
4156 }
4157
John McCall7f416cc2015-09-08 08:05:57 +00004158 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4159
4160 // Increase the overflow area.
4161 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4162 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4163 CGF.EmitBranch(Cont);
4164 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004165
4166 CGF.EmitBlock(Cont);
4167
John McCall7f416cc2015-09-08 08:05:57 +00004168 // Merge the cases with a phi.
4169 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4170 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004171
John McCall7f416cc2015-09-08 08:05:57 +00004172 // Load the pointer if the argument was passed indirectly.
4173 if (isIndirect) {
4174 Result = Address(Builder.CreateLoad(Result, "aggr"),
4175 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004176 }
4177
4178 return Result;
4179}
4180
John McCallea8d8bb2010-03-11 00:10:12 +00004181bool
4182PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4183 llvm::Value *Address) const {
4184 // This is calculated from the LLVM and GCC tables and verified
4185 // against gcc output. AFAIK all ABIs use the same encoding.
4186
4187 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004188
Chris Lattnerece04092012-02-07 00:39:47 +00004189 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004190 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4191 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4192 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4193
4194 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004195 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004196
4197 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004198 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004199
4200 // 64-76 are various 4-byte special-purpose registers:
4201 // 64: mq
4202 // 65: lr
4203 // 66: ctr
4204 // 67: ap
4205 // 68-75 cr0-7
4206 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004207 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004208
4209 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004210 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004211
4212 // 109: vrsave
4213 // 110: vscr
4214 // 111: spe_acc
4215 // 112: spefscr
4216 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004217 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004218
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004219 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004220}
4221
Roman Divackyd966e722012-05-09 18:22:46 +00004222// PowerPC-64
4223
4224namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004225/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004226class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004227public:
4228 enum ABIKind {
4229 ELFv1 = 0,
4230 ELFv2
4231 };
4232
4233private:
4234 static const unsigned GPRBits = 64;
4235 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004236 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004237 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004238
4239 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4240 // will be passed in a QPX register.
4241 bool IsQPXVectorTy(const Type *Ty) const {
4242 if (!HasQPX)
4243 return false;
4244
4245 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4246 unsigned NumElements = VT->getNumElements();
4247 if (NumElements == 1)
4248 return false;
4249
4250 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4251 if (getContext().getTypeSize(Ty) <= 256)
4252 return true;
4253 } else if (VT->getElementType()->
4254 isSpecificBuiltinType(BuiltinType::Float)) {
4255 if (getContext().getTypeSize(Ty) <= 128)
4256 return true;
4257 }
4258 }
4259
4260 return false;
4261 }
4262
4263 bool IsQPXVectorTy(QualType Ty) const {
4264 return IsQPXVectorTy(Ty.getTypePtr());
4265 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004266
4267public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004268 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4269 bool SoftFloatABI)
4270 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4271 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004272
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004273 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004274 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004275
4276 ABIArgInfo classifyReturnType(QualType RetTy) const;
4277 ABIArgInfo classifyArgumentType(QualType Ty) const;
4278
Reid Klecknere9f6a712014-10-31 17:10:41 +00004279 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4280 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4281 uint64_t Members) const override;
4282
Bill Schmidt84d37792012-10-12 19:26:17 +00004283 // TODO: We can add more logic to computeInfo to improve performance.
4284 // Example: For aggregate arguments that fit in a register, we could
4285 // use getDirectInReg (as is done below for structs containing a single
4286 // floating-point value) to avoid pushing them to memory on function
4287 // entry. This would require changing the logic in PPCISelLowering
4288 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004289 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004290 if (!getCXXABI().classifyReturnType(FI))
4291 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004292 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004293 // We rely on the default argument classification for the most part.
4294 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004295 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004296 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004297 if (T) {
4298 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004299 if (IsQPXVectorTy(T) ||
4300 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004301 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004302 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004303 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004304 continue;
4305 }
4306 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004307 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004308 }
4309 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004310
John McCall7f416cc2015-09-08 08:05:57 +00004311 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4312 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004313};
4314
4315class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004316
Bill Schmidt25cb3492012-10-03 19:18:57 +00004317public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004318 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004319 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4320 bool SoftFloatABI)
4321 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4322 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004323
Craig Topper4f12f102014-03-12 06:41:41 +00004324 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004325 // This is recovered from gcc output.
4326 return 1; // r1 is the dedicated stack pointer
4327 }
4328
4329 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004330 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004331};
4332
Roman Divackyd966e722012-05-09 18:22:46 +00004333class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4334public:
4335 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4336
Craig Topper4f12f102014-03-12 06:41:41 +00004337 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004338 // This is recovered from gcc output.
4339 return 1; // r1 is the dedicated stack pointer
4340 }
4341
4342 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004343 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004344};
4345
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004346}
Roman Divackyd966e722012-05-09 18:22:46 +00004347
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004348// Return true if the ABI requires Ty to be passed sign- or zero-
4349// extended to 64 bits.
4350bool
4351PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4352 // Treat an enum type as its underlying type.
4353 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4354 Ty = EnumTy->getDecl()->getIntegerType();
4355
4356 // Promotable integer types are required to be promoted by the ABI.
4357 if (Ty->isPromotableIntegerType())
4358 return true;
4359
4360 // In addition to the usual promotable integer types, we also need to
4361 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4362 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4363 switch (BT->getKind()) {
4364 case BuiltinType::Int:
4365 case BuiltinType::UInt:
4366 return true;
4367 default:
4368 break;
4369 }
4370
4371 return false;
4372}
4373
John McCall7f416cc2015-09-08 08:05:57 +00004374/// isAlignedParamType - Determine whether a type requires 16-byte or
4375/// higher alignment in the parameter area. Always returns at least 8.
4376CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004377 // Complex types are passed just like their elements.
4378 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4379 Ty = CTy->getElementType();
4380
4381 // Only vector types of size 16 bytes need alignment (larger types are
4382 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004383 if (IsQPXVectorTy(Ty)) {
4384 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004385 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004386
John McCall7f416cc2015-09-08 08:05:57 +00004387 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004388 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004389 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004390 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004391
4392 // For single-element float/vector structs, we consider the whole type
4393 // to have the same alignment requirements as its single element.
4394 const Type *AlignAsType = nullptr;
4395 const Type *EltType = isSingleElementStruct(Ty, getContext());
4396 if (EltType) {
4397 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004398 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004399 getContext().getTypeSize(EltType) == 128) ||
4400 (BT && BT->isFloatingPoint()))
4401 AlignAsType = EltType;
4402 }
4403
Ulrich Weigandb7122372014-07-21 00:48:09 +00004404 // Likewise for ELFv2 homogeneous aggregates.
4405 const Type *Base = nullptr;
4406 uint64_t Members = 0;
4407 if (!AlignAsType && Kind == ELFv2 &&
4408 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4409 AlignAsType = Base;
4410
Ulrich Weigand581badc2014-07-10 17:20:07 +00004411 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004412 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4413 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004414 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004415
John McCall7f416cc2015-09-08 08:05:57 +00004416 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004417 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004418 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004419 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004420
4421 // Otherwise, we only need alignment for any aggregate type that
4422 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004423 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4424 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004425 return CharUnits::fromQuantity(32);
4426 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004427 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004428
John McCall7f416cc2015-09-08 08:05:57 +00004429 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004430}
4431
Ulrich Weigandb7122372014-07-21 00:48:09 +00004432/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4433/// aggregate. Base is set to the base element type, and Members is set
4434/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004435bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4436 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004437 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4438 uint64_t NElements = AT->getSize().getZExtValue();
4439 if (NElements == 0)
4440 return false;
4441 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4442 return false;
4443 Members *= NElements;
4444 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4445 const RecordDecl *RD = RT->getDecl();
4446 if (RD->hasFlexibleArrayMember())
4447 return false;
4448
4449 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004450
4451 // If this is a C++ record, check the bases first.
4452 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4453 for (const auto &I : CXXRD->bases()) {
4454 // Ignore empty records.
4455 if (isEmptyRecord(getContext(), I.getType(), true))
4456 continue;
4457
4458 uint64_t FldMembers;
4459 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4460 return false;
4461
4462 Members += FldMembers;
4463 }
4464 }
4465
Ulrich Weigandb7122372014-07-21 00:48:09 +00004466 for (const auto *FD : RD->fields()) {
4467 // Ignore (non-zero arrays of) empty records.
4468 QualType FT = FD->getType();
4469 while (const ConstantArrayType *AT =
4470 getContext().getAsConstantArrayType(FT)) {
4471 if (AT->getSize().getZExtValue() == 0)
4472 return false;
4473 FT = AT->getElementType();
4474 }
4475 if (isEmptyRecord(getContext(), FT, true))
4476 continue;
4477
4478 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4479 if (getContext().getLangOpts().CPlusPlus &&
4480 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4481 continue;
4482
4483 uint64_t FldMembers;
4484 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4485 return false;
4486
4487 Members = (RD->isUnion() ?
4488 std::max(Members, FldMembers) : Members + FldMembers);
4489 }
4490
4491 if (!Base)
4492 return false;
4493
4494 // Ensure there is no padding.
4495 if (getContext().getTypeSize(Base) * Members !=
4496 getContext().getTypeSize(Ty))
4497 return false;
4498 } else {
4499 Members = 1;
4500 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4501 Members = 2;
4502 Ty = CT->getElementType();
4503 }
4504
Reid Klecknere9f6a712014-10-31 17:10:41 +00004505 // Most ABIs only support float, double, and some vector type widths.
4506 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004507 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004508
4509 // The base type must be the same for all members. Types that
4510 // agree in both total size and mode (float vs. vector) are
4511 // treated as being equivalent here.
4512 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004513 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004514 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004515 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4516 // so make sure to widen it explicitly.
4517 if (const VectorType *VT = Base->getAs<VectorType>()) {
4518 QualType EltTy = VT->getElementType();
4519 unsigned NumElements =
4520 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4521 Base = getContext()
4522 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4523 .getTypePtr();
4524 }
4525 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004526
4527 if (Base->isVectorType() != TyPtr->isVectorType() ||
4528 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4529 return false;
4530 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004531 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4532}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004533
Reid Klecknere9f6a712014-10-31 17:10:41 +00004534bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4535 // Homogeneous aggregates for ELFv2 must have base types of float,
4536 // double, long double, or 128-bit vectors.
4537 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4538 if (BT->getKind() == BuiltinType::Float ||
4539 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004540 BT->getKind() == BuiltinType::LongDouble) {
4541 if (IsSoftFloatABI)
4542 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004543 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004544 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004545 }
4546 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004547 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004548 return true;
4549 }
4550 return false;
4551}
4552
4553bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4554 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004555 // Vector types require one register, floating point types require one
4556 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004557 uint32_t NumRegs =
4558 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004559
4560 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004561 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004562}
4563
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004564ABIArgInfo
4565PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004566 Ty = useFirstFieldIfTransparentUnion(Ty);
4567
Bill Schmidt90b22c92012-11-27 02:46:43 +00004568 if (Ty->isAnyComplexType())
4569 return ABIArgInfo::getDirect();
4570
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004571 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4572 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004573 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004574 uint64_t Size = getContext().getTypeSize(Ty);
4575 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004576 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004577 else if (Size < 128) {
4578 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4579 return ABIArgInfo::getDirect(CoerceTy);
4580 }
4581 }
4582
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004583 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004584 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004585 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004586
John McCall7f416cc2015-09-08 08:05:57 +00004587 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4588 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004589
4590 // ELFv2 homogeneous aggregates are passed as array types.
4591 const Type *Base = nullptr;
4592 uint64_t Members = 0;
4593 if (Kind == ELFv2 &&
4594 isHomogeneousAggregate(Ty, Base, Members)) {
4595 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4596 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4597 return ABIArgInfo::getDirect(CoerceTy);
4598 }
4599
Ulrich Weigand601957f2014-07-21 00:56:36 +00004600 // If an aggregate may end up fully in registers, we do not
4601 // use the ByVal method, but pass the aggregate as array.
4602 // This is usually beneficial since we avoid forcing the
4603 // back-end to store the argument to memory.
4604 uint64_t Bits = getContext().getTypeSize(Ty);
4605 if (Bits > 0 && Bits <= 8 * GPRBits) {
4606 llvm::Type *CoerceTy;
4607
4608 // Types up to 8 bytes are passed as integer type (which will be
4609 // properly aligned in the argument save area doubleword).
4610 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004611 CoerceTy =
4612 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004613 // Larger types are passed as arrays, with the base type selected
4614 // according to the required alignment in the save area.
4615 else {
4616 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004617 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004618 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4619 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4620 }
4621
4622 return ABIArgInfo::getDirect(CoerceTy);
4623 }
4624
Ulrich Weigandb7122372014-07-21 00:48:09 +00004625 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004626 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4627 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004628 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004629 }
4630
4631 return (isPromotableTypeForABI(Ty) ?
4632 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4633}
4634
4635ABIArgInfo
4636PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4637 if (RetTy->isVoidType())
4638 return ABIArgInfo::getIgnore();
4639
Bill Schmidta3d121c2012-12-17 04:20:17 +00004640 if (RetTy->isAnyComplexType())
4641 return ABIArgInfo::getDirect();
4642
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004643 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4644 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004645 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004646 uint64_t Size = getContext().getTypeSize(RetTy);
4647 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004648 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004649 else if (Size < 128) {
4650 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4651 return ABIArgInfo::getDirect(CoerceTy);
4652 }
4653 }
4654
Ulrich Weigandb7122372014-07-21 00:48:09 +00004655 if (isAggregateTypeForABI(RetTy)) {
4656 // ELFv2 homogeneous aggregates are returned as array types.
4657 const Type *Base = nullptr;
4658 uint64_t Members = 0;
4659 if (Kind == ELFv2 &&
4660 isHomogeneousAggregate(RetTy, Base, Members)) {
4661 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4662 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4663 return ABIArgInfo::getDirect(CoerceTy);
4664 }
4665
4666 // ELFv2 small aggregates are returned in up to two registers.
4667 uint64_t Bits = getContext().getTypeSize(RetTy);
4668 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4669 if (Bits == 0)
4670 return ABIArgInfo::getIgnore();
4671
4672 llvm::Type *CoerceTy;
4673 if (Bits > GPRBits) {
4674 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Serge Guelton1d993272017-05-09 19:31:30 +00004675 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004676 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004677 CoerceTy =
4678 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004679 return ABIArgInfo::getDirect(CoerceTy);
4680 }
4681
4682 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004683 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004684 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004685
4686 return (isPromotableTypeForABI(RetTy) ?
4687 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4688}
4689
Bill Schmidt25cb3492012-10-03 19:18:57 +00004690// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004691Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4692 QualType Ty) const {
4693 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4694 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004695
John McCall7f416cc2015-09-08 08:05:57 +00004696 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004697
Bill Schmidt924c4782013-01-14 17:45:36 +00004698 // If we have a complex type and the base type is smaller than 8 bytes,
4699 // the ABI calls for the real and imaginary parts to be right-adjusted
4700 // in separate doublewords. However, Clang expects us to produce a
4701 // pointer to a structure with the two parts packed tightly. So generate
4702 // loads of the real and imaginary parts relative to the va_list pointer,
4703 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004704 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4705 CharUnits EltSize = TypeInfo.first / 2;
4706 if (EltSize < SlotSize) {
4707 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4708 SlotSize * 2, SlotSize,
4709 SlotSize, /*AllowHigher*/ true);
4710
4711 Address RealAddr = Addr;
4712 Address ImagAddr = RealAddr;
4713 if (CGF.CGM.getDataLayout().isBigEndian()) {
4714 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4715 SlotSize - EltSize);
4716 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4717 2 * SlotSize - EltSize);
4718 } else {
4719 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4720 }
4721
4722 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4723 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4724 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4725 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4726 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4727
4728 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4729 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4730 /*init*/ true);
4731 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004732 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004733 }
4734
John McCall7f416cc2015-09-08 08:05:57 +00004735 // Otherwise, just use the general rule.
4736 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4737 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004738}
4739
4740static bool
4741PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4742 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004743 // This is calculated from the LLVM and GCC tables and verified
4744 // against gcc output. AFAIK all ABIs use the same encoding.
4745
4746 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4747
4748 llvm::IntegerType *i8 = CGF.Int8Ty;
4749 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4750 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4751 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4752
4753 // 0-31: r0-31, the 8-byte general-purpose registers
4754 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4755
4756 // 32-63: fp0-31, the 8-byte floating-point registers
4757 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4758
Hal Finkel84832a72016-08-30 02:38:34 +00004759 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004760 // 64: mq
4761 // 65: lr
4762 // 66: ctr
4763 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004764 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4765
4766 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004767 // 68-75 cr0-7
4768 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004769 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004770
4771 // 77-108: v0-31, the 16-byte vector registers
4772 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4773
4774 // 109: vrsave
4775 // 110: vscr
4776 // 111: spe_acc
4777 // 112: spefscr
4778 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004779 // 114: tfhar
4780 // 115: tfiar
4781 // 116: texasr
4782 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004783
4784 return false;
4785}
John McCallea8d8bb2010-03-11 00:10:12 +00004786
Bill Schmidt25cb3492012-10-03 19:18:57 +00004787bool
4788PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4789 CodeGen::CodeGenFunction &CGF,
4790 llvm::Value *Address) const {
4791
4792 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4793}
4794
4795bool
4796PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4797 llvm::Value *Address) const {
4798
4799 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4800}
4801
Chris Lattner0cf24192010-06-28 20:05:43 +00004802//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004803// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004804//===----------------------------------------------------------------------===//
4805
4806namespace {
4807
John McCall12f23522016-04-04 18:33:08 +00004808class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004809public:
4810 enum ABIKind {
4811 AAPCS = 0,
Martin Storsjo502de222017-07-13 17:59:14 +00004812 DarwinPCS,
4813 Win64
Tim Northovera2ee4332014-03-29 15:09:45 +00004814 };
4815
4816private:
4817 ABIKind Kind;
4818
4819public:
John McCall12f23522016-04-04 18:33:08 +00004820 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4821 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004822
4823private:
4824 ABIKind getABIKind() const { return Kind; }
4825 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4826
4827 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004828 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004829 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4830 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4831 uint64_t Members) const override;
4832
Tim Northovera2ee4332014-03-29 15:09:45 +00004833 bool isIllegalVectorType(QualType Ty) const;
4834
David Blaikie1cbb9712014-11-14 19:09:44 +00004835 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004836 if (!getCXXABI().classifyReturnType(FI))
4837 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004838
Tim Northoverb047bfa2014-11-27 21:02:49 +00004839 for (auto &it : FI.arguments())
4840 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004841 }
4842
John McCall7f416cc2015-09-08 08:05:57 +00004843 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4844 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004845
John McCall7f416cc2015-09-08 08:05:57 +00004846 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4847 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004848
John McCall7f416cc2015-09-08 08:05:57 +00004849 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4850 QualType Ty) const override {
Martin Storsjo502de222017-07-13 17:59:14 +00004851 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4852 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4853 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
Tim Northovera2ee4332014-03-29 15:09:45 +00004854 }
John McCall12f23522016-04-04 18:33:08 +00004855
Martin Storsjo502de222017-07-13 17:59:14 +00004856 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4857 QualType Ty) const override;
4858
John McCall12f23522016-04-04 18:33:08 +00004859 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4860 ArrayRef<llvm::Type*> scalars,
4861 bool asReturnValue) const override {
4862 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4863 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004864 bool isSwiftErrorInRegister() const override {
4865 return true;
4866 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00004867
4868 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4869 unsigned elts) const override;
Tim Northovera2ee4332014-03-29 15:09:45 +00004870};
4871
Tim Northover573cbee2014-05-24 12:52:07 +00004872class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004873public:
Tim Northover573cbee2014-05-24 12:52:07 +00004874 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4875 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004876
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004877 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Saleem Abdulrasool40db4772017-02-11 23:03:13 +00004878 return "mov\tfp, fp\t\t# marker for objc_retainAutoreleaseReturnValue";
Tim Northovera2ee4332014-03-29 15:09:45 +00004879 }
4880
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004881 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4882 return 31;
4883 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004884
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004885 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004886};
Martin Storsjo1c8af272017-07-20 05:47:06 +00004887
4888class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4889public:
4890 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4891 : AArch64TargetCodeGenInfo(CGT, K) {}
4892
4893 void getDependentLibraryOption(llvm::StringRef Lib,
4894 llvm::SmallString<24> &Opt) const override {
4895 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4896 }
4897
4898 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4899 llvm::SmallString<32> &Opt) const override {
4900 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4901 }
4902};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004903}
Tim Northovera2ee4332014-03-29 15:09:45 +00004904
Tim Northoverb047bfa2014-11-27 21:02:49 +00004905ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004906 Ty = useFirstFieldIfTransparentUnion(Ty);
4907
Tim Northovera2ee4332014-03-29 15:09:45 +00004908 // Handle illegal vector types here.
4909 if (isIllegalVectorType(Ty)) {
4910 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004911 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004912 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004913 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4914 return ABIArgInfo::getDirect(ResType);
4915 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004916 if (Size <= 32) {
4917 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004918 return ABIArgInfo::getDirect(ResType);
4919 }
4920 if (Size == 64) {
4921 llvm::Type *ResType =
4922 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004923 return ABIArgInfo::getDirect(ResType);
4924 }
4925 if (Size == 128) {
4926 llvm::Type *ResType =
4927 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004928 return ABIArgInfo::getDirect(ResType);
4929 }
John McCall7f416cc2015-09-08 08:05:57 +00004930 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004931 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004932
4933 if (!isAggregateTypeForABI(Ty)) {
4934 // Treat an enum type as its underlying type.
4935 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4936 Ty = EnumTy->getDecl()->getIntegerType();
4937
Tim Northovera2ee4332014-03-29 15:09:45 +00004938 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4939 ? ABIArgInfo::getExtend()
4940 : ABIArgInfo::getDirect());
4941 }
4942
4943 // Structures with either a non-trivial destructor or a non-trivial
4944 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004945 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004946 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4947 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004948 }
4949
4950 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4951 // elsewhere for GNU compatibility.
Tim Northover23bcad22017-05-05 22:36:06 +00004952 uint64_t Size = getContext().getTypeSize(Ty);
4953 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
4954 if (IsEmpty || Size == 0) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004955 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4956 return ABIArgInfo::getIgnore();
4957
Tim Northover23bcad22017-05-05 22:36:06 +00004958 // GNU C mode. The only argument that gets ignored is an empty one with size
4959 // 0.
4960 if (IsEmpty && Size == 0)
4961 return ABIArgInfo::getIgnore();
Tim Northovera2ee4332014-03-29 15:09:45 +00004962 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4963 }
4964
4965 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004966 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004967 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004968 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004969 return ABIArgInfo::getDirect(
4970 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004971 }
4972
4973 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00004974 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004975 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4976 // same size and alignment.
4977 if (getTarget().isRenderScriptTarget()) {
4978 return coerceToIntArray(Ty, getContext(), getVMContext());
4979 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004980 unsigned Alignment = getContext().getTypeAlign(Ty);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00004981 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004982
Tim Northovera2ee4332014-03-29 15:09:45 +00004983 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4984 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004985 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004986 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4987 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4988 }
4989 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4990 }
4991
John McCall7f416cc2015-09-08 08:05:57 +00004992 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004993}
4994
Tim Northover573cbee2014-05-24 12:52:07 +00004995ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004996 if (RetTy->isVoidType())
4997 return ABIArgInfo::getIgnore();
4998
4999 // Large vector types should be returned via memory.
5000 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00005001 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005002
5003 if (!isAggregateTypeForABI(RetTy)) {
5004 // Treat an enum type as its underlying type.
5005 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5006 RetTy = EnumTy->getDecl()->getIntegerType();
5007
Tim Northover4dab6982014-04-18 13:46:08 +00005008 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5009 ? ABIArgInfo::getExtend()
5010 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005011 }
5012
Tim Northover23bcad22017-05-05 22:36:06 +00005013 uint64_t Size = getContext().getTypeSize(RetTy);
5014 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
Tim Northovera2ee4332014-03-29 15:09:45 +00005015 return ABIArgInfo::getIgnore();
5016
Craig Topper8a13c412014-05-21 05:09:00 +00005017 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005018 uint64_t Members = 0;
5019 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00005020 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5021 return ABIArgInfo::getDirect();
5022
5023 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
Tim Northovera2ee4332014-03-29 15:09:45 +00005024 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005025 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5026 // same size and alignment.
5027 if (getTarget().isRenderScriptTarget()) {
5028 return coerceToIntArray(RetTy, getContext(), getVMContext());
5029 }
Pete Cooper635b5092015-04-17 22:16:24 +00005030 unsigned Alignment = getContext().getTypeAlign(RetTy);
Davide Italiano7a3b69d2017-04-03 16:51:39 +00005031 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00005032
5033 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5034 // For aggregates with 16-byte alignment, we use i128.
5035 if (Alignment < 128 && Size == 128) {
5036 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5037 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5038 }
Tim Northovera2ee4332014-03-29 15:09:45 +00005039 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5040 }
5041
John McCall7f416cc2015-09-08 08:05:57 +00005042 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005043}
5044
Tim Northover573cbee2014-05-24 12:52:07 +00005045/// isIllegalVectorType - check whether the vector type is legal for AArch64.
5046bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00005047 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5048 // Check whether VT is legal.
5049 unsigned NumElements = VT->getNumElements();
5050 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00005051 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00005052 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00005053 return true;
5054 return Size != 64 && (Size != 128 || NumElements == 1);
5055 }
5056 return false;
5057}
5058
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005059bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5060 llvm::Type *eltTy,
5061 unsigned elts) const {
5062 if (!llvm::isPowerOf2_32(elts))
5063 return false;
5064 if (totalSize.getQuantity() != 8 &&
5065 (totalSize.getQuantity() != 16 || elts == 1))
5066 return false;
5067 return true;
5068}
5069
Reid Klecknere9f6a712014-10-31 17:10:41 +00005070bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5071 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5072 // point type or a short-vector type. This is the same as the 32-bit ABI,
5073 // but with the difference that any floating-point type is allowed,
5074 // including __fp16.
5075 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5076 if (BT->isFloatingPoint())
5077 return true;
5078 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5079 unsigned VecSize = getContext().getTypeSize(VT);
5080 if (VecSize == 64 || VecSize == 128)
5081 return true;
5082 }
5083 return false;
5084}
5085
5086bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5087 uint64_t Members) const {
5088 return Members <= 4;
5089}
5090
John McCall7f416cc2015-09-08 08:05:57 +00005091Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005092 QualType Ty,
5093 CodeGenFunction &CGF) const {
5094 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005095 bool IsIndirect = AI.isIndirect();
5096
Tim Northoverb047bfa2014-11-27 21:02:49 +00005097 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5098 if (IsIndirect)
5099 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5100 else if (AI.getCoerceToType())
5101 BaseTy = AI.getCoerceToType();
5102
5103 unsigned NumRegs = 1;
5104 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5105 BaseTy = ArrTy->getElementType();
5106 NumRegs = ArrTy->getNumElements();
5107 }
5108 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5109
Tim Northovera2ee4332014-03-29 15:09:45 +00005110 // The AArch64 va_list type and handling is specified in the Procedure Call
5111 // Standard, section B.4:
5112 //
5113 // struct {
5114 // void *__stack;
5115 // void *__gr_top;
5116 // void *__vr_top;
5117 // int __gr_offs;
5118 // int __vr_offs;
5119 // };
5120
5121 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5122 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5123 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5124 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005125
John McCall7f416cc2015-09-08 08:05:57 +00005126 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5127 CharUnits TyAlign = TyInfo.second;
5128
5129 Address reg_offs_p = Address::invalid();
5130 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005131 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005132 CharUnits reg_top_offset;
5133 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005134 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005135 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005136 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005137 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5138 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005139 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5140 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005141 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005142 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005143 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005144 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005145 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005146 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5147 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005148 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5149 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005150 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005151 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005152 }
5153
5154 //=======================================
5155 // Find out where argument was passed
5156 //=======================================
5157
5158 // If reg_offs >= 0 we're already using the stack for this type of
5159 // argument. We don't want to keep updating reg_offs (in case it overflows,
5160 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5161 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005162 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005163 UsingStack = CGF.Builder.CreateICmpSGE(
5164 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5165
5166 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5167
5168 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005169 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005170 CGF.EmitBlock(MaybeRegBlock);
5171
5172 // Integer arguments may need to correct register alignment (for example a
5173 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5174 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005175 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5176 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005177
5178 reg_offs = CGF.Builder.CreateAdd(
5179 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5180 "align_regoffs");
5181 reg_offs = CGF.Builder.CreateAnd(
5182 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5183 "aligned_regoffs");
5184 }
5185
5186 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005187 // The fact that this is done unconditionally reflects the fact that
5188 // allocating an argument to the stack also uses up all the remaining
5189 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005190 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005191 NewOffset = CGF.Builder.CreateAdd(
5192 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5193 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5194
5195 // Now we're in a position to decide whether this argument really was in
5196 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005197 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005198 InRegs = CGF.Builder.CreateICmpSLE(
5199 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5200
5201 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5202
5203 //=======================================
5204 // Argument was in registers
5205 //=======================================
5206
5207 // Now we emit the code for if the argument was originally passed in
5208 // registers. First start the appropriate block:
5209 CGF.EmitBlock(InRegBlock);
5210
John McCall7f416cc2015-09-08 08:05:57 +00005211 llvm::Value *reg_top = nullptr;
5212 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5213 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005214 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005215 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5216 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5217 Address RegAddr = Address::invalid();
5218 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005219
5220 if (IsIndirect) {
5221 // If it's been passed indirectly (actually a struct), whatever we find from
5222 // stored registers or on the stack will actually be a struct **.
5223 MemTy = llvm::PointerType::getUnqual(MemTy);
5224 }
5225
Craig Topper8a13c412014-05-21 05:09:00 +00005226 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005227 uint64_t NumMembers = 0;
5228 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005229 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005230 // Homogeneous aggregates passed in registers will have their elements split
5231 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5232 // qN+1, ...). We reload and store into a temporary local variable
5233 // contiguously.
5234 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005235 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005236 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5237 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005238 Address Tmp = CGF.CreateTempAlloca(HFATy,
5239 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005240
John McCall7f416cc2015-09-08 08:05:57 +00005241 // On big-endian platforms, the value will be right-aligned in its slot.
5242 int Offset = 0;
5243 if (CGF.CGM.getDataLayout().isBigEndian() &&
5244 BaseTyInfo.first.getQuantity() < 16)
5245 Offset = 16 - BaseTyInfo.first.getQuantity();
5246
Tim Northovera2ee4332014-03-29 15:09:45 +00005247 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005248 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5249 Address LoadAddr =
5250 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5251 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5252
5253 Address StoreAddr =
5254 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005255
5256 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5257 CGF.Builder.CreateStore(Elem, StoreAddr);
5258 }
5259
John McCall7f416cc2015-09-08 08:05:57 +00005260 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005261 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005262 // Otherwise the object is contiguous in memory.
5263
5264 // It might be right-aligned in its slot.
5265 CharUnits SlotSize = BaseAddr.getAlignment();
5266 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005267 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005268 TyInfo.first < SlotSize) {
5269 CharUnits Offset = SlotSize - TyInfo.first;
5270 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005271 }
5272
John McCall7f416cc2015-09-08 08:05:57 +00005273 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005274 }
5275
5276 CGF.EmitBranch(ContBlock);
5277
5278 //=======================================
5279 // Argument was on the stack
5280 //=======================================
5281 CGF.EmitBlock(OnStackBlock);
5282
John McCall7f416cc2015-09-08 08:05:57 +00005283 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5284 CharUnits::Zero(), "stack_p");
5285 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005286
John McCall7f416cc2015-09-08 08:05:57 +00005287 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005288 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005289 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5290 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005291
John McCall7f416cc2015-09-08 08:05:57 +00005292 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005293
John McCall7f416cc2015-09-08 08:05:57 +00005294 OnStackPtr = CGF.Builder.CreateAdd(
5295 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005296 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005297 OnStackPtr = CGF.Builder.CreateAnd(
5298 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005299 "align_stack");
5300
John McCall7f416cc2015-09-08 08:05:57 +00005301 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005302 }
John McCall7f416cc2015-09-08 08:05:57 +00005303 Address OnStackAddr(OnStackPtr,
5304 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005305
John McCall7f416cc2015-09-08 08:05:57 +00005306 // All stack slots are multiples of 8 bytes.
5307 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5308 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005309 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005310 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005311 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005312 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005313
John McCall7f416cc2015-09-08 08:05:57 +00005314 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005315 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005316 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005317
5318 // Write the new value of __stack for the next call to va_arg
5319 CGF.Builder.CreateStore(NewStack, stack_p);
5320
5321 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005322 TyInfo.first < StackSlotSize) {
5323 CharUnits Offset = StackSlotSize - TyInfo.first;
5324 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005325 }
5326
John McCall7f416cc2015-09-08 08:05:57 +00005327 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005328
5329 CGF.EmitBranch(ContBlock);
5330
5331 //=======================================
5332 // Tidy up
5333 //=======================================
5334 CGF.EmitBlock(ContBlock);
5335
John McCall7f416cc2015-09-08 08:05:57 +00005336 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5337 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005338
5339 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005340 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5341 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005342
5343 return ResAddr;
5344}
5345
John McCall7f416cc2015-09-08 08:05:57 +00005346Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5347 CodeGenFunction &CGF) const {
5348 // The backend's lowering doesn't support va_arg for aggregates or
5349 // illegal vector types. Lower VAArg here for these cases and use
5350 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005351 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005352 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005353
John McCall7f416cc2015-09-08 08:05:57 +00005354 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005355
John McCall7f416cc2015-09-08 08:05:57 +00005356 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005357 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005358 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5359 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5360 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005361 }
5362
John McCall7f416cc2015-09-08 08:05:57 +00005363 // The size of the actual thing passed, which might end up just
5364 // being a pointer for indirect types.
5365 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5366
5367 // Arguments bigger than 16 bytes which aren't homogeneous
5368 // aggregates should be passed indirectly.
5369 bool IsIndirect = false;
5370 if (TyInfo.first.getQuantity() > 16) {
5371 const Type *Base = nullptr;
5372 uint64_t Members = 0;
5373 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005374 }
5375
John McCall7f416cc2015-09-08 08:05:57 +00005376 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5377 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005378}
5379
Martin Storsjo502de222017-07-13 17:59:14 +00005380Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5381 QualType Ty) const {
5382 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5383 CGF.getContext().getTypeInfoInChars(Ty),
5384 CharUnits::fromQuantity(8),
5385 /*allowHigherAlign*/ false);
5386}
5387
Tim Northovera2ee4332014-03-29 15:09:45 +00005388//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005389// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005390//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005391
5392namespace {
5393
John McCall12f23522016-04-04 18:33:08 +00005394class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005395public:
5396 enum ABIKind {
5397 APCS = 0,
5398 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005399 AAPCS_VFP = 2,
5400 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005401 };
5402
5403private:
5404 ABIKind Kind;
5405
5406public:
John McCall12f23522016-04-04 18:33:08 +00005407 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5408 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005409 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005410 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005411
John McCall3480ef22011-08-30 01:42:09 +00005412 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005413 switch (getTarget().getTriple().getEnvironment()) {
5414 case llvm::Triple::Android:
5415 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005416 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005417 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005418 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005419 case llvm::Triple::MuslEABI:
5420 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005421 return true;
5422 default:
5423 return false;
5424 }
John McCall3480ef22011-08-30 01:42:09 +00005425 }
5426
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005427 bool isEABIHF() const {
5428 switch (getTarget().getTriple().getEnvironment()) {
5429 case llvm::Triple::EABIHF:
5430 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005431 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005432 return true;
5433 default:
5434 return false;
5435 }
5436 }
5437
Daniel Dunbar020daa92009-09-12 01:00:39 +00005438 ABIKind getABIKind() const { return Kind; }
5439
Tim Northovera484bc02013-10-01 14:34:25 +00005440private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005441 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005442 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005443 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005444
Reid Klecknere9f6a712014-10-31 17:10:41 +00005445 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5446 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5447 uint64_t Members) const override;
5448
Craig Topper4f12f102014-03-12 06:41:41 +00005449 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005450
John McCall7f416cc2015-09-08 08:05:57 +00005451 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5452 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005453
5454 llvm::CallingConv::ID getLLVMDefaultCC() const;
5455 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005456 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005457
5458 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5459 ArrayRef<llvm::Type*> scalars,
5460 bool asReturnValue) const override {
5461 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5462 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005463 bool isSwiftErrorInRegister() const override {
5464 return true;
5465 }
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005466 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5467 unsigned elts) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005468};
5469
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005470class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5471public:
Chris Lattner2b037972010-07-29 02:01:43 +00005472 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5473 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005474
John McCall3480ef22011-08-30 01:42:09 +00005475 const ARMABIInfo &getABIInfo() const {
5476 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5477 }
5478
Craig Topper4f12f102014-03-12 06:41:41 +00005479 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005480 return 13;
5481 }
Roman Divackyc1617352011-05-18 19:36:54 +00005482
Craig Topper4f12f102014-03-12 06:41:41 +00005483 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005484 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5485 }
5486
Roman Divackyc1617352011-05-18 19:36:54 +00005487 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005488 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005489 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005490
5491 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005492 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005493 return false;
5494 }
John McCall3480ef22011-08-30 01:42:09 +00005495
Craig Topper4f12f102014-03-12 06:41:41 +00005496 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005497 if (getABIInfo().isEABI()) return 88;
5498 return TargetCodeGenInfo::getSizeOfUnwindException();
5499 }
Tim Northovera484bc02013-10-01 14:34:25 +00005500
Eric Christopher162c91c2015-06-05 22:03:00 +00005501 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005502 CodeGen::CodeGenModule &CGM,
5503 ForDefinition_t IsForDefinition) const override {
5504 if (!IsForDefinition)
5505 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005506 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005507 if (!FD)
5508 return;
5509
5510 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5511 if (!Attr)
5512 return;
5513
5514 const char *Kind;
5515 switch (Attr->getInterrupt()) {
5516 case ARMInterruptAttr::Generic: Kind = ""; break;
5517 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5518 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5519 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5520 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5521 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5522 }
5523
5524 llvm::Function *Fn = cast<llvm::Function>(GV);
5525
5526 Fn->addFnAttr("interrupt", Kind);
5527
Tim Northover5627d392015-10-30 16:30:45 +00005528 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5529 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005530 return;
5531
5532 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5533 // however this is not necessarily true on taking any interrupt. Instruct
5534 // the backend to perform a realignment as part of the function prologue.
5535 llvm::AttrBuilder B;
5536 B.addStackAlignmentAttr(8);
Reid Kleckneree4930b2017-05-02 22:07:37 +00005537 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
Tim Northovera484bc02013-10-01 14:34:25 +00005538 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005539};
5540
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005541class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005542public:
5543 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5544 : ARMTargetCodeGenInfo(CGT, K) {}
5545
Eric Christopher162c91c2015-06-05 22:03:00 +00005546 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005547 CodeGen::CodeGenModule &CGM,
5548 ForDefinition_t IsForDefinition) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005549
5550 void getDependentLibraryOption(llvm::StringRef Lib,
5551 llvm::SmallString<24> &Opt) const override {
5552 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5553 }
5554
5555 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5556 llvm::SmallString<32> &Opt) const override {
5557 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5558 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005559};
5560
Eric Christopher162c91c2015-06-05 22:03:00 +00005561void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00005562 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM,
5563 ForDefinition_t IsForDefinition) const {
5564 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM, IsForDefinition);
5565 if (!IsForDefinition)
5566 return;
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005567 addStackProbeSizeTargetAttribute(D, GV, CGM);
5568}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005569}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005570
Chris Lattner22326a12010-07-29 02:31:05 +00005571void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005572 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005573 FI.getReturnInfo() =
5574 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005575
Tim Northoverbc784d12015-02-24 17:22:40 +00005576 for (auto &I : FI.arguments())
5577 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005578
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005579 // Always honor user-specified calling convention.
5580 if (FI.getCallingConvention() != llvm::CallingConv::C)
5581 return;
5582
John McCall882987f2013-02-28 19:01:20 +00005583 llvm::CallingConv::ID cc = getRuntimeCC();
5584 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005585 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005586}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005587
John McCall882987f2013-02-28 19:01:20 +00005588/// Return the default calling convention that LLVM will use.
5589llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5590 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005591 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005592 return llvm::CallingConv::ARM_AAPCS_VFP;
5593 else if (isEABI())
5594 return llvm::CallingConv::ARM_AAPCS;
5595 else
5596 return llvm::CallingConv::ARM_APCS;
5597}
5598
5599/// Return the calling convention that our ABI would like us to use
5600/// as the C calling convention.
5601llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005602 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005603 case APCS: return llvm::CallingConv::ARM_APCS;
5604 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5605 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005606 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005607 }
John McCall882987f2013-02-28 19:01:20 +00005608 llvm_unreachable("bad ABI kind");
5609}
5610
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005611void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005612 assert(getRuntimeCC() == llvm::CallingConv::C);
5613
5614 // Don't muddy up the IR with a ton of explicit annotations if
5615 // they'd just match what LLVM will infer from the triple.
5616 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5617 if (abiCC != getLLVMDefaultCC())
5618 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005619
Tim Northover5627d392015-10-30 16:30:45 +00005620 // AAPCS apparently requires runtime support functions to be soft-float, but
5621 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5622 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
Peter Smith32e26752017-07-27 10:43:53 +00005623
5624 // The Run-time ABI for the ARM Architecture section 4.1.2 requires
5625 // AEABI-complying FP helper functions to use the base AAPCS.
5626 // These AEABI functions are expanded in the ARM llvm backend, all the builtin
5627 // support functions emitted by clang such as the _Complex helpers follow the
5628 // abiCC.
5629 if (abiCC != getLLVMDefaultCC())
Tim Northover5627d392015-10-30 16:30:45 +00005630 BuiltinCC = abiCC;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005631}
5632
Tim Northoverbc784d12015-02-24 17:22:40 +00005633ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5634 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005635 // 6.1.2.1 The following argument types are VFP CPRCs:
5636 // A single-precision floating-point type (including promoted
5637 // half-precision types); A double-precision floating-point type;
5638 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5639 // with a Base Type of a single- or double-precision floating-point type,
5640 // 64-bit containerized vectors or 128-bit containerized vectors with one
5641 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005642 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005643
Reid Klecknerb1be6832014-11-15 01:41:41 +00005644 Ty = useFirstFieldIfTransparentUnion(Ty);
5645
Manman Renfef9e312012-10-16 19:18:39 +00005646 // Handle illegal vector types here.
5647 if (isIllegalVectorType(Ty)) {
5648 uint64_t Size = getContext().getTypeSize(Ty);
5649 if (Size <= 32) {
5650 llvm::Type *ResType =
5651 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005652 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005653 }
5654 if (Size == 64) {
5655 llvm::Type *ResType = llvm::VectorType::get(
5656 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005657 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005658 }
5659 if (Size == 128) {
5660 llvm::Type *ResType = llvm::VectorType::get(
5661 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005662 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005663 }
John McCall7f416cc2015-09-08 08:05:57 +00005664 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005665 }
5666
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005667 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5668 // unspecified. This is not done for OpenCL as it handles the half type
5669 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005670 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005671 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5672 llvm::Type::getFloatTy(getVMContext()) :
5673 llvm::Type::getInt32Ty(getVMContext());
5674 return ABIArgInfo::getDirect(ResType);
5675 }
5676
John McCalla1dee5302010-08-22 10:59:02 +00005677 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005678 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005679 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005680 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005681 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005682
Tim Northover5a1558e2014-11-07 22:30:50 +00005683 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5684 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005685 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005686
Oliver Stannard405bded2014-02-11 09:25:50 +00005687 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005688 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005689 }
Tim Northover1060eae2013-06-21 22:49:34 +00005690
Daniel Dunbar09d33622009-09-14 21:54:03 +00005691 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005692 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005693 return ABIArgInfo::getIgnore();
5694
Tim Northover5a1558e2014-11-07 22:30:50 +00005695 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005696 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5697 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005698 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005699 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005700 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005701 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005702 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005703 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005704 }
Tim Northover5627d392015-10-30 16:30:45 +00005705 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5706 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5707 // this convention even for a variadic function: the backend will use GPRs
5708 // if needed.
5709 const Type *Base = nullptr;
5710 uint64_t Members = 0;
5711 if (isHomogeneousAggregate(Ty, Base, Members)) {
5712 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5713 llvm::Type *Ty =
5714 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5715 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5716 }
5717 }
5718
5719 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5720 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5721 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5722 // bigger than 128-bits, they get placed in space allocated by the caller,
5723 // and a pointer is passed.
5724 return ABIArgInfo::getIndirect(
5725 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005726 }
5727
Manman Ren6c30e132012-08-13 21:23:55 +00005728 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005729 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5730 // most 8-byte. We realign the indirect argument if type alignment is bigger
5731 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005732 uint64_t ABIAlign = 4;
5733 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5734 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005735 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005736 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005737
Manman Ren8cd99812012-11-06 04:58:01 +00005738 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005739 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005740 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5741 /*ByVal=*/true,
5742 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005743 }
5744
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005745 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5746 // same size and alignment.
5747 if (getTarget().isRenderScriptTarget()) {
5748 return coerceToIntArray(Ty, getContext(), getVMContext());
5749 }
5750
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005751 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005752 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005753 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005754 // FIXME: Try to match the types of the arguments more accurately where
5755 // we can.
5756 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005757 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5758 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005759 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005760 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5761 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005762 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005763
Tim Northover5a1558e2014-11-07 22:30:50 +00005764 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005765}
5766
Chris Lattner458b2aa2010-07-29 02:16:43 +00005767static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005768 llvm::LLVMContext &VMContext) {
5769 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5770 // is called integer-like if its size is less than or equal to one word, and
5771 // the offset of each of its addressable sub-fields is zero.
5772
5773 uint64_t Size = Context.getTypeSize(Ty);
5774
5775 // Check that the type fits in a word.
5776 if (Size > 32)
5777 return false;
5778
5779 // FIXME: Handle vector types!
5780 if (Ty->isVectorType())
5781 return false;
5782
Daniel Dunbard53bac72009-09-14 02:20:34 +00005783 // Float types are never treated as "integer like".
5784 if (Ty->isRealFloatingType())
5785 return false;
5786
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005787 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005788 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005789 return true;
5790
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005791 // Small complex integer types are "integer like".
5792 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5793 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005794
5795 // Single element and zero sized arrays should be allowed, by the definition
5796 // above, but they are not.
5797
5798 // Otherwise, it must be a record type.
5799 const RecordType *RT = Ty->getAs<RecordType>();
5800 if (!RT) return false;
5801
5802 // Ignore records with flexible arrays.
5803 const RecordDecl *RD = RT->getDecl();
5804 if (RD->hasFlexibleArrayMember())
5805 return false;
5806
5807 // Check that all sub-fields are at offset 0, and are themselves "integer
5808 // like".
5809 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5810
5811 bool HadField = false;
5812 unsigned idx = 0;
5813 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5814 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005815 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005816
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005817 // Bit-fields are not addressable, we only need to verify they are "integer
5818 // like". We still have to disallow a subsequent non-bitfield, for example:
5819 // struct { int : 0; int x }
5820 // is non-integer like according to gcc.
5821 if (FD->isBitField()) {
5822 if (!RD->isUnion())
5823 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005824
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005825 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5826 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005827
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005828 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005829 }
5830
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005831 // Check if this field is at offset 0.
5832 if (Layout.getFieldOffset(idx) != 0)
5833 return false;
5834
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005835 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5836 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005837
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005838 // Only allow at most one field in a structure. This doesn't match the
5839 // wording above, but follows gcc in situations with a field following an
5840 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005841 if (!RD->isUnion()) {
5842 if (HadField)
5843 return false;
5844
5845 HadField = true;
5846 }
5847 }
5848
5849 return true;
5850}
5851
Oliver Stannard405bded2014-02-11 09:25:50 +00005852ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5853 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005854 bool IsEffectivelyAAPCS_VFP =
5855 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005856
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005857 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005858 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005859
Daniel Dunbar19964db2010-09-23 01:54:32 +00005860 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005861 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005862 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005863 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005864
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005865 // __fp16 gets returned as if it were an int or float, but with the top 16
5866 // bits unspecified. This is not done for OpenCL as it handles the half type
5867 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005868 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005869 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5870 llvm::Type::getFloatTy(getVMContext()) :
5871 llvm::Type::getInt32Ty(getVMContext());
5872 return ABIArgInfo::getDirect(ResType);
5873 }
5874
John McCalla1dee5302010-08-22 10:59:02 +00005875 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005876 // Treat an enum type as its underlying type.
5877 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5878 RetTy = EnumTy->getDecl()->getIntegerType();
5879
Tim Northover5a1558e2014-11-07 22:30:50 +00005880 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5881 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005882 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005883
5884 // Are we following APCS?
5885 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005886 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005887 return ABIArgInfo::getIgnore();
5888
Daniel Dunbareedf1512010-02-01 23:31:19 +00005889 // Complex types are all returned as packed integers.
5890 //
5891 // FIXME: Consider using 2 x vector types if the back end handles them
5892 // correctly.
5893 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005894 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5895 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005896
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005897 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005898 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005899 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005900 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005901 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005902 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005903 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005904 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5905 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005906 }
5907
5908 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005909 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005910 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005911
5912 // Otherwise this is an AAPCS variant.
5913
Chris Lattner458b2aa2010-07-29 02:16:43 +00005914 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005915 return ABIArgInfo::getIgnore();
5916
Bob Wilson1d9269a2011-11-02 04:51:36 +00005917 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005918 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005919 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005920 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005921 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005922 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005923 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005924 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005925 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005926 }
5927
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005928 // Aggregates <= 4 bytes are returned in r0; other aggregates
5929 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005930 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005931 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005932 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5933 // same size and alignment.
5934 if (getTarget().isRenderScriptTarget()) {
5935 return coerceToIntArray(RetTy, getContext(), getVMContext());
5936 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005937 if (getDataLayout().isBigEndian())
5938 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005939 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005940
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005941 // Return in the smallest viable integer type.
5942 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005943 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005944 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005945 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5946 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005947 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5948 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5949 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005950 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005951 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005952 }
5953
John McCall7f416cc2015-09-08 08:05:57 +00005954 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005955}
5956
Manman Renfef9e312012-10-16 19:18:39 +00005957/// isIllegalVector - check whether Ty is an illegal vector type.
5958bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005959 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5960 if (isAndroid()) {
5961 // Android shipped using Clang 3.1, which supported a slightly different
5962 // vector ABI. The primary differences were that 3-element vector types
5963 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5964 // accepts that legacy behavior for Android only.
5965 // Check whether VT is legal.
5966 unsigned NumElements = VT->getNumElements();
5967 // NumElements should be power of 2 or equal to 3.
5968 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5969 return true;
5970 } else {
5971 // Check whether VT is legal.
5972 unsigned NumElements = VT->getNumElements();
5973 uint64_t Size = getContext().getTypeSize(VT);
5974 // NumElements should be power of 2.
5975 if (!llvm::isPowerOf2_32(NumElements))
5976 return true;
5977 // Size should be greater than 32 bits.
5978 return Size <= 32;
5979 }
Manman Renfef9e312012-10-16 19:18:39 +00005980 }
5981 return false;
5982}
5983
Arnold Schwaighofer634e3202017-05-26 18:11:54 +00005984bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
5985 llvm::Type *eltTy,
5986 unsigned numElts) const {
5987 if (!llvm::isPowerOf2_32(numElts))
5988 return false;
5989 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
5990 if (size > 64)
5991 return false;
5992 if (vectorSize.getQuantity() != 8 &&
5993 (vectorSize.getQuantity() != 16 || numElts == 1))
5994 return false;
5995 return true;
5996}
5997
Reid Klecknere9f6a712014-10-31 17:10:41 +00005998bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5999 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6000 // double, or 64-bit or 128-bit vectors.
6001 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6002 if (BT->getKind() == BuiltinType::Float ||
6003 BT->getKind() == BuiltinType::Double ||
6004 BT->getKind() == BuiltinType::LongDouble)
6005 return true;
6006 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6007 unsigned VecSize = getContext().getTypeSize(VT);
6008 if (VecSize == 64 || VecSize == 128)
6009 return true;
6010 }
6011 return false;
6012}
6013
6014bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6015 uint64_t Members) const {
6016 return Members <= 4;
6017}
6018
John McCall7f416cc2015-09-08 08:05:57 +00006019Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6020 QualType Ty) const {
6021 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006022
John McCall7f416cc2015-09-08 08:05:57 +00006023 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00006024 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00006025 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6026 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6027 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00006028 }
6029
John McCall7f416cc2015-09-08 08:05:57 +00006030 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6031 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00006032
John McCall7f416cc2015-09-08 08:05:57 +00006033 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6034 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00006035 const Type *Base = nullptr;
6036 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00006037 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6038 IsIndirect = true;
6039
Tim Northover5627d392015-10-30 16:30:45 +00006040 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6041 // allocated by the caller.
6042 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6043 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6044 !isHomogeneousAggregate(Ty, Base, Members)) {
6045 IsIndirect = true;
6046
John McCall7f416cc2015-09-08 08:05:57 +00006047 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00006048 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6049 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00006050 // Our callers should be prepared to handle an under-aligned address.
6051 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6052 getABIKind() == ARMABIInfo::AAPCS) {
6053 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6054 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00006055 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6056 // ARMv7k allows type alignment up to 16 bytes.
6057 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6058 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00006059 } else {
6060 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00006061 }
John McCall7f416cc2015-09-08 08:05:57 +00006062 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00006063
John McCall7f416cc2015-09-08 08:05:57 +00006064 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6065 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006066}
6067
Chris Lattner0cf24192010-06-28 20:05:43 +00006068//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00006069// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006070//===----------------------------------------------------------------------===//
6071
6072namespace {
6073
Justin Holewinski83e96682012-05-24 17:43:12 +00006074class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006075public:
Justin Holewinski36837432013-03-30 14:38:24 +00006076 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006077
6078 ABIArgInfo classifyReturnType(QualType RetTy) const;
6079 ABIArgInfo classifyArgumentType(QualType Ty) const;
6080
Craig Topper4f12f102014-03-12 06:41:41 +00006081 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006082 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6083 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006084};
6085
Justin Holewinski83e96682012-05-24 17:43:12 +00006086class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006087public:
Justin Holewinski83e96682012-05-24 17:43:12 +00006088 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6089 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00006090
Eric Christopher162c91c2015-06-05 22:03:00 +00006091 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006092 CodeGen::CodeGenModule &M,
6093 ForDefinition_t IsForDefinition) const override;
6094
Justin Holewinski36837432013-03-30 14:38:24 +00006095private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00006096 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6097 // resulting MDNode to the nvvm.annotations MDNode.
6098 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006099};
6100
Justin Holewinski83e96682012-05-24 17:43:12 +00006101ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006102 if (RetTy->isVoidType())
6103 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006104
6105 // note: this is different from default ABI
6106 if (!RetTy->isScalarType())
6107 return ABIArgInfo::getDirect();
6108
6109 // Treat an enum type as its underlying type.
6110 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6111 RetTy = EnumTy->getDecl()->getIntegerType();
6112
6113 return (RetTy->isPromotableIntegerType() ?
6114 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006115}
6116
Justin Holewinski83e96682012-05-24 17:43:12 +00006117ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006118 // Treat an enum type as its underlying type.
6119 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6120 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006121
Eli Bendersky95338a02014-10-29 13:43:21 +00006122 // Return aggregates type as indirect by value
6123 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006124 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006125
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006126 return (Ty->isPromotableIntegerType() ?
6127 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006128}
6129
Justin Holewinski83e96682012-05-24 17:43:12 +00006130void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006131 if (!getCXXABI().classifyReturnType(FI))
6132 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006133 for (auto &I : FI.arguments())
6134 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006135
6136 // Always honor user-specified calling convention.
6137 if (FI.getCallingConvention() != llvm::CallingConv::C)
6138 return;
6139
John McCall882987f2013-02-28 19:01:20 +00006140 FI.setEffectiveCallingConvention(getRuntimeCC());
6141}
6142
John McCall7f416cc2015-09-08 08:05:57 +00006143Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6144 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006145 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006146}
6147
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006148void NVPTXTargetCodeGenInfo::setTargetAttributes(
6149 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6150 ForDefinition_t IsForDefinition) const {
6151 if (!IsForDefinition)
6152 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006153 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006154 if (!FD) return;
6155
6156 llvm::Function *F = cast<llvm::Function>(GV);
6157
6158 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006159 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006160 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006161 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006162 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006163 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006164 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6165 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006166 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006167 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006168 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006169 }
Justin Holewinski38031972011-10-05 17:58:44 +00006170
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006171 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006172 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006173 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006174 // __global__ functions cannot be called from the device, we do not
6175 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006176 if (FD->hasAttr<CUDAGlobalAttr>()) {
6177 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6178 addNVVMMetadata(F, "kernel", 1);
6179 }
Artem Belevich7093e402015-04-21 22:55:54 +00006180 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006181 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006182 llvm::APSInt MaxThreads(32);
6183 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6184 if (MaxThreads > 0)
6185 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6186
6187 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6188 // not specified in __launch_bounds__ or if the user specified a 0 value,
6189 // we don't have to add a PTX directive.
6190 if (Attr->getMinBlocks()) {
6191 llvm::APSInt MinBlocks(32);
6192 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6193 if (MinBlocks > 0)
6194 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6195 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006196 }
6197 }
Justin Holewinski38031972011-10-05 17:58:44 +00006198 }
6199}
6200
Eli Benderskye06a2c42014-04-15 16:57:05 +00006201void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6202 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006203 llvm::Module *M = F->getParent();
6204 llvm::LLVMContext &Ctx = M->getContext();
6205
6206 // Get "nvvm.annotations" metadata node
6207 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6208
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006209 llvm::Metadata *MDVals[] = {
6210 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6211 llvm::ConstantAsMetadata::get(
6212 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006213 // Append metadata to nvvm.annotations
6214 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6215}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006216}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006217
6218//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006219// SystemZ ABI Implementation
6220//===----------------------------------------------------------------------===//
6221
6222namespace {
6223
Bryan Chane3f1ed52016-04-28 13:56:43 +00006224class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006225 bool HasVector;
6226
Ulrich Weigand47445072013-05-06 16:26:41 +00006227public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006228 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006229 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006230
6231 bool isPromotableIntegerType(QualType Ty) const;
6232 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006233 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006234 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006235 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006236
6237 ABIArgInfo classifyReturnType(QualType RetTy) const;
6238 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6239
Craig Topper4f12f102014-03-12 06:41:41 +00006240 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006241 if (!getCXXABI().classifyReturnType(FI))
6242 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006243 for (auto &I : FI.arguments())
6244 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006245 }
6246
John McCall7f416cc2015-09-08 08:05:57 +00006247 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6248 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006249
6250 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6251 ArrayRef<llvm::Type*> scalars,
6252 bool asReturnValue) const override {
6253 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6254 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006255 bool isSwiftErrorInRegister() const override {
6256 return true;
6257 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006258};
6259
6260class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6261public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006262 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6263 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006264};
6265
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006266}
Ulrich Weigand47445072013-05-06 16:26:41 +00006267
6268bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6269 // Treat an enum type as its underlying type.
6270 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6271 Ty = EnumTy->getDecl()->getIntegerType();
6272
6273 // Promotable integer types are required to be promoted by the ABI.
6274 if (Ty->isPromotableIntegerType())
6275 return true;
6276
6277 // 32-bit values must also be promoted.
6278 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6279 switch (BT->getKind()) {
6280 case BuiltinType::Int:
6281 case BuiltinType::UInt:
6282 return true;
6283 default:
6284 return false;
6285 }
6286 return false;
6287}
6288
6289bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006290 return (Ty->isAnyComplexType() ||
6291 Ty->isVectorType() ||
6292 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006293}
6294
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006295bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6296 return (HasVector &&
6297 Ty->isVectorType() &&
6298 getContext().getTypeSize(Ty) <= 128);
6299}
6300
Ulrich Weigand47445072013-05-06 16:26:41 +00006301bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6302 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6303 switch (BT->getKind()) {
6304 case BuiltinType::Float:
6305 case BuiltinType::Double:
6306 return true;
6307 default:
6308 return false;
6309 }
6310
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006311 return false;
6312}
6313
6314QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006315 if (const RecordType *RT = Ty->getAsStructureType()) {
6316 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006317 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006318
6319 // If this is a C++ record, check the bases first.
6320 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006321 for (const auto &I : CXXRD->bases()) {
6322 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006323
6324 // Empty bases don't affect things either way.
6325 if (isEmptyRecord(getContext(), Base, true))
6326 continue;
6327
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006328 if (!Found.isNull())
6329 return Ty;
6330 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006331 }
6332
6333 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006334 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006335 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006336 // Unlike isSingleElementStruct(), empty structure and array fields
6337 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006338 if (getContext().getLangOpts().CPlusPlus &&
6339 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6340 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006341
6342 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006343 // Nested structures still do though.
6344 if (!Found.isNull())
6345 return Ty;
6346 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006347 }
6348
6349 // Unlike isSingleElementStruct(), trailing padding is allowed.
6350 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006351 if (!Found.isNull())
6352 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006353 }
6354
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006355 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006356}
6357
John McCall7f416cc2015-09-08 08:05:57 +00006358Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6359 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006360 // Assume that va_list type is correct; should be pointer to LLVM type:
6361 // struct {
6362 // i64 __gpr;
6363 // i64 __fpr;
6364 // i8 *__overflow_arg_area;
6365 // i8 *__reg_save_area;
6366 // };
6367
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006368 // Every non-vector argument occupies 8 bytes and is passed by preference
6369 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6370 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006371 Ty = getContext().getCanonicalType(Ty);
6372 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006373 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006374 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006375 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006376 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006377 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006378 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006379 CharUnits UnpaddedSize;
6380 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006381 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006382 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6383 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006384 } else {
6385 if (AI.getCoerceToType())
6386 ArgTy = AI.getCoerceToType();
6387 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006388 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006389 UnpaddedSize = TyInfo.first;
6390 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006391 }
John McCall7f416cc2015-09-08 08:05:57 +00006392 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6393 if (IsVector && UnpaddedSize > PaddedSize)
6394 PaddedSize = CharUnits::fromQuantity(16);
6395 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006396
John McCall7f416cc2015-09-08 08:05:57 +00006397 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006398
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006399 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006400 llvm::Value *PaddedSizeV =
6401 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006402
6403 if (IsVector) {
6404 // Work out the address of a vector argument on the stack.
6405 // Vector arguments are always passed in the high bits of a
6406 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006407 Address OverflowArgAreaPtr =
6408 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006409 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006410 Address OverflowArgArea =
6411 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6412 TyInfo.second);
6413 Address MemAddr =
6414 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006415
6416 // Update overflow_arg_area_ptr pointer
6417 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006418 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6419 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006420 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6421
6422 return MemAddr;
6423 }
6424
John McCall7f416cc2015-09-08 08:05:57 +00006425 assert(PaddedSize.getQuantity() == 8);
6426
6427 unsigned MaxRegs, RegCountField, RegSaveIndex;
6428 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006429 if (InFPRs) {
6430 MaxRegs = 4; // Maximum of 4 FPR arguments
6431 RegCountField = 1; // __fpr
6432 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006433 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006434 } else {
6435 MaxRegs = 5; // Maximum of 5 GPR arguments
6436 RegCountField = 0; // __gpr
6437 RegSaveIndex = 2; // save offset for r2
6438 RegPadding = Padding; // values are passed in the low bits of a GPR
6439 }
6440
John McCall7f416cc2015-09-08 08:05:57 +00006441 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6442 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6443 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006444 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006445 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6446 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006447 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006448
6449 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6450 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6451 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6452 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6453
6454 // Emit code to load the value if it was passed in registers.
6455 CGF.EmitBlock(InRegBlock);
6456
6457 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006458 llvm::Value *ScaledRegCount =
6459 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6460 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006461 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6462 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006463 llvm::Value *RegOffset =
6464 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006465 Address RegSaveAreaPtr =
6466 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6467 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006468 llvm::Value *RegSaveArea =
6469 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006470 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6471 "raw_reg_addr"),
6472 PaddedSize);
6473 Address RegAddr =
6474 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006475
6476 // Update the register count
6477 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6478 llvm::Value *NewRegCount =
6479 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6480 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6481 CGF.EmitBranch(ContBlock);
6482
6483 // Emit code to load the value if it was passed in memory.
6484 CGF.EmitBlock(InMemBlock);
6485
6486 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006487 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6488 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6489 Address OverflowArgArea =
6490 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6491 PaddedSize);
6492 Address RawMemAddr =
6493 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6494 Address MemAddr =
6495 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006496
6497 // Update overflow_arg_area_ptr pointer
6498 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006499 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6500 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006501 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6502 CGF.EmitBranch(ContBlock);
6503
6504 // Return the appropriate result.
6505 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006506 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6507 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006508
6509 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006510 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6511 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006512
6513 return ResAddr;
6514}
6515
Ulrich Weigand47445072013-05-06 16:26:41 +00006516ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6517 if (RetTy->isVoidType())
6518 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006519 if (isVectorArgumentType(RetTy))
6520 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006521 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006522 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006523 return (isPromotableIntegerType(RetTy) ?
6524 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6525}
6526
6527ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6528 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006529 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006530 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006531
6532 // Integers and enums are extended to full register width.
6533 if (isPromotableIntegerType(Ty))
6534 return ABIArgInfo::getExtend();
6535
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006536 // Handle vector types and vector-like structure types. Note that
6537 // as opposed to float-like structure types, we do not allow any
6538 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006539 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006540 QualType SingleElementTy = GetSingleElementType(Ty);
6541 if (isVectorArgumentType(SingleElementTy) &&
6542 getContext().getTypeSize(SingleElementTy) == Size)
6543 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6544
6545 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006546 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006547 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006548
6549 // Handle small structures.
6550 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6551 // Structures with flexible arrays have variable length, so really
6552 // fail the size test above.
6553 const RecordDecl *RD = RT->getDecl();
6554 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006555 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006556
6557 // The structure is passed as an unextended integer, a float, or a double.
6558 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006559 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006560 assert(Size == 32 || Size == 64);
6561 if (Size == 32)
6562 PassTy = llvm::Type::getFloatTy(getVMContext());
6563 else
6564 PassTy = llvm::Type::getDoubleTy(getVMContext());
6565 } else
6566 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6567 return ABIArgInfo::getDirect(PassTy);
6568 }
6569
6570 // Non-structure compounds are passed indirectly.
6571 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006572 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006573
Craig Topper8a13c412014-05-21 05:09:00 +00006574 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006575}
6576
6577//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006578// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006579//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006580
6581namespace {
6582
6583class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6584public:
Chris Lattner2b037972010-07-29 02:01:43 +00006585 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6586 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006587 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006588 CodeGen::CodeGenModule &M,
6589 ForDefinition_t IsForDefinition) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006590};
6591
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006592}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006593
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006594void MSP430TargetCodeGenInfo::setTargetAttributes(
6595 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
6596 ForDefinition_t IsForDefinition) const {
6597 if (!IsForDefinition)
6598 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006599 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006600 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6601 // Handle 'interrupt' attribute:
6602 llvm::Function *F = cast<llvm::Function>(GV);
6603
6604 // Step 1: Set ISR calling convention.
6605 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6606
6607 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006608 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006609
6610 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006611 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006612 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6613 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006614 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006615 }
6616}
6617
Chris Lattner0cf24192010-06-28 20:05:43 +00006618//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006619// MIPS ABI Implementation. This works for both little-endian and
6620// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006621//===----------------------------------------------------------------------===//
6622
John McCall943fae92010-05-27 06:19:26 +00006623namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006624class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006625 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006626 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6627 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006628 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006629 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006630 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006631 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006632public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006633 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006634 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006635 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006636
6637 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006638 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006639 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006640 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6641 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006642 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006643};
6644
John McCall943fae92010-05-27 06:19:26 +00006645class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006646 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006647public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006648 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6649 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006650 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006651
Craig Topper4f12f102014-03-12 06:41:41 +00006652 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006653 return 29;
6654 }
6655
Eric Christopher162c91c2015-06-05 22:03:00 +00006656 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006657 CodeGen::CodeGenModule &CGM,
6658 ForDefinition_t IsForDefinition) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006659 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006660 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006661 llvm::Function *Fn = cast<llvm::Function>(GV);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00006662
6663 if (FD->hasAttr<MipsLongCallAttr>())
6664 Fn->addFnAttr("long-call");
6665 else if (FD->hasAttr<MipsShortCallAttr>())
6666 Fn->addFnAttr("short-call");
6667
6668 // Other attributes do not have a meaning for declarations.
6669 if (!IsForDefinition)
6670 return;
6671
Reed Kotler3d5966f2013-03-13 20:40:30 +00006672 if (FD->hasAttr<Mips16Attr>()) {
6673 Fn->addFnAttr("mips16");
6674 }
6675 else if (FD->hasAttr<NoMips16Attr>()) {
6676 Fn->addFnAttr("nomips16");
6677 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006678
Simon Atanasyan2c87f532017-05-22 12:47:43 +00006679 if (FD->hasAttr<MicroMipsAttr>())
6680 Fn->addFnAttr("micromips");
6681 else if (FD->hasAttr<NoMicroMipsAttr>())
6682 Fn->addFnAttr("nomicromips");
6683
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006684 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6685 if (!Attr)
6686 return;
6687
6688 const char *Kind;
6689 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006690 case MipsInterruptAttr::eic: Kind = "eic"; break;
6691 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6692 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6693 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6694 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6695 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6696 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6697 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6698 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6699 }
6700
6701 Fn->addFnAttr("interrupt", Kind);
6702
Reed Kotler373feca2013-01-16 17:10:28 +00006703 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006704
John McCall943fae92010-05-27 06:19:26 +00006705 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006706 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006707
Craig Topper4f12f102014-03-12 06:41:41 +00006708 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006709 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006710 }
John McCall943fae92010-05-27 06:19:26 +00006711};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006712}
John McCall943fae92010-05-27 06:19:26 +00006713
Eric Christopher7565e0d2015-05-29 23:09:49 +00006714void MipsABIInfo::CoerceToIntArgs(
6715 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006716 llvm::IntegerType *IntTy =
6717 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006718
6719 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6720 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6721 ArgList.push_back(IntTy);
6722
6723 // If necessary, add one more integer type to ArgList.
6724 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6725
6726 if (R)
6727 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006728}
6729
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006730// In N32/64, an aligned double precision floating point field is passed in
6731// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006732llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006733 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6734
6735 if (IsO32) {
6736 CoerceToIntArgs(TySize, ArgList);
6737 return llvm::StructType::get(getVMContext(), ArgList);
6738 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006739
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006740 if (Ty->isComplexType())
6741 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006742
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006743 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006744
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006745 // Unions/vectors are passed in integer registers.
6746 if (!RT || !RT->isStructureOrClassType()) {
6747 CoerceToIntArgs(TySize, ArgList);
6748 return llvm::StructType::get(getVMContext(), ArgList);
6749 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006750
6751 const RecordDecl *RD = RT->getDecl();
6752 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006753 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006754
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006755 uint64_t LastOffset = 0;
6756 unsigned idx = 0;
6757 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6758
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006759 // Iterate over fields in the struct/class and check if there are any aligned
6760 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006761 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6762 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006763 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006764 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6765
6766 if (!BT || BT->getKind() != BuiltinType::Double)
6767 continue;
6768
6769 uint64_t Offset = Layout.getFieldOffset(idx);
6770 if (Offset % 64) // Ignore doubles that are not aligned.
6771 continue;
6772
6773 // Add ((Offset - LastOffset) / 64) args of type i64.
6774 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6775 ArgList.push_back(I64);
6776
6777 // Add double type.
6778 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6779 LastOffset = Offset + 64;
6780 }
6781
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006782 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6783 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006784
6785 return llvm::StructType::get(getVMContext(), ArgList);
6786}
6787
Akira Hatanakaddd66342013-10-29 18:41:15 +00006788llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6789 uint64_t Offset) const {
6790 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006791 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006792
Akira Hatanakaddd66342013-10-29 18:41:15 +00006793 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006794}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006795
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006796ABIArgInfo
6797MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006798 Ty = useFirstFieldIfTransparentUnion(Ty);
6799
Akira Hatanaka1632af62012-01-09 19:31:25 +00006800 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006801 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006802 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006803
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006804 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6805 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006806 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6807 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006808
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006809 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006810 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006811 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006812 return ABIArgInfo::getIgnore();
6813
Mark Lacey3825e832013-10-06 01:33:34 +00006814 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006815 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006816 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006817 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006818
Petar Jovanovic6f4cdb82017-05-10 14:28:18 +00006819 // Use indirect if the aggregate cannot fit into registers for
6820 // passing arguments according to the ABI
6821 unsigned Threshold = IsO32 ? 16 : 64;
6822
6823 if(getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(Threshold))
6824 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align), true,
6825 getContext().getTypeAlign(Ty) / 8 > Align);
6826
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006827 // If we have reached here, aggregates are passed directly by coercing to
6828 // another structure type. Padding is inserted if the offset of the
6829 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006830 ABIArgInfo ArgInfo =
6831 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6832 getPaddingType(OrigOffset, CurrOffset));
6833 ArgInfo.setInReg(true);
6834 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006835 }
6836
6837 // Treat an enum type as its underlying type.
6838 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6839 Ty = EnumTy->getDecl()->getIntegerType();
6840
Daniel Sanders5b445b32014-10-24 14:42:42 +00006841 // All integral types are promoted to the GPR width.
6842 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006843 return ABIArgInfo::getExtend();
6844
Akira Hatanakaddd66342013-10-29 18:41:15 +00006845 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006846 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006847}
6848
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006849llvm::Type*
6850MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006851 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006852 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006853
Akira Hatanakab6f74432012-02-09 18:49:26 +00006854 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006855 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006856 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6857 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006858
Akira Hatanakab6f74432012-02-09 18:49:26 +00006859 // N32/64 returns struct/classes in floating point registers if the
6860 // following conditions are met:
6861 // 1. The size of the struct/class is no larger than 128-bit.
6862 // 2. The struct/class has one or two fields all of which are floating
6863 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006864 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006865 //
6866 // Any other composite results are returned in integer registers.
6867 //
6868 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6869 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6870 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006871 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006872
Akira Hatanakab6f74432012-02-09 18:49:26 +00006873 if (!BT || !BT->isFloatingPoint())
6874 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006875
David Blaikie2d7c57e2012-04-30 02:36:29 +00006876 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006877 }
6878
6879 if (b == e)
6880 return llvm::StructType::get(getVMContext(), RTList,
6881 RD->hasAttr<PackedAttr>());
6882
6883 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006884 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006885 }
6886
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006887 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006888 return llvm::StructType::get(getVMContext(), RTList);
6889}
6890
Akira Hatanakab579fe52011-06-02 00:09:17 +00006891ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006892 uint64_t Size = getContext().getTypeSize(RetTy);
6893
Daniel Sandersed39f582014-09-04 13:28:14 +00006894 if (RetTy->isVoidType())
6895 return ABIArgInfo::getIgnore();
6896
6897 // O32 doesn't treat zero-sized structs differently from other structs.
6898 // However, N32/N64 ignores zero sized return values.
6899 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006900 return ABIArgInfo::getIgnore();
6901
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006902 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006903 if (Size <= 128) {
6904 if (RetTy->isAnyComplexType())
6905 return ABIArgInfo::getDirect();
6906
Daniel Sanderse5018b62014-09-04 15:05:39 +00006907 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006908 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006909 if (!IsO32 ||
6910 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6911 ABIArgInfo ArgInfo =
6912 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6913 ArgInfo.setInReg(true);
6914 return ArgInfo;
6915 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006916 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006917
John McCall7f416cc2015-09-08 08:05:57 +00006918 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006919 }
6920
6921 // Treat an enum type as its underlying type.
6922 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6923 RetTy = EnumTy->getDecl()->getIntegerType();
6924
6925 return (RetTy->isPromotableIntegerType() ?
6926 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6927}
6928
6929void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006930 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006931 if (!getCXXABI().classifyReturnType(FI))
6932 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006933
Eric Christopher7565e0d2015-05-29 23:09:49 +00006934 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006935 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006936
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006937 for (auto &I : FI.arguments())
6938 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006939}
6940
John McCall7f416cc2015-09-08 08:05:57 +00006941Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6942 QualType OrigTy) const {
6943 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006944
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006945 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6946 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006947 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006948 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006949 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006950 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006951 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006952 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006953 DidPromote = true;
6954 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6955 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006956 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006957
John McCall7f416cc2015-09-08 08:05:57 +00006958 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006959
John McCall7f416cc2015-09-08 08:05:57 +00006960 // The alignment of things in the argument area is never larger than
6961 // StackAlignInBytes.
6962 TyInfo.second =
6963 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6964
6965 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6966 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6967
6968 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6969 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6970
6971
6972 // If there was a promotion, "unpromote" into a temporary.
6973 // TODO: can we just use a pointer into a subset of the original slot?
6974 if (DidPromote) {
6975 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6976 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6977
6978 // Truncate down to the right width.
6979 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6980 : CGF.IntPtrTy);
6981 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6982 if (OrigTy->isPointerType())
6983 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6984
6985 CGF.Builder.CreateStore(V, Temp);
6986 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006987 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006988
John McCall7f416cc2015-09-08 08:05:57 +00006989 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006990}
6991
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006992bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6993 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006994
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006995 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6996 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6997 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006998
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006999 return false;
7000}
7001
John McCall943fae92010-05-27 06:19:26 +00007002bool
7003MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7004 llvm::Value *Address) const {
7005 // This information comes from gcc's implementation, which seems to
7006 // as canonical as it gets.
7007
John McCall943fae92010-05-27 06:19:26 +00007008 // Everything on MIPS is 4 bytes. Double-precision FP registers
7009 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007010 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00007011
7012 // 0-31 are the general purpose registers, $0 - $31.
7013 // 32-63 are the floating-point registers, $f0 - $f31.
7014 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7015 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00007016 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00007017
7018 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7019 // They are one bit wide and ignored here.
7020
7021 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7022 // (coprocessor 1 is the FP unit)
7023 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7024 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7025 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00007026 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00007027 return false;
7028}
7029
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007030//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00007031// AVR ABI Implementation.
7032//===----------------------------------------------------------------------===//
7033
7034namespace {
7035class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7036public:
7037 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7038 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7039
7040 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007041 CodeGen::CodeGenModule &CGM,
7042 ForDefinition_t IsForDefinition) const override {
7043 if (!IsForDefinition)
7044 return;
Dylan McKaye8232d72017-02-08 05:09:26 +00007045 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7046 if (!FD) return;
7047 auto *Fn = cast<llvm::Function>(GV);
7048
7049 if (FD->getAttr<AVRInterruptAttr>())
7050 Fn->addFnAttr("interrupt");
7051
7052 if (FD->getAttr<AVRSignalAttr>())
7053 Fn->addFnAttr("signal");
7054 }
7055};
7056}
7057
7058//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007059// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00007060// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007061// handling.
7062//===----------------------------------------------------------------------===//
7063
7064namespace {
7065
7066class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7067public:
7068 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7069 : DefaultTargetCodeGenInfo(CGT) {}
7070
Eric Christopher162c91c2015-06-05 22:03:00 +00007071 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007072 CodeGen::CodeGenModule &M,
7073 ForDefinition_t IsForDefinition) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007074};
7075
Eric Christopher162c91c2015-06-05 22:03:00 +00007076void TCETargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007077 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7078 ForDefinition_t IsForDefinition) const {
7079 if (!IsForDefinition)
7080 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007081 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007082 if (!FD) return;
7083
7084 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007085
David Blaikiebbafb8a2012-03-11 07:00:24 +00007086 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007087 if (FD->hasAttr<OpenCLKernelAttr>()) {
7088 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00007089 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00007090 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7091 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007092 // Convert the reqd_work_group_size() attributes to metadata.
7093 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00007094 llvm::NamedMDNode *OpenCLMetadata =
7095 M.getModule().getOrInsertNamedMetadata(
7096 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007097
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007098 SmallVector<llvm::Metadata *, 5> Operands;
7099 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007100
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007101 Operands.push_back(
7102 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7103 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7104 Operands.push_back(
7105 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7106 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7107 Operands.push_back(
7108 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7109 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007110
Eric Christopher7565e0d2015-05-29 23:09:49 +00007111 // Add a boolean constant operand for "required" (true) or "hint"
7112 // (false) for implementing the work_group_size_hint attr later.
7113 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007114 Operands.push_back(
7115 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007116 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7117 }
7118 }
7119 }
7120}
7121
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007122}
John McCall943fae92010-05-27 06:19:26 +00007123
Tony Linthicum76329bf2011-12-12 21:14:55 +00007124//===----------------------------------------------------------------------===//
7125// Hexagon ABI Implementation
7126//===----------------------------------------------------------------------===//
7127
7128namespace {
7129
7130class HexagonABIInfo : public ABIInfo {
7131
7132
7133public:
7134 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7135
7136private:
7137
7138 ABIArgInfo classifyReturnType(QualType RetTy) const;
7139 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7140
Craig Topper4f12f102014-03-12 06:41:41 +00007141 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007142
John McCall7f416cc2015-09-08 08:05:57 +00007143 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7144 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007145};
7146
7147class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7148public:
7149 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7150 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7151
Craig Topper4f12f102014-03-12 06:41:41 +00007152 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007153 return 29;
7154 }
7155};
7156
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007157}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007158
7159void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007160 if (!getCXXABI().classifyReturnType(FI))
7161 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007162 for (auto &I : FI.arguments())
7163 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007164}
7165
7166ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7167 if (!isAggregateTypeForABI(Ty)) {
7168 // Treat an enum type as its underlying type.
7169 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7170 Ty = EnumTy->getDecl()->getIntegerType();
7171
7172 return (Ty->isPromotableIntegerType() ?
7173 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7174 }
7175
Krzysztof Parzyszek408b2722017-05-12 13:18:07 +00007176 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7177 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7178
Tony Linthicum76329bf2011-12-12 21:14:55 +00007179 // Ignore empty records.
7180 if (isEmptyRecord(getContext(), Ty, true))
7181 return ABIArgInfo::getIgnore();
7182
Tony Linthicum76329bf2011-12-12 21:14:55 +00007183 uint64_t Size = getContext().getTypeSize(Ty);
7184 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007185 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007186 // Pass in the smallest viable integer type.
7187 else if (Size > 32)
7188 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7189 else if (Size > 16)
7190 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7191 else if (Size > 8)
7192 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7193 else
7194 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7195}
7196
7197ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7198 if (RetTy->isVoidType())
7199 return ABIArgInfo::getIgnore();
7200
7201 // Large vector types should be returned via memory.
7202 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007203 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007204
7205 if (!isAggregateTypeForABI(RetTy)) {
7206 // Treat an enum type as its underlying type.
7207 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7208 RetTy = EnumTy->getDecl()->getIntegerType();
7209
7210 return (RetTy->isPromotableIntegerType() ?
7211 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7212 }
7213
Tony Linthicum76329bf2011-12-12 21:14:55 +00007214 if (isEmptyRecord(getContext(), RetTy, true))
7215 return ABIArgInfo::getIgnore();
7216
7217 // Aggregates <= 8 bytes are returned in r0; other aggregates
7218 // are returned indirectly.
7219 uint64_t Size = getContext().getTypeSize(RetTy);
7220 if (Size <= 64) {
7221 // Return in the smallest viable integer type.
7222 if (Size <= 8)
7223 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7224 if (Size <= 16)
7225 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7226 if (Size <= 32)
7227 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7228 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7229 }
7230
John McCall7f416cc2015-09-08 08:05:57 +00007231 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007232}
7233
John McCall7f416cc2015-09-08 08:05:57 +00007234Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7235 QualType Ty) const {
7236 // FIXME: Someone needs to audit that this handle alignment correctly.
7237 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7238 getContext().getTypeInfoInChars(Ty),
7239 CharUnits::fromQuantity(4),
7240 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007241}
7242
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007243//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007244// Lanai ABI Implementation
7245//===----------------------------------------------------------------------===//
7246
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007247namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007248class LanaiABIInfo : public DefaultABIInfo {
7249public:
7250 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7251
7252 bool shouldUseInReg(QualType Ty, CCState &State) const;
7253
7254 void computeInfo(CGFunctionInfo &FI) const override {
7255 CCState State(FI.getCallingConvention());
7256 // Lanai uses 4 registers to pass arguments unless the function has the
7257 // regparm attribute set.
7258 if (FI.getHasRegParm()) {
7259 State.FreeRegs = FI.getRegParm();
7260 } else {
7261 State.FreeRegs = 4;
7262 }
7263
7264 if (!getCXXABI().classifyReturnType(FI))
7265 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7266 for (auto &I : FI.arguments())
7267 I.info = classifyArgumentType(I.type, State);
7268 }
7269
Jacques Pienaare74d9132016-04-26 00:09:29 +00007270 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007271 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7272};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007273} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007274
7275bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7276 unsigned Size = getContext().getTypeSize(Ty);
7277 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7278
7279 if (SizeInRegs == 0)
7280 return false;
7281
7282 if (SizeInRegs > State.FreeRegs) {
7283 State.FreeRegs = 0;
7284 return false;
7285 }
7286
7287 State.FreeRegs -= SizeInRegs;
7288
7289 return true;
7290}
7291
Jacques Pienaare74d9132016-04-26 00:09:29 +00007292ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7293 CCState &State) const {
7294 if (!ByVal) {
7295 if (State.FreeRegs) {
7296 --State.FreeRegs; // Non-byval indirects just use one pointer.
7297 return getNaturalAlignIndirectInReg(Ty);
7298 }
7299 return getNaturalAlignIndirect(Ty, false);
7300 }
7301
7302 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007303 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007304 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7305 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7306 /*Realign=*/TypeAlign >
7307 MinABIStackAlignInBytes);
7308}
7309
Jacques Pienaard964cc22016-03-28 21:02:54 +00007310ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7311 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007312 // Check with the C++ ABI first.
7313 const RecordType *RT = Ty->getAs<RecordType>();
7314 if (RT) {
7315 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7316 if (RAA == CGCXXABI::RAA_Indirect) {
7317 return getIndirectResult(Ty, /*ByVal=*/false, State);
7318 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7319 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7320 }
7321 }
7322
7323 if (isAggregateTypeForABI(Ty)) {
7324 // Structures with flexible arrays are always indirect.
7325 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7326 return getIndirectResult(Ty, /*ByVal=*/true, State);
7327
7328 // Ignore empty structs/unions.
7329 if (isEmptyRecord(getContext(), Ty, true))
7330 return ABIArgInfo::getIgnore();
7331
7332 llvm::LLVMContext &LLVMContext = getVMContext();
7333 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7334 if (SizeInRegs <= State.FreeRegs) {
7335 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7336 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7337 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7338 State.FreeRegs -= SizeInRegs;
7339 return ABIArgInfo::getDirectInReg(Result);
7340 } else {
7341 State.FreeRegs = 0;
7342 }
7343 return getIndirectResult(Ty, true, State);
7344 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007345
7346 // Treat an enum type as its underlying type.
7347 if (const auto *EnumTy = Ty->getAs<EnumType>())
7348 Ty = EnumTy->getDecl()->getIntegerType();
7349
Jacques Pienaare74d9132016-04-26 00:09:29 +00007350 bool InReg = shouldUseInReg(Ty, State);
7351 if (Ty->isPromotableIntegerType()) {
7352 if (InReg)
7353 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007354 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007355 }
7356 if (InReg)
7357 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007358 return ABIArgInfo::getDirect();
7359}
7360
7361namespace {
7362class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7363public:
7364 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7365 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7366};
7367}
7368
7369//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007370// AMDGPU ABI Implementation
7371//===----------------------------------------------------------------------===//
7372
7373namespace {
7374
Matt Arsenault88d7da02016-08-22 19:25:59 +00007375class AMDGPUABIInfo final : public DefaultABIInfo {
7376public:
7377 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7378
7379private:
7380 ABIArgInfo classifyArgumentType(QualType Ty) const;
7381
7382 void computeInfo(CGFunctionInfo &FI) const override;
7383};
7384
7385void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7386 if (!getCXXABI().classifyReturnType(FI))
7387 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7388
7389 unsigned CC = FI.getCallingConvention();
7390 for (auto &Arg : FI.arguments())
7391 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7392 Arg.info = classifyArgumentType(Arg.type);
7393 else
7394 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7395}
7396
7397/// \brief Classify argument of given type \p Ty.
7398ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7399 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7400 if (!StrTy) {
7401 return DefaultABIInfo::classifyArgumentType(Ty);
7402 }
7403
7404 // Coerce single element structs to its element.
7405 if (StrTy->getNumElements() == 1) {
7406 return ABIArgInfo::getDirect();
7407 }
7408
7409 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7410 // individual elements, which confuses the Clover OpenCL backend; therefore we
7411 // have to set it to false here. Other args of getDirect() are just defaults.
7412 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7413}
7414
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007415class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7416public:
7417 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007418 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007419 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007420 CodeGen::CodeGenModule &M,
7421 ForDefinition_t IsForDefinition) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007422 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007423
Yaxun Liu402804b2016-12-15 08:09:08 +00007424 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7425 llvm::PointerType *T, QualType QT) const override;
Yaxun Liu6d96f1632017-05-18 18:51:09 +00007426
7427 unsigned getASTAllocaAddressSpace() const override {
7428 return LangAS::FirstTargetAddressSpace +
7429 getABIInfo().getDataLayout().getAllocaAddrSpace();
7430 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00007431 unsigned getGlobalVarAddressSpace(CodeGenModule &CGM,
7432 const VarDecl *D) const override;
Yaxun Liu402804b2016-12-15 08:09:08 +00007433};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007434}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007435
Eric Christopher162c91c2015-06-05 22:03:00 +00007436void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Simon Atanasyan1a116db2017-07-20 20:34:18 +00007437 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M,
7438 ForDefinition_t IsForDefinition) const {
7439 if (!IsForDefinition)
7440 return;
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007441 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007442 if (!FD)
7443 return;
7444
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007445 llvm::Function *F = cast<llvm::Function>(GV);
7446
Stanislav Mekhanoshin921a4232017-04-06 18:15:44 +00007447 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7448 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7449 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7450 if (ReqdWGS || FlatWGS) {
7451 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7452 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7453 if (ReqdWGS && Min == 0 && Max == 0)
7454 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007455
7456 if (Min != 0) {
7457 assert(Min <= Max && "Min must be less than or equal Max");
7458
7459 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7460 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7461 } else
7462 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007463 }
7464
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007465 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7466 unsigned Min = Attr->getMin();
7467 unsigned Max = Attr->getMax();
7468
7469 if (Min != 0) {
7470 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7471
7472 std::string AttrVal = llvm::utostr(Min);
7473 if (Max != 0)
7474 AttrVal = AttrVal + "," + llvm::utostr(Max);
7475 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7476 } else
7477 assert(Max == 0 && "Max must be zero");
7478 }
7479
7480 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007481 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007482
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007483 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007484 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7485 }
7486
7487 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7488 uint32_t NumVGPR = Attr->getNumVGPR();
7489
7490 if (NumVGPR != 0)
7491 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007492 }
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007493}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007494
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007495unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7496 return llvm::CallingConv::AMDGPU_KERNEL;
7497}
7498
Yaxun Liu402804b2016-12-15 08:09:08 +00007499// Currently LLVM assumes null pointers always have value 0,
7500// which results in incorrectly transformed IR. Therefore, instead of
7501// emitting null pointers in private and local address spaces, a null
7502// pointer in generic address space is emitted which is casted to a
7503// pointer in local or private address space.
7504llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7505 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7506 QualType QT) const {
7507 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7508 return llvm::ConstantPointerNull::get(PT);
7509
7510 auto &Ctx = CGM.getContext();
7511 auto NPT = llvm::PointerType::get(PT->getElementType(),
7512 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7513 return llvm::ConstantExpr::getAddrSpaceCast(
7514 llvm::ConstantPointerNull::get(NPT), PT);
7515}
7516
Yaxun Liucbf647c2017-07-08 13:24:52 +00007517unsigned
7518AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7519 const VarDecl *D) const {
7520 assert(!CGM.getLangOpts().OpenCL &&
7521 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7522 "Address space agnostic languages only");
7523 unsigned DefaultGlobalAS =
7524 LangAS::FirstTargetAddressSpace +
7525 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global);
7526 if (!D)
7527 return DefaultGlobalAS;
7528
7529 unsigned AddrSpace = D->getType().getAddressSpace();
7530 assert(AddrSpace == LangAS::Default ||
7531 AddrSpace >= LangAS::FirstTargetAddressSpace);
7532 if (AddrSpace != LangAS::Default)
7533 return AddrSpace;
7534
7535 if (CGM.isTypeConstant(D->getType(), false)) {
7536 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7537 return ConstAS.getValue();
7538 }
7539 return DefaultGlobalAS;
7540}
7541
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007542//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007543// SPARC v8 ABI Implementation.
7544// Based on the SPARC Compliance Definition version 2.4.1.
7545//
7546// Ensures that complex values are passed in registers.
7547//
7548namespace {
7549class SparcV8ABIInfo : public DefaultABIInfo {
7550public:
7551 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7552
7553private:
7554 ABIArgInfo classifyReturnType(QualType RetTy) const;
7555 void computeInfo(CGFunctionInfo &FI) const override;
7556};
7557} // end anonymous namespace
7558
7559
7560ABIArgInfo
7561SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7562 if (Ty->isAnyComplexType()) {
7563 return ABIArgInfo::getDirect();
7564 }
7565 else {
7566 return DefaultABIInfo::classifyReturnType(Ty);
7567 }
7568}
7569
7570void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7571
7572 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7573 for (auto &Arg : FI.arguments())
7574 Arg.info = classifyArgumentType(Arg.type);
7575}
7576
7577namespace {
7578class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7579public:
7580 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7581 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7582};
7583} // end anonymous namespace
7584
7585//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007586// SPARC v9 ABI Implementation.
7587// Based on the SPARC Compliance Definition version 2.4.1.
7588//
7589// Function arguments a mapped to a nominal "parameter array" and promoted to
7590// registers depending on their type. Each argument occupies 8 or 16 bytes in
7591// the array, structs larger than 16 bytes are passed indirectly.
7592//
7593// One case requires special care:
7594//
7595// struct mixed {
7596// int i;
7597// float f;
7598// };
7599//
7600// When a struct mixed is passed by value, it only occupies 8 bytes in the
7601// parameter array, but the int is passed in an integer register, and the float
7602// is passed in a floating point register. This is represented as two arguments
7603// with the LLVM IR inreg attribute:
7604//
7605// declare void f(i32 inreg %i, float inreg %f)
7606//
7607// The code generator will only allocate 4 bytes from the parameter array for
7608// the inreg arguments. All other arguments are allocated a multiple of 8
7609// bytes.
7610//
7611namespace {
7612class SparcV9ABIInfo : public ABIInfo {
7613public:
7614 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7615
7616private:
7617 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007618 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007619 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7620 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007621
7622 // Coercion type builder for structs passed in registers. The coercion type
7623 // serves two purposes:
7624 //
7625 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7626 // in registers.
7627 // 2. Expose aligned floating point elements as first-level elements, so the
7628 // code generator knows to pass them in floating point registers.
7629 //
7630 // We also compute the InReg flag which indicates that the struct contains
7631 // aligned 32-bit floats.
7632 //
7633 struct CoerceBuilder {
7634 llvm::LLVMContext &Context;
7635 const llvm::DataLayout &DL;
7636 SmallVector<llvm::Type*, 8> Elems;
7637 uint64_t Size;
7638 bool InReg;
7639
7640 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7641 : Context(c), DL(dl), Size(0), InReg(false) {}
7642
7643 // Pad Elems with integers until Size is ToSize.
7644 void pad(uint64_t ToSize) {
7645 assert(ToSize >= Size && "Cannot remove elements");
7646 if (ToSize == Size)
7647 return;
7648
7649 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007650 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007651 if (Aligned > Size && Aligned <= ToSize) {
7652 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7653 Size = Aligned;
7654 }
7655
7656 // Add whole 64-bit words.
7657 while (Size + 64 <= ToSize) {
7658 Elems.push_back(llvm::Type::getInt64Ty(Context));
7659 Size += 64;
7660 }
7661
7662 // Final in-word padding.
7663 if (Size < ToSize) {
7664 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7665 Size = ToSize;
7666 }
7667 }
7668
7669 // Add a floating point element at Offset.
7670 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7671 // Unaligned floats are treated as integers.
7672 if (Offset % Bits)
7673 return;
7674 // The InReg flag is only required if there are any floats < 64 bits.
7675 if (Bits < 64)
7676 InReg = true;
7677 pad(Offset);
7678 Elems.push_back(Ty);
7679 Size = Offset + Bits;
7680 }
7681
7682 // Add a struct type to the coercion type, starting at Offset (in bits).
7683 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7684 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7685 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7686 llvm::Type *ElemTy = StrTy->getElementType(i);
7687 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7688 switch (ElemTy->getTypeID()) {
7689 case llvm::Type::StructTyID:
7690 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7691 break;
7692 case llvm::Type::FloatTyID:
7693 addFloat(ElemOffset, ElemTy, 32);
7694 break;
7695 case llvm::Type::DoubleTyID:
7696 addFloat(ElemOffset, ElemTy, 64);
7697 break;
7698 case llvm::Type::FP128TyID:
7699 addFloat(ElemOffset, ElemTy, 128);
7700 break;
7701 case llvm::Type::PointerTyID:
7702 if (ElemOffset % 64 == 0) {
7703 pad(ElemOffset);
7704 Elems.push_back(ElemTy);
7705 Size += 64;
7706 }
7707 break;
7708 default:
7709 break;
7710 }
7711 }
7712 }
7713
7714 // Check if Ty is a usable substitute for the coercion type.
7715 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007716 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007717 }
7718
7719 // Get the coercion type as a literal struct type.
7720 llvm::Type *getType() const {
7721 if (Elems.size() == 1)
7722 return Elems.front();
7723 else
7724 return llvm::StructType::get(Context, Elems);
7725 }
7726 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007727};
7728} // end anonymous namespace
7729
7730ABIArgInfo
7731SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7732 if (Ty->isVoidType())
7733 return ABIArgInfo::getIgnore();
7734
7735 uint64_t Size = getContext().getTypeSize(Ty);
7736
7737 // Anything too big to fit in registers is passed with an explicit indirect
7738 // pointer / sret pointer.
7739 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007740 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007741
7742 // Treat an enum type as its underlying type.
7743 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7744 Ty = EnumTy->getDecl()->getIntegerType();
7745
7746 // Integer types smaller than a register are extended.
7747 if (Size < 64 && Ty->isIntegerType())
7748 return ABIArgInfo::getExtend();
7749
7750 // Other non-aggregates go in registers.
7751 if (!isAggregateTypeForABI(Ty))
7752 return ABIArgInfo::getDirect();
7753
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007754 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7755 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7756 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007757 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007758
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007759 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007760 // Build a coercion type from the LLVM struct type.
7761 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7762 if (!StrTy)
7763 return ABIArgInfo::getDirect();
7764
7765 CoerceBuilder CB(getVMContext(), getDataLayout());
7766 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007767 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007768
7769 // Try to use the original type for coercion.
7770 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7771
7772 if (CB.InReg)
7773 return ABIArgInfo::getDirectInReg(CoerceTy);
7774 else
7775 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007776}
7777
John McCall7f416cc2015-09-08 08:05:57 +00007778Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7779 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007780 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7781 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7782 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7783 AI.setCoerceToType(ArgTy);
7784
John McCall7f416cc2015-09-08 08:05:57 +00007785 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007786
John McCall7f416cc2015-09-08 08:05:57 +00007787 CGBuilderTy &Builder = CGF.Builder;
7788 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7789 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7790
7791 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7792
7793 Address ArgAddr = Address::invalid();
7794 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007795 switch (AI.getKind()) {
7796 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007797 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007798 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007799 llvm_unreachable("Unsupported ABI kind for va_arg");
7800
John McCall7f416cc2015-09-08 08:05:57 +00007801 case ABIArgInfo::Extend: {
7802 Stride = SlotSize;
7803 CharUnits Offset = SlotSize - TypeInfo.first;
7804 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007805 break;
John McCall7f416cc2015-09-08 08:05:57 +00007806 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007807
John McCall7f416cc2015-09-08 08:05:57 +00007808 case ABIArgInfo::Direct: {
7809 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007810 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007811 ArgAddr = Addr;
7812 break;
John McCall7f416cc2015-09-08 08:05:57 +00007813 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007814
7815 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007816 Stride = SlotSize;
7817 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7818 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7819 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007820 break;
7821
7822 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007823 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007824 }
7825
7826 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007827 llvm::Value *NextPtr =
7828 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7829 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007830
John McCall7f416cc2015-09-08 08:05:57 +00007831 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007832}
7833
7834void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7835 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007836 for (auto &I : FI.arguments())
7837 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007838}
7839
7840namespace {
7841class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7842public:
7843 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7844 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007845
Craig Topper4f12f102014-03-12 06:41:41 +00007846 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007847 return 14;
7848 }
7849
7850 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007851 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007852};
7853} // end anonymous namespace
7854
Roman Divackyf02c9942014-02-24 18:46:27 +00007855bool
7856SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7857 llvm::Value *Address) const {
7858 // This is calculated from the LLVM and GCC tables and verified
7859 // against gcc output. AFAIK all ABIs use the same encoding.
7860
7861 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7862
7863 llvm::IntegerType *i8 = CGF.Int8Ty;
7864 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7865 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7866
7867 // 0-31: the 8-byte general-purpose registers
7868 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7869
7870 // 32-63: f0-31, the 4-byte floating-point registers
7871 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7872
7873 // Y = 64
7874 // PSR = 65
7875 // WIM = 66
7876 // TBR = 67
7877 // PC = 68
7878 // NPC = 69
7879 // FSR = 70
7880 // CSR = 71
7881 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007882
Roman Divackyf02c9942014-02-24 18:46:27 +00007883 // 72-87: d0-15, the 8-byte floating-point registers
7884 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7885
7886 return false;
7887}
7888
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007889
Robert Lytton0e076492013-08-13 09:43:10 +00007890//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007891// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007892//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007893
Robert Lytton0e076492013-08-13 09:43:10 +00007894namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007895
7896/// A SmallStringEnc instance is used to build up the TypeString by passing
7897/// it by reference between functions that append to it.
7898typedef llvm::SmallString<128> SmallStringEnc;
7899
7900/// TypeStringCache caches the meta encodings of Types.
7901///
7902/// The reason for caching TypeStrings is two fold:
7903/// 1. To cache a type's encoding for later uses;
7904/// 2. As a means to break recursive member type inclusion.
7905///
7906/// A cache Entry can have a Status of:
7907/// NonRecursive: The type encoding is not recursive;
7908/// Recursive: The type encoding is recursive;
7909/// Incomplete: An incomplete TypeString;
7910/// IncompleteUsed: An incomplete TypeString that has been used in a
7911/// Recursive type encoding.
7912///
7913/// A NonRecursive entry will have all of its sub-members expanded as fully
7914/// as possible. Whilst it may contain types which are recursive, the type
7915/// itself is not recursive and thus its encoding may be safely used whenever
7916/// the type is encountered.
7917///
7918/// A Recursive entry will have all of its sub-members expanded as fully as
7919/// possible. The type itself is recursive and it may contain other types which
7920/// are recursive. The Recursive encoding must not be used during the expansion
7921/// of a recursive type's recursive branch. For simplicity the code uses
7922/// IncompleteCount to reject all usage of Recursive encodings for member types.
7923///
7924/// An Incomplete entry is always a RecordType and only encodes its
7925/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7926/// are placed into the cache during type expansion as a means to identify and
7927/// handle recursive inclusion of types as sub-members. If there is recursion
7928/// the entry becomes IncompleteUsed.
7929///
7930/// During the expansion of a RecordType's members:
7931///
7932/// If the cache contains a NonRecursive encoding for the member type, the
7933/// cached encoding is used;
7934///
7935/// If the cache contains a Recursive encoding for the member type, the
7936/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7937///
7938/// If the member is a RecordType, an Incomplete encoding is placed into the
7939/// cache to break potential recursive inclusion of itself as a sub-member;
7940///
7941/// Once a member RecordType has been expanded, its temporary incomplete
7942/// entry is removed from the cache. If a Recursive encoding was swapped out
7943/// it is swapped back in;
7944///
7945/// If an incomplete entry is used to expand a sub-member, the incomplete
7946/// entry is marked as IncompleteUsed. The cache keeps count of how many
7947/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7948///
7949/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7950/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7951/// Else the member is part of a recursive type and thus the recursion has
7952/// been exited too soon for the encoding to be correct for the member.
7953///
7954class TypeStringCache {
7955 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7956 struct Entry {
7957 std::string Str; // The encoded TypeString for the type.
7958 enum Status State; // Information about the encoding in 'Str'.
7959 std::string Swapped; // A temporary place holder for a Recursive encoding
7960 // during the expansion of RecordType's members.
7961 };
7962 std::map<const IdentifierInfo *, struct Entry> Map;
7963 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7964 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7965public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007966 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007967 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7968 bool removeIncomplete(const IdentifierInfo *ID);
7969 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7970 bool IsRecursive);
7971 StringRef lookupStr(const IdentifierInfo *ID);
7972};
7973
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007974/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007975/// FieldEncoding is a helper for this ordering process.
7976class FieldEncoding {
7977 bool HasName;
7978 std::string Enc;
7979public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007980 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007981 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007982 bool operator<(const FieldEncoding &rhs) const {
7983 if (HasName != rhs.HasName) return HasName;
7984 return Enc < rhs.Enc;
7985 }
7986};
7987
Robert Lytton7d1db152013-08-19 09:46:39 +00007988class XCoreABIInfo : public DefaultABIInfo {
7989public:
7990 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007991 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7992 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007993};
7994
Robert Lyttond21e2d72014-03-03 13:45:29 +00007995class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007996 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007997public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007998 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007999 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00008000 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8001 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00008002};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008003
Robert Lytton2d196952013-10-11 10:29:34 +00008004} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00008005
James Y Knight29b5f082016-02-24 02:59:33 +00008006// TODO: this implementation is likely now redundant with the default
8007// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00008008Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8009 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00008010 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00008011
Robert Lytton2d196952013-10-11 10:29:34 +00008012 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008013 CharUnits SlotSize = CharUnits::fromQuantity(4);
8014 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00008015
Robert Lytton2d196952013-10-11 10:29:34 +00008016 // Handle the argument.
8017 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00008018 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00008019 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8020 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8021 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00008022 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00008023
8024 Address Val = Address::invalid();
8025 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00008026 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00008027 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00008028 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00008029 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00008030 llvm_unreachable("Unsupported ABI kind for va_arg");
8031 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00008032 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8033 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00008034 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008035 case ABIArgInfo::Extend:
8036 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00008037 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8038 ArgSize = CharUnits::fromQuantity(
8039 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00008040 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00008041 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008042 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00008043 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8044 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8045 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00008046 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00008047 }
Robert Lytton2d196952013-10-11 10:29:34 +00008048
8049 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00008050 if (!ArgSize.isZero()) {
8051 llvm::Value *APN =
8052 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8053 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00008054 }
John McCall7f416cc2015-09-08 08:05:57 +00008055
Robert Lytton2d196952013-10-11 10:29:34 +00008056 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00008057}
Robert Lytton0e076492013-08-13 09:43:10 +00008058
Robert Lytton844aeeb2014-05-02 09:33:20 +00008059/// During the expansion of a RecordType, an incomplete TypeString is placed
8060/// into the cache as a means to identify and break recursion.
8061/// If there is a Recursive encoding in the cache, it is swapped out and will
8062/// be reinserted by removeIncomplete().
8063/// All other types of encoding should have been used rather than arriving here.
8064void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8065 std::string StubEnc) {
8066 if (!ID)
8067 return;
8068 Entry &E = Map[ID];
8069 assert( (E.Str.empty() || E.State == Recursive) &&
8070 "Incorrectly use of addIncomplete");
8071 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8072 E.Swapped.swap(E.Str); // swap out the Recursive
8073 E.Str.swap(StubEnc);
8074 E.State = Incomplete;
8075 ++IncompleteCount;
8076}
8077
8078/// Once the RecordType has been expanded, the temporary incomplete TypeString
8079/// must be removed from the cache.
8080/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8081/// Returns true if the RecordType was defined recursively.
8082bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8083 if (!ID)
8084 return false;
8085 auto I = Map.find(ID);
8086 assert(I != Map.end() && "Entry not present");
8087 Entry &E = I->second;
8088 assert( (E.State == Incomplete ||
8089 E.State == IncompleteUsed) &&
8090 "Entry must be an incomplete type");
8091 bool IsRecursive = false;
8092 if (E.State == IncompleteUsed) {
8093 // We made use of our Incomplete encoding, thus we are recursive.
8094 IsRecursive = true;
8095 --IncompleteUsedCount;
8096 }
8097 if (E.Swapped.empty())
8098 Map.erase(I);
8099 else {
8100 // Swap the Recursive back.
8101 E.Swapped.swap(E.Str);
8102 E.Swapped.clear();
8103 E.State = Recursive;
8104 }
8105 --IncompleteCount;
8106 return IsRecursive;
8107}
8108
8109/// Add the encoded TypeString to the cache only if it is NonRecursive or
8110/// Recursive (viz: all sub-members were expanded as fully as possible).
8111void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8112 bool IsRecursive) {
8113 if (!ID || IncompleteUsedCount)
8114 return; // No key or it is is an incomplete sub-type so don't add.
8115 Entry &E = Map[ID];
8116 if (IsRecursive && !E.Str.empty()) {
8117 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8118 "This is not the same Recursive entry");
8119 // The parent container was not recursive after all, so we could have used
8120 // this Recursive sub-member entry after all, but we assumed the worse when
8121 // we started viz: IncompleteCount!=0.
8122 return;
8123 }
8124 assert(E.Str.empty() && "Entry already present");
8125 E.Str = Str.str();
8126 E.State = IsRecursive? Recursive : NonRecursive;
8127}
8128
8129/// Return a cached TypeString encoding for the ID. If there isn't one, or we
8130/// are recursively expanding a type (IncompleteCount != 0) and the cached
8131/// encoding is Recursive, return an empty StringRef.
8132StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8133 if (!ID)
8134 return StringRef(); // We have no key.
8135 auto I = Map.find(ID);
8136 if (I == Map.end())
8137 return StringRef(); // We have no encoding.
8138 Entry &E = I->second;
8139 if (E.State == Recursive && IncompleteCount)
8140 return StringRef(); // We don't use Recursive encodings for member types.
8141
8142 if (E.State == Incomplete) {
8143 // The incomplete type is being used to break out of recursion.
8144 E.State = IncompleteUsed;
8145 ++IncompleteUsedCount;
8146 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00008147 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008148}
8149
8150/// The XCore ABI includes a type information section that communicates symbol
8151/// type information to the linker. The linker uses this information to verify
8152/// safety/correctness of things such as array bound and pointers et al.
8153/// The ABI only requires C (and XC) language modules to emit TypeStrings.
8154/// This type information (TypeString) is emitted into meta data for all global
8155/// symbols: definitions, declarations, functions & variables.
8156///
8157/// The TypeString carries type, qualifier, name, size & value details.
8158/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00008159/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00008160/// The output is tested by test/CodeGen/xcore-stringtype.c.
8161///
8162static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8163 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8164
8165/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8166void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8167 CodeGen::CodeGenModule &CGM) const {
8168 SmallStringEnc Enc;
8169 if (getTypeString(Enc, D, CGM, TSC)) {
8170 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008171 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8172 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008173 llvm::NamedMDNode *MD =
8174 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8175 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8176 }
8177}
8178
Xiuli Pan972bea82016-03-24 03:57:17 +00008179//===----------------------------------------------------------------------===//
8180// SPIR ABI Implementation
8181//===----------------------------------------------------------------------===//
8182
8183namespace {
8184class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8185public:
8186 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8187 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008188 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008189};
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008190
Xiuli Pan972bea82016-03-24 03:57:17 +00008191} // End anonymous namespace.
8192
Pekka Jaaskelainenfc2629a2017-06-01 07:18:49 +00008193namespace clang {
8194namespace CodeGen {
8195void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8196 DefaultABIInfo SPIRABI(CGM.getTypes());
8197 SPIRABI.computeInfo(FI);
8198}
8199}
8200}
8201
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008202unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8203 return llvm::CallingConv::SPIR_KERNEL;
8204}
8205
Robert Lytton844aeeb2014-05-02 09:33:20 +00008206static bool appendType(SmallStringEnc &Enc, QualType QType,
8207 const CodeGen::CodeGenModule &CGM,
8208 TypeStringCache &TSC);
8209
8210/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008211/// Builds a SmallVector containing the encoded field types in declaration
8212/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008213static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8214 const RecordDecl *RD,
8215 const CodeGen::CodeGenModule &CGM,
8216 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008217 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008218 SmallStringEnc Enc;
8219 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008220 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008221 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008222 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008223 Enc += "b(";
8224 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008225 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008226 Enc += ':';
8227 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008228 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008229 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008230 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008231 Enc += ')';
8232 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008233 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008234 }
8235 return true;
8236}
8237
8238/// Appends structure and union types to Enc and adds encoding to cache.
8239/// Recursively calls appendType (via extractFieldType) for each field.
8240/// Union types have their fields ordered according to the ABI.
8241static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8242 const CodeGen::CodeGenModule &CGM,
8243 TypeStringCache &TSC, const IdentifierInfo *ID) {
8244 // Append the cached TypeString if we have one.
8245 StringRef TypeString = TSC.lookupStr(ID);
8246 if (!TypeString.empty()) {
8247 Enc += TypeString;
8248 return true;
8249 }
8250
8251 // Start to emit an incomplete TypeString.
8252 size_t Start = Enc.size();
8253 Enc += (RT->isUnionType()? 'u' : 's');
8254 Enc += '(';
8255 if (ID)
8256 Enc += ID->getName();
8257 Enc += "){";
8258
8259 // We collect all encoded fields and order as necessary.
8260 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008261 const RecordDecl *RD = RT->getDecl()->getDefinition();
8262 if (RD && !RD->field_empty()) {
8263 // An incomplete TypeString stub is placed in the cache for this RecordType
8264 // so that recursive calls to this RecordType will use it whilst building a
8265 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008266 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008267 std::string StubEnc(Enc.substr(Start).str());
8268 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8269 TSC.addIncomplete(ID, std::move(StubEnc));
8270 if (!extractFieldType(FE, RD, CGM, TSC)) {
8271 (void) TSC.removeIncomplete(ID);
8272 return false;
8273 }
8274 IsRecursive = TSC.removeIncomplete(ID);
8275 // The ABI requires unions to be sorted but not structures.
8276 // See FieldEncoding::operator< for sort algorithm.
8277 if (RT->isUnionType())
8278 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008279 // We can now complete the TypeString.
8280 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008281 for (unsigned I = 0; I != E; ++I) {
8282 if (I)
8283 Enc += ',';
8284 Enc += FE[I].str();
8285 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008286 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008287 Enc += '}';
8288 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8289 return true;
8290}
8291
8292/// Appends enum types to Enc and adds the encoding to the cache.
8293static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8294 TypeStringCache &TSC,
8295 const IdentifierInfo *ID) {
8296 // Append the cached TypeString if we have one.
8297 StringRef TypeString = TSC.lookupStr(ID);
8298 if (!TypeString.empty()) {
8299 Enc += TypeString;
8300 return true;
8301 }
8302
8303 size_t Start = Enc.size();
8304 Enc += "e(";
8305 if (ID)
8306 Enc += ID->getName();
8307 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008308
8309 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008310 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008311 SmallVector<FieldEncoding, 16> FE;
8312 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8313 ++I) {
8314 SmallStringEnc EnumEnc;
8315 EnumEnc += "m(";
8316 EnumEnc += I->getName();
8317 EnumEnc += "){";
8318 I->getInitVal().toString(EnumEnc);
8319 EnumEnc += '}';
8320 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8321 }
8322 std::sort(FE.begin(), FE.end());
8323 unsigned E = FE.size();
8324 for (unsigned I = 0; I != E; ++I) {
8325 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008326 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008327 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008328 }
8329 }
8330 Enc += '}';
8331 TSC.addIfComplete(ID, Enc.substr(Start), false);
8332 return true;
8333}
8334
8335/// Appends type's qualifier to Enc.
8336/// This is done prior to appending the type's encoding.
8337static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8338 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008339 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008340 int Lookup = 0;
8341 if (QT.isConstQualified())
8342 Lookup += 1<<0;
8343 if (QT.isRestrictQualified())
8344 Lookup += 1<<1;
8345 if (QT.isVolatileQualified())
8346 Lookup += 1<<2;
8347 Enc += Table[Lookup];
8348}
8349
8350/// Appends built-in types to Enc.
8351static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8352 const char *EncType;
8353 switch (BT->getKind()) {
8354 case BuiltinType::Void:
8355 EncType = "0";
8356 break;
8357 case BuiltinType::Bool:
8358 EncType = "b";
8359 break;
8360 case BuiltinType::Char_U:
8361 EncType = "uc";
8362 break;
8363 case BuiltinType::UChar:
8364 EncType = "uc";
8365 break;
8366 case BuiltinType::SChar:
8367 EncType = "sc";
8368 break;
8369 case BuiltinType::UShort:
8370 EncType = "us";
8371 break;
8372 case BuiltinType::Short:
8373 EncType = "ss";
8374 break;
8375 case BuiltinType::UInt:
8376 EncType = "ui";
8377 break;
8378 case BuiltinType::Int:
8379 EncType = "si";
8380 break;
8381 case BuiltinType::ULong:
8382 EncType = "ul";
8383 break;
8384 case BuiltinType::Long:
8385 EncType = "sl";
8386 break;
8387 case BuiltinType::ULongLong:
8388 EncType = "ull";
8389 break;
8390 case BuiltinType::LongLong:
8391 EncType = "sll";
8392 break;
8393 case BuiltinType::Float:
8394 EncType = "ft";
8395 break;
8396 case BuiltinType::Double:
8397 EncType = "d";
8398 break;
8399 case BuiltinType::LongDouble:
8400 EncType = "ld";
8401 break;
8402 default:
8403 return false;
8404 }
8405 Enc += EncType;
8406 return true;
8407}
8408
8409/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8410static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8411 const CodeGen::CodeGenModule &CGM,
8412 TypeStringCache &TSC) {
8413 Enc += "p(";
8414 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8415 return false;
8416 Enc += ')';
8417 return true;
8418}
8419
8420/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008421static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8422 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008423 const CodeGen::CodeGenModule &CGM,
8424 TypeStringCache &TSC, StringRef NoSizeEnc) {
8425 if (AT->getSizeModifier() != ArrayType::Normal)
8426 return false;
8427 Enc += "a(";
8428 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8429 CAT->getSize().toStringUnsigned(Enc);
8430 else
8431 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8432 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008433 // The Qualifiers should be attached to the type rather than the array.
8434 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008435 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8436 return false;
8437 Enc += ')';
8438 return true;
8439}
8440
8441/// Appends a function encoding to Enc, calling appendType for the return type
8442/// and the arguments.
8443static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8444 const CodeGen::CodeGenModule &CGM,
8445 TypeStringCache &TSC) {
8446 Enc += "f{";
8447 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8448 return false;
8449 Enc += "}(";
8450 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8451 // N.B. we are only interested in the adjusted param types.
8452 auto I = FPT->param_type_begin();
8453 auto E = FPT->param_type_end();
8454 if (I != E) {
8455 do {
8456 if (!appendType(Enc, *I, CGM, TSC))
8457 return false;
8458 ++I;
8459 if (I != E)
8460 Enc += ',';
8461 } while (I != E);
8462 if (FPT->isVariadic())
8463 Enc += ",va";
8464 } else {
8465 if (FPT->isVariadic())
8466 Enc += "va";
8467 else
8468 Enc += '0';
8469 }
8470 }
8471 Enc += ')';
8472 return true;
8473}
8474
8475/// Handles the type's qualifier before dispatching a call to handle specific
8476/// type encodings.
8477static bool appendType(SmallStringEnc &Enc, QualType QType,
8478 const CodeGen::CodeGenModule &CGM,
8479 TypeStringCache &TSC) {
8480
8481 QualType QT = QType.getCanonicalType();
8482
Robert Lytton6adb20f2014-06-05 09:06:21 +00008483 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8484 // The Qualifiers should be attached to the type rather than the array.
8485 // Thus we don't call appendQualifier() here.
8486 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8487
Robert Lytton844aeeb2014-05-02 09:33:20 +00008488 appendQualifier(Enc, QT);
8489
8490 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8491 return appendBuiltinType(Enc, BT);
8492
Robert Lytton844aeeb2014-05-02 09:33:20 +00008493 if (const PointerType *PT = QT->getAs<PointerType>())
8494 return appendPointerType(Enc, PT, CGM, TSC);
8495
8496 if (const EnumType *ET = QT->getAs<EnumType>())
8497 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8498
8499 if (const RecordType *RT = QT->getAsStructureType())
8500 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8501
8502 if (const RecordType *RT = QT->getAsUnionType())
8503 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8504
8505 if (const FunctionType *FT = QT->getAs<FunctionType>())
8506 return appendFunctionType(Enc, FT, CGM, TSC);
8507
8508 return false;
8509}
8510
8511static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8512 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8513 if (!D)
8514 return false;
8515
8516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8517 if (FD->getLanguageLinkage() != CLanguageLinkage)
8518 return false;
8519 return appendType(Enc, FD->getType(), CGM, TSC);
8520 }
8521
8522 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8523 if (VD->getLanguageLinkage() != CLanguageLinkage)
8524 return false;
8525 QualType QT = VD->getType().getCanonicalType();
8526 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8527 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008528 // The Qualifiers should be attached to the type rather than the array.
8529 // Thus we don't call appendQualifier() here.
8530 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008531 }
8532 return appendType(Enc, QT, CGM, TSC);
8533 }
8534 return false;
8535}
8536
8537
Robert Lytton0e076492013-08-13 09:43:10 +00008538//===----------------------------------------------------------------------===//
8539// Driver code
8540//===----------------------------------------------------------------------===//
8541
Rafael Espindola9f834732014-09-19 01:54:22 +00008542bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008543 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008544}
8545
Chris Lattner2b037972010-07-29 02:01:43 +00008546const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008547 if (TheTargetCodeGenInfo)
8548 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008549
Reid Kleckner9305fd12016-04-13 23:37:17 +00008550 // Helper to set the unique_ptr while still keeping the return value.
8551 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8552 this->TheTargetCodeGenInfo.reset(P);
8553 return *P;
8554 };
8555
John McCallc8e01702013-04-16 22:48:15 +00008556 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008557 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008558 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008559 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008560
Derek Schuff09338a22012-09-06 17:37:28 +00008561 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008562 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008563 case llvm::Triple::mips:
8564 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008565 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008566 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8567 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008568
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008569 case llvm::Triple::mips64:
8570 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008571 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008572
Dylan McKaye8232d72017-02-08 05:09:26 +00008573 case llvm::Triple::avr:
8574 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8575
Tim Northover25e8a672014-05-24 12:51:25 +00008576 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008577 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008578 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008579 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008580 Kind = AArch64ABIInfo::DarwinPCS;
Martin Storsjo502de222017-07-13 17:59:14 +00008581 else if (Triple.isOSWindows())
Martin Storsjo1c8af272017-07-20 05:47:06 +00008582 return SetCGInfo(
8583 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
Tim Northovera2ee4332014-03-29 15:09:45 +00008584
Reid Kleckner9305fd12016-04-13 23:37:17 +00008585 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008586 }
8587
Dan Gohmanc2853072015-09-03 22:51:53 +00008588 case llvm::Triple::wasm32:
8589 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008590 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008591
Daniel Dunbard59655c2009-09-12 00:59:49 +00008592 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008593 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008594 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008595 case llvm::Triple::thumbeb: {
8596 if (Triple.getOS() == llvm::Triple::Win32) {
8597 return SetCGInfo(
8598 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008599 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008600
Reid Kleckner9305fd12016-04-13 23:37:17 +00008601 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8602 StringRef ABIStr = getTarget().getABI();
8603 if (ABIStr == "apcs-gnu")
8604 Kind = ARMABIInfo::APCS;
8605 else if (ABIStr == "aapcs16")
8606 Kind = ARMABIInfo::AAPCS16_VFP;
8607 else if (CodeGenOpts.FloatABI == "hard" ||
8608 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008609 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008610 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008611 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008612 Kind = ARMABIInfo::AAPCS_VFP;
8613
8614 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8615 }
8616
John McCallea8d8bb2010-03-11 00:10:12 +00008617 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008618 return SetCGInfo(
8619 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008620 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008621 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008622 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008623 if (getTarget().getABI() == "elfv2")
8624 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008625 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008626 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008627
Hal Finkel415c2a32016-10-02 02:10:45 +00008628 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8629 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008630 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008631 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008632 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008633 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008634 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008635 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008636 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008637 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008638 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008639
Hal Finkel415c2a32016-10-02 02:10:45 +00008640 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8641 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008642 }
John McCallea8d8bb2010-03-11 00:10:12 +00008643
Peter Collingbournec947aae2012-05-20 23:28:41 +00008644 case llvm::Triple::nvptx:
8645 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008646 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008647
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008648 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008649 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008650
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008651 case llvm::Triple::systemz: {
8652 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008653 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008654 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008655
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008656 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008657 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008658 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008659
Eli Friedman33465822011-07-08 23:31:17 +00008660 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008661 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008662 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008663 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008664 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008665
John McCall1fe2a8c2013-06-18 02:46:29 +00008666 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008667 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8668 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8669 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008670 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008671 return SetCGInfo(new X86_32TargetCodeGenInfo(
8672 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8673 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8674 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008675 }
Eli Friedman33465822011-07-08 23:31:17 +00008676 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008677
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008678 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008679 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008680 X86AVXABILevel AVXLevel =
8681 (ABI == "avx512"
8682 ? X86AVXABILevel::AVX512
8683 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008684
Chris Lattner04dc9572010-08-31 16:44:54 +00008685 switch (Triple.getOS()) {
8686 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008687 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008688 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008689 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008690 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008691 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008692 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008693 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008694 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008695 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008696 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008697 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008698 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008699 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008700 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008701 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008702 case llvm::Triple::sparc:
8703 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008704 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008705 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008706 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008707 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008708 case llvm::Triple::spir:
8709 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008710 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008711 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008712}