blob: e4f7d99bef674f6d886a7011e37af3b9bafcd839 [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 {
401 return llvm::CallingConv::C;
402}
Yaxun Liu37ceede2016-07-20 19:21:11 +0000403
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000404static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000405
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000406/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000407/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000408static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
409 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000410 if (FD->isUnnamedBitfield())
411 return true;
412
413 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000414
Eli Friedman0b3f2012011-11-18 03:47:20 +0000415 // Constant arrays of empty records count as empty, strip them off.
416 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000417 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000418 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
419 if (AT->getSize() == 0)
420 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000421 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000422 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000423
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000424 const RecordType *RT = FT->getAs<RecordType>();
425 if (!RT)
426 return false;
427
428 // C++ record fields are never empty, at least in the Itanium ABI.
429 //
430 // FIXME: We should use a predicate for whether this behavior is true in the
431 // current ABI.
432 if (isa<CXXRecordDecl>(RT->getDecl()))
433 return false;
434
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000435 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000436}
437
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000438/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000439/// fields. Note that a structure with a flexible array member is not
440/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000441static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000442 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000443 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000444 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000445 const RecordDecl *RD = RT->getDecl();
446 if (RD->hasFlexibleArrayMember())
447 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000448
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000449 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000450 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000451 for (const auto &I : CXXRD->bases())
452 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000453 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000454
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000455 for (const auto *I : RD->fields())
456 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000457 return false;
458 return true;
459}
460
461/// isSingleElementStruct - Determine if a structure is a "single
462/// element struct", i.e. it has exactly one non-empty field or
463/// exactly one field which is itself a single element
464/// struct. Structures with flexible array members are never
465/// considered single element structs.
466///
467/// \return The field declaration for the single non-empty field, if
468/// it exists.
469static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000470 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000472 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000473
474 const RecordDecl *RD = RT->getDecl();
475 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000476 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000477
Craig Topper8a13c412014-05-21 05:09:00 +0000478 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000479
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000480 // If this is a C++ record, check the bases first.
481 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000482 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000483 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000484 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000485 continue;
486
487 // If we already found an element then this isn't a single-element struct.
488 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000489 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000490
491 // If this is non-empty and not a single element struct, the composite
492 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000493 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000494 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000495 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000496 }
497 }
498
499 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000500 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000501 QualType FT = FD->getType();
502
503 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000504 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000505 continue;
506
507 // If we already found an element then this isn't a single-element
508 // struct.
509 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000510 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000511
512 // Treat single element arrays as the element.
513 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
514 if (AT->getSize().getZExtValue() != 1)
515 break;
516 FT = AT->getElementType();
517 }
518
John McCalla1dee5302010-08-22 10:59:02 +0000519 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000520 Found = FT.getTypePtr();
521 } else {
522 Found = isSingleElementStruct(FT, Context);
523 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000524 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525 }
526 }
527
Eli Friedmanee945342011-11-18 01:25:50 +0000528 // We don't consider a struct a single-element struct if it has
529 // padding beyond the element type.
530 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000531 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000532
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000533 return Found;
534}
535
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000536namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000537Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
538 const ABIArgInfo &AI) {
539 // This default implementation defers to the llvm backend's va_arg
540 // instruction. It can handle only passing arguments directly
541 // (typically only handled in the backend for primitive types), or
542 // aggregates passed indirectly by pointer (NOTE: if the "byval"
543 // flag has ABI impact in the callee, this implementation cannot
544 // work.)
545
546 // Only a few cases are covered here at the moment -- those needed
547 // by the default abi.
548 llvm::Value *Val;
549
550 if (AI.isIndirect()) {
551 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000552 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000553 assert(
554 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000555 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000556
557 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
558 CharUnits TyAlignForABI = TyInfo.second;
559
560 llvm::Type *BaseTy =
561 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
562 llvm::Value *Addr =
563 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
564 return Address(Addr, TyAlignForABI);
565 } else {
566 assert((AI.isDirect() || AI.isExtend()) &&
567 "Unexpected ArgInfo Kind in generic VAArg emitter!");
568
569 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000570 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000571 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000572 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000573 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000574 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000575 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000576 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000577
578 Address Temp = CGF.CreateMemTemp(Ty, "varet");
579 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
580 CGF.Builder.CreateStore(Val, Temp);
581 return Temp;
582 }
583}
584
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000585/// DefaultABIInfo - The default implementation for ABI specific
586/// details. This implementation provides information which results in
587/// self-consistent and sensible LLVM IR generation, but does not
588/// conform to any particular ABI.
589class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000590public:
591 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000592
Chris Lattner458b2aa2010-07-29 02:16:43 +0000593 ABIArgInfo classifyReturnType(QualType RetTy) const;
594 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000595
Craig Topper4f12f102014-03-12 06:41:41 +0000596 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000597 if (!getCXXABI().classifyReturnType(FI))
598 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000599 for (auto &I : FI.arguments())
600 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000601 }
602
John McCall7f416cc2015-09-08 08:05:57 +0000603 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000604 QualType Ty) const override {
605 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
606 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000607};
608
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000609class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
610public:
Chris Lattner2b037972010-07-29 02:01:43 +0000611 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
612 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000613};
614
Chris Lattner458b2aa2010-07-29 02:16:43 +0000615ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000616 Ty = useFirstFieldIfTransparentUnion(Ty);
617
618 if (isAggregateTypeForABI(Ty)) {
619 // Records with non-trivial destructors/copy-constructors should not be
620 // passed by value.
621 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000622 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000623
John McCall7f416cc2015-09-08 08:05:57 +0000624 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000625 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000626
Chris Lattner9723d6c2010-03-11 18:19:55 +0000627 // Treat an enum type as its underlying type.
628 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
629 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000630
Chris Lattner9723d6c2010-03-11 18:19:55 +0000631 return (Ty->isPromotableIntegerType() ?
632 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000633}
634
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000635ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
636 if (RetTy->isVoidType())
637 return ABIArgInfo::getIgnore();
638
639 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000640 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000641
642 // Treat an enum type as its underlying type.
643 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
644 RetTy = EnumTy->getDecl()->getIntegerType();
645
646 return (RetTy->isPromotableIntegerType() ?
647 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
648}
649
Derek Schuff09338a22012-09-06 17:37:28 +0000650//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000651// WebAssembly ABI Implementation
652//
653// This is a very simple ABI that relies a lot on DefaultABIInfo.
654//===----------------------------------------------------------------------===//
655
656class WebAssemblyABIInfo final : public DefaultABIInfo {
657public:
658 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
659 : DefaultABIInfo(CGT) {}
660
661private:
662 ABIArgInfo classifyReturnType(QualType RetTy) const;
663 ABIArgInfo classifyArgumentType(QualType Ty) const;
664
665 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000666 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000667 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000668 void computeInfo(CGFunctionInfo &FI) const override {
669 if (!getCXXABI().classifyReturnType(FI))
670 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
671 for (auto &Arg : FI.arguments())
672 Arg.info = classifyArgumentType(Arg.type);
673 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000674
675 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
676 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000677};
678
679class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
680public:
681 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
682 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
683};
684
685/// \brief Classify argument of given type \p Ty.
686ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
687 Ty = useFirstFieldIfTransparentUnion(Ty);
688
689 if (isAggregateTypeForABI(Ty)) {
690 // Records with non-trivial destructors/copy-constructors should not be
691 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000693 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000694 // Ignore empty structs/unions.
695 if (isEmptyRecord(getContext(), Ty, true))
696 return ABIArgInfo::getIgnore();
697 // Lower single-element structs to just pass a regular value. TODO: We
698 // could do reasonable-size multiple-element structs too, using getExpand(),
699 // though watch out for things like bitfields.
700 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
701 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000702 }
703
704 // Otherwise just do the default thing.
705 return DefaultABIInfo::classifyArgumentType(Ty);
706}
707
708ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
709 if (isAggregateTypeForABI(RetTy)) {
710 // Records with non-trivial destructors/copy-constructors should not be
711 // returned by value.
712 if (!getRecordArgABI(RetTy, getCXXABI())) {
713 // Ignore empty structs/unions.
714 if (isEmptyRecord(getContext(), RetTy, true))
715 return ABIArgInfo::getIgnore();
716 // Lower single-element structs to just return a regular value. TODO: We
717 // could do reasonable-size multiple-element structs too, using
718 // ABIArgInfo::getDirect().
719 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
720 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
721 }
722 }
723
724 // Otherwise just do the default thing.
725 return DefaultABIInfo::classifyReturnType(RetTy);
726}
727
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000728Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
729 QualType Ty) const {
730 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
731 getContext().getTypeInfoInChars(Ty),
732 CharUnits::fromQuantity(4),
733 /*AllowHigherAlign=*/ true);
734}
735
Dan Gohmanc2853072015-09-03 22:51:53 +0000736//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000737// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000738//
739// This is a simplified version of the x86_32 ABI. Arguments and return values
740// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000741//===----------------------------------------------------------------------===//
742
743class PNaClABIInfo : public ABIInfo {
744 public:
745 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
746
747 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000748 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000749
Craig Topper4f12f102014-03-12 06:41:41 +0000750 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000751 Address EmitVAArg(CodeGenFunction &CGF,
752 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000753};
754
755class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
756 public:
757 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
758 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
759};
760
761void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000762 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000763 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
764
Reid Kleckner40ca9132014-05-13 22:05:45 +0000765 for (auto &I : FI.arguments())
766 I.info = classifyArgumentType(I.type);
767}
Derek Schuff09338a22012-09-06 17:37:28 +0000768
John McCall7f416cc2015-09-08 08:05:57 +0000769Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
770 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000771 // The PNaCL ABI is a bit odd, in that varargs don't use normal
772 // function classification. Structs get passed directly for varargs
773 // functions, through a rewriting transform in
774 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
775 // this target to actually support a va_arg instructions with an
776 // aggregate type, unlike other targets.
777 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000778}
779
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000780/// \brief Classify argument of given type \p Ty.
781ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000782 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000783 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000784 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
785 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000786 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
787 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000788 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000789 } else if (Ty->isFloatingType()) {
790 // Floating-point types don't go inreg.
791 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000792 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000793
794 return (Ty->isPromotableIntegerType() ?
795 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000796}
797
798ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
799 if (RetTy->isVoidType())
800 return ABIArgInfo::getIgnore();
801
Eli Benderskye20dad62013-04-04 22:49:35 +0000802 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000803 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000804 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000805
806 // Treat an enum type as its underlying type.
807 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
808 RetTy = EnumTy->getDecl()->getIntegerType();
809
810 return (RetTy->isPromotableIntegerType() ?
811 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
812}
813
Chad Rosier651c1832013-03-25 21:00:27 +0000814/// IsX86_MMXType - Return true if this is an MMX type.
815bool IsX86_MMXType(llvm::Type *IRType) {
816 // 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 +0000817 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
818 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
819 IRType->getScalarSizeInBits() != 64;
820}
821
Jay Foad7c57be32011-07-11 09:56:20 +0000822static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000823 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000824 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000825 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
826 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
827 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000828 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000829 }
830
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000831 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000832 }
833
834 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000835 return Ty;
836}
837
Reid Kleckner80944df2014-10-31 22:00:51 +0000838/// Returns true if this type can be passed in SSE registers with the
839/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
840static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
841 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
842 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
843 return true;
844 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
845 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
846 // registers specially.
847 unsigned VecSize = Context.getTypeSize(VT);
848 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
849 return true;
850 }
851 return false;
852}
853
854/// Returns true if this aggregate is small enough to be passed in SSE registers
855/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
856static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
857 return NumMembers <= 4;
858}
859
Chris Lattner0cf24192010-06-28 20:05:43 +0000860//===----------------------------------------------------------------------===//
861// X86-32 ABI Implementation
862//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000863
Reid Kleckner661f35b2014-01-18 01:12:41 +0000864/// \brief Similar to llvm::CCState, but for Clang.
865struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000866 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000867
868 unsigned CC;
869 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000870 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000871};
872
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000873/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000874class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000875 enum Class {
876 Integer,
877 Float
878 };
879
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000880 static const unsigned MinABIStackAlignInBytes = 4;
881
David Chisnallde3a0692009-08-17 23:08:21 +0000882 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000883 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000884 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000885 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000886 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000887 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000888
889 static bool isRegisterSize(unsigned Size) {
890 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
891 }
892
Reid Kleckner80944df2014-10-31 22:00:51 +0000893 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
894 // FIXME: Assumes vectorcall is in use.
895 return isX86VectorTypeForVectorCall(getContext(), Ty);
896 }
897
898 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
899 uint64_t NumMembers) const override {
900 // FIXME: Assumes vectorcall is in use.
901 return isX86VectorCallAggregateSmallEnough(NumMembers);
902 }
903
Reid Kleckner40ca9132014-05-13 22:05:45 +0000904 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000905
Daniel Dunbar557893d2010-04-21 19:10:51 +0000906 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
907 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000908 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
909
John McCall7f416cc2015-09-08 08:05:57 +0000910 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000911
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000912 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000913 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000914
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000915 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000916 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000917 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000918 /// \brief Updates the number of available free registers, returns
919 /// true if any registers were allocated.
920 bool updateFreeRegs(QualType Ty, CCState &State) const;
921
922 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
923 bool &NeedsPadding) const;
924 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000925
Reid Kleckner04046052016-05-02 17:41:07 +0000926 bool canExpandIndirectArgument(QualType Ty) const;
927
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000928 /// \brief Rewrite the function info so that all memory arguments use
929 /// inalloca.
930 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
931
932 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000933 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000934 QualType Type) const;
935
Rafael Espindola75419dc2012-07-23 23:30:29 +0000936public:
937
Craig Topper4f12f102014-03-12 06:41:41 +0000938 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000939 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
940 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000941
Michael Kupersteindc745202015-10-19 07:52:25 +0000942 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
943 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000944 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000945 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000946 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
947 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000948 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000949 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000950 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000951
952 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
953 ArrayRef<llvm::Type*> scalars,
954 bool asReturnValue) const override {
955 // LLVM's x86-32 lowering currently only assigns up to three
956 // integer registers and three fp registers. Oddly, it'll use up to
957 // four vector registers for vectors, but those can overlap with the
958 // scalar registers.
959 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
960 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +0000961
962 bool isSwiftErrorInRegister() const override {
963 // x86-32 lowering does not support passing swifterror in a register.
964 return false;
965 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000966};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000967
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000968class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
969public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000970 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
971 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000972 unsigned NumRegisterParameters, bool SoftFloatABI)
973 : TargetCodeGenInfo(new X86_32ABIInfo(
974 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
975 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000976
John McCall1fe2a8c2013-06-18 02:46:29 +0000977 static bool isStructReturnInRegABI(
978 const llvm::Triple &Triple, const CodeGenOptions &Opts);
979
Eric Christopher162c91c2015-06-05 22:03:00 +0000980 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000981 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000982
Craig Topper4f12f102014-03-12 06:41:41 +0000983 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000984 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000985 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000986 return 4;
987 }
988
989 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000990 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000991
Jay Foad7c57be32011-07-11 09:56:20 +0000992 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000993 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000994 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000995 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
996 }
997
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000998 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
999 std::string &Constraints,
1000 std::vector<llvm::Type *> &ResultRegTypes,
1001 std::vector<llvm::Type *> &ResultTruncRegTypes,
1002 std::vector<LValue> &ResultRegDests,
1003 std::string &AsmString,
1004 unsigned NumOutputs) const override;
1005
Craig Topper4f12f102014-03-12 06:41:41 +00001006 llvm::Constant *
1007 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001008 unsigned Sig = (0xeb << 0) | // jmp rel8
1009 (0x06 << 8) | // .+0x08
1010 ('F' << 16) |
1011 ('T' << 24);
1012 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1013 }
John McCall01391782016-02-05 21:37:38 +00001014
1015 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1016 return "movl\t%ebp, %ebp"
1017 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1018 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001019};
1020
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001021}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001022
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001023/// Rewrite input constraint references after adding some output constraints.
1024/// In the case where there is one output and one input and we add one output,
1025/// we need to replace all operand references greater than or equal to 1:
1026/// mov $0, $1
1027/// mov eax, $1
1028/// The result will be:
1029/// mov $0, $2
1030/// mov eax, $2
1031static void rewriteInputConstraintReferences(unsigned FirstIn,
1032 unsigned NumNewOuts,
1033 std::string &AsmString) {
1034 std::string Buf;
1035 llvm::raw_string_ostream OS(Buf);
1036 size_t Pos = 0;
1037 while (Pos < AsmString.size()) {
1038 size_t DollarStart = AsmString.find('$', Pos);
1039 if (DollarStart == std::string::npos)
1040 DollarStart = AsmString.size();
1041 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1042 if (DollarEnd == std::string::npos)
1043 DollarEnd = AsmString.size();
1044 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1045 Pos = DollarEnd;
1046 size_t NumDollars = DollarEnd - DollarStart;
1047 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1048 // We have an operand reference.
1049 size_t DigitStart = Pos;
1050 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1051 if (DigitEnd == std::string::npos)
1052 DigitEnd = AsmString.size();
1053 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1054 unsigned OperandIndex;
1055 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1056 if (OperandIndex >= FirstIn)
1057 OperandIndex += NumNewOuts;
1058 OS << OperandIndex;
1059 } else {
1060 OS << OperandStr;
1061 }
1062 Pos = DigitEnd;
1063 }
1064 }
1065 AsmString = std::move(OS.str());
1066}
1067
1068/// Add output constraints for EAX:EDX because they are return registers.
1069void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1070 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1071 std::vector<llvm::Type *> &ResultRegTypes,
1072 std::vector<llvm::Type *> &ResultTruncRegTypes,
1073 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1074 unsigned NumOutputs) const {
1075 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1076
1077 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1078 // larger.
1079 if (!Constraints.empty())
1080 Constraints += ',';
1081 if (RetWidth <= 32) {
1082 Constraints += "={eax}";
1083 ResultRegTypes.push_back(CGF.Int32Ty);
1084 } else {
1085 // Use the 'A' constraint for EAX:EDX.
1086 Constraints += "=A";
1087 ResultRegTypes.push_back(CGF.Int64Ty);
1088 }
1089
1090 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1091 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1092 ResultTruncRegTypes.push_back(CoerceTy);
1093
1094 // Coerce the integer by bitcasting the return slot pointer.
1095 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1096 CoerceTy->getPointerTo()));
1097 ResultRegDests.push_back(ReturnSlot);
1098
1099 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1100}
1101
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001102/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001103/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001104bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1105 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106 uint64_t Size = Context.getTypeSize(Ty);
1107
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001108 // For i386, type must be register sized.
1109 // For the MCU ABI, it only needs to be <= 8-byte
1110 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1111 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001112
1113 if (Ty->isVectorType()) {
1114 // 64- and 128- bit vectors inside structures are not returned in
1115 // registers.
1116 if (Size == 64 || Size == 128)
1117 return false;
1118
1119 return true;
1120 }
1121
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001122 // If this is a builtin, pointer, enum, complex type, member pointer, or
1123 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001124 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001125 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001126 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001127 return true;
1128
1129 // Arrays are treated like records.
1130 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001131 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001132
1133 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001134 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001135 if (!RT) return false;
1136
Anders Carlsson40446e82010-01-27 03:25:19 +00001137 // FIXME: Traverse bases here too.
1138
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001139 // Structure types are passed in register if all fields would be
1140 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001141 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001142 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001143 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001144 continue;
1145
1146 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001147 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001148 return false;
1149 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001150 return true;
1151}
1152
Reid Kleckner04046052016-05-02 17:41:07 +00001153static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1154 // Treat complex types as the element type.
1155 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1156 Ty = CTy->getElementType();
1157
1158 // Check for a type which we know has a simple scalar argument-passing
1159 // convention without any padding. (We're specifically looking for 32
1160 // and 64-bit integer and integer-equivalents, float, and double.)
1161 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1162 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1163 return false;
1164
1165 uint64_t Size = Context.getTypeSize(Ty);
1166 return Size == 32 || Size == 64;
1167}
1168
1169/// Test whether an argument type which is to be passed indirectly (on the
1170/// stack) would have the equivalent layout if it was expanded into separate
1171/// arguments. If so, we prefer to do the latter to avoid inhibiting
1172/// optimizations.
1173bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1174 // We can only expand structure types.
1175 const RecordType *RT = Ty->getAs<RecordType>();
1176 if (!RT)
1177 return false;
1178 const RecordDecl *RD = RT->getDecl();
1179 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1180 if (!IsWin32StructABI ) {
1181 // On non-Windows, we have to conservatively match our old bitcode
1182 // prototypes in order to be ABI-compatible at the bitcode level.
1183 if (!CXXRD->isCLike())
1184 return false;
1185 } else {
1186 // Don't do this for dynamic classes.
1187 if (CXXRD->isDynamicClass())
1188 return false;
1189 // Don't do this if there are any non-empty bases.
1190 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1191 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1192 return false;
1193 }
1194 }
1195 }
1196
1197 uint64_t Size = 0;
1198
1199 for (const auto *FD : RD->fields()) {
1200 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1201 // argument is smaller than 32-bits, expanding the struct will create
1202 // alignment padding.
1203 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1204 return false;
1205
1206 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1207 // how to expand them yet, and the predicate for telling if a bitfield still
1208 // counts as "basic" is more complicated than what we were doing previously.
1209 if (FD->isBitField())
1210 return false;
1211
1212 Size += getContext().getTypeSize(FD->getType());
1213 }
1214
1215 // We can do this if there was no alignment padding.
1216 return Size == getContext().getTypeSize(Ty);
1217}
1218
John McCall7f416cc2015-09-08 08:05:57 +00001219ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001220 // If the return value is indirect, then the hidden argument is consuming one
1221 // integer register.
1222 if (State.FreeRegs) {
1223 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001224 if (!IsMCUABI)
1225 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001226 }
John McCall7f416cc2015-09-08 08:05:57 +00001227 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001228}
1229
Eric Christopher7565e0d2015-05-29 23:09:49 +00001230ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1231 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001232 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001233 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001234
Reid Kleckner80944df2014-10-31 22:00:51 +00001235 const Type *Base = nullptr;
1236 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001237 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1238 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001239 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1240 // The LLVM struct type for such an aggregate should lower properly.
1241 return ABIArgInfo::getDirect();
1242 }
1243
Chris Lattner458b2aa2010-07-29 02:16:43 +00001244 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001245 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001246 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001247 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001248
1249 // 128-bit vectors are a special case; they are returned in
1250 // registers and we need to make sure to pick a type the LLVM
1251 // backend will like.
1252 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001253 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001254 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001255
1256 // Always return in register if it fits in a general purpose
1257 // register, or if it is 64 bits and has a single element.
1258 if ((Size == 8 || Size == 16 || Size == 32) ||
1259 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001260 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001261 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001262
John McCall7f416cc2015-09-08 08:05:57 +00001263 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001264 }
1265
1266 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001267 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001268
John McCalla1dee5302010-08-22 10:59:02 +00001269 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001270 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001271 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001272 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001273 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001274 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001275
David Chisnallde3a0692009-08-17 23:08:21 +00001276 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001277 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001278 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001279
Denis Zobnin380b2242016-02-11 11:26:03 +00001280 // Ignore empty structs/unions.
1281 if (isEmptyRecord(getContext(), RetTy, true))
1282 return ABIArgInfo::getIgnore();
1283
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001284 // Small structures which are register sized are generally returned
1285 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001286 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001287 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001288
1289 // As a special-case, if the struct is a "single-element" struct, and
1290 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001291 // floating-point register. (MSVC does not apply this special case.)
1292 // We apply a similar transformation for pointer types to improve the
1293 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001294 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001295 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001296 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001297 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1298
1299 // FIXME: We should be able to narrow this integer in cases with dead
1300 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001301 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001302 }
1303
John McCall7f416cc2015-09-08 08:05:57 +00001304 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001305 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001306
Chris Lattner458b2aa2010-07-29 02:16:43 +00001307 // Treat an enum type as its underlying type.
1308 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1309 RetTy = EnumTy->getDecl()->getIntegerType();
1310
1311 return (RetTy->isPromotableIntegerType() ?
1312 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001313}
1314
Eli Friedman7919bea2012-06-05 19:40:46 +00001315static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1316 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1317}
1318
Daniel Dunbared23de32010-09-16 20:42:00 +00001319static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1320 const RecordType *RT = Ty->getAs<RecordType>();
1321 if (!RT)
1322 return 0;
1323 const RecordDecl *RD = RT->getDecl();
1324
1325 // If this is a C++ record, check the bases first.
1326 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001327 for (const auto &I : CXXRD->bases())
1328 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001329 return false;
1330
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001331 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001332 QualType FT = i->getType();
1333
Eli Friedman7919bea2012-06-05 19:40:46 +00001334 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001335 return true;
1336
1337 if (isRecordWithSSEVectorType(Context, FT))
1338 return true;
1339 }
1340
1341 return false;
1342}
1343
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001344unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1345 unsigned Align) const {
1346 // Otherwise, if the alignment is less than or equal to the minimum ABI
1347 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001348 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001349 return 0; // Use default alignment.
1350
1351 // On non-Darwin, the stack type alignment is always 4.
1352 if (!IsDarwinVectorABI) {
1353 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001354 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001355 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001356
Daniel Dunbared23de32010-09-16 20:42:00 +00001357 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001358 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1359 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001360 return 16;
1361
1362 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001363}
1364
Rafael Espindola703c47f2012-10-19 05:04:37 +00001365ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001366 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001367 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001368 if (State.FreeRegs) {
1369 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001370 if (!IsMCUABI)
1371 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001372 }
John McCall7f416cc2015-09-08 08:05:57 +00001373 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001374 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001375
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001376 // Compute the byval alignment.
1377 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1378 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1379 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001380 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001381
1382 // If the stack alignment is less than the type alignment, realign the
1383 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001384 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001385 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1386 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001387}
1388
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001389X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1390 const Type *T = isSingleElementStruct(Ty, getContext());
1391 if (!T)
1392 T = Ty.getTypePtr();
1393
1394 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1395 BuiltinType::Kind K = BT->getKind();
1396 if (K == BuiltinType::Float || K == BuiltinType::Double)
1397 return Float;
1398 }
1399 return Integer;
1400}
1401
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001402bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001403 if (!IsSoftFloatABI) {
1404 Class C = classify(Ty);
1405 if (C == Float)
1406 return false;
1407 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001408
Rafael Espindola077dd592012-10-24 01:58:58 +00001409 unsigned Size = getContext().getTypeSize(Ty);
1410 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001411
1412 if (SizeInRegs == 0)
1413 return false;
1414
Michael Kuperstein68901882015-10-25 08:18:20 +00001415 if (!IsMCUABI) {
1416 if (SizeInRegs > State.FreeRegs) {
1417 State.FreeRegs = 0;
1418 return false;
1419 }
1420 } else {
1421 // The MCU psABI allows passing parameters in-reg even if there are
1422 // earlier parameters that are passed on the stack. Also,
1423 // it does not allow passing >8-byte structs in-register,
1424 // even if there are 3 free registers available.
1425 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1426 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001427 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001428
Reid Kleckner661f35b2014-01-18 01:12:41 +00001429 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001430 return true;
1431}
1432
1433bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1434 bool &InReg,
1435 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001436 // On Windows, aggregates other than HFAs are never passed in registers, and
1437 // they do not consume register slots. Homogenous floating-point aggregates
1438 // (HFAs) have already been dealt with at this point.
1439 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1440 return false;
1441
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001442 NeedsPadding = false;
1443 InReg = !IsMCUABI;
1444
1445 if (!updateFreeRegs(Ty, State))
1446 return false;
1447
1448 if (IsMCUABI)
1449 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001450
Reid Kleckner80944df2014-10-31 22:00:51 +00001451 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001452 State.CC == llvm::CallingConv::X86_VectorCall ||
1453 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001454 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001455 NeedsPadding = true;
1456
Rafael Espindola077dd592012-10-24 01:58:58 +00001457 return false;
1458 }
1459
Rafael Espindola703c47f2012-10-19 05:04:37 +00001460 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001461}
1462
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001463bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1464 if (!updateFreeRegs(Ty, State))
1465 return false;
1466
1467 if (IsMCUABI)
1468 return false;
1469
1470 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001471 State.CC == llvm::CallingConv::X86_VectorCall ||
1472 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001473 if (getContext().getTypeSize(Ty) > 32)
1474 return false;
1475
1476 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1477 Ty->isReferenceType());
1478 }
1479
1480 return true;
1481}
1482
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001483ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1484 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001485 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001486
Reid Klecknerb1be6832014-11-15 01:41:41 +00001487 Ty = useFirstFieldIfTransparentUnion(Ty);
1488
Reid Kleckner80944df2014-10-31 22:00:51 +00001489 // Check with the C++ ABI first.
1490 const RecordType *RT = Ty->getAs<RecordType>();
1491 if (RT) {
1492 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1493 if (RAA == CGCXXABI::RAA_Indirect) {
1494 return getIndirectResult(Ty, false, State);
1495 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1496 // The field index doesn't matter, we'll fix it up later.
1497 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1498 }
1499 }
1500
1501 // vectorcall adds the concept of a homogenous vector aggregate, similar
1502 // to other targets.
1503 const Type *Base = nullptr;
1504 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001505 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1506 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001507 isHomogeneousAggregate(Ty, Base, NumElts)) {
1508 if (State.FreeSSERegs >= NumElts) {
1509 State.FreeSSERegs -= NumElts;
1510 if (Ty->isBuiltinType() || Ty->isVectorType())
1511 return ABIArgInfo::getDirect();
1512 return ABIArgInfo::getExpand();
1513 }
1514 return getIndirectResult(Ty, /*ByVal=*/false, State);
1515 }
1516
1517 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001518 // Structures with flexible arrays are always indirect.
1519 // FIXME: This should not be byval!
1520 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1521 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001522
Reid Kleckner04046052016-05-02 17:41:07 +00001523 // Ignore empty structs/unions on non-Windows.
1524 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001525 return ABIArgInfo::getIgnore();
1526
Rafael Espindolafad28de2012-10-24 01:59:00 +00001527 llvm::LLVMContext &LLVMContext = getVMContext();
1528 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001529 bool NeedsPadding = false;
1530 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001531 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001532 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001533 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001534 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001535 if (InReg)
1536 return ABIArgInfo::getDirectInReg(Result);
1537 else
1538 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001539 }
Craig Topper8a13c412014-05-21 05:09:00 +00001540 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001541
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001542 // Expand small (<= 128-bit) record types when we know that the stack layout
1543 // of those arguments will match the struct. This is important because the
1544 // LLVM backend isn't smart enough to remove byval, which inhibits many
1545 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001546 // Don't do this for the MCU if there are still free integer registers
1547 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001548 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1549 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001550 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001551 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001552 State.CC == llvm::CallingConv::X86_VectorCall ||
1553 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001554 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001555
Reid Kleckner661f35b2014-01-18 01:12:41 +00001556 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001557 }
1558
Chris Lattnerd774ae92010-08-26 20:05:13 +00001559 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001560 // On Darwin, some vectors are passed in memory, we handle this by passing
1561 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001562 if (IsDarwinVectorABI) {
1563 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001564 if ((Size == 8 || Size == 16 || Size == 32) ||
1565 (Size == 64 && VT->getNumElements() == 1))
1566 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1567 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001568 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001569
Chad Rosier651c1832013-03-25 21:00:27 +00001570 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1571 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001572
Chris Lattnerd774ae92010-08-26 20:05:13 +00001573 return ABIArgInfo::getDirect();
1574 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001575
1576
Chris Lattner458b2aa2010-07-29 02:16:43 +00001577 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1578 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001579
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001580 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001581
1582 if (Ty->isPromotableIntegerType()) {
1583 if (InReg)
1584 return ABIArgInfo::getExtendInReg();
1585 return ABIArgInfo::getExtend();
1586 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001587
Rafael Espindola703c47f2012-10-19 05:04:37 +00001588 if (InReg)
1589 return ABIArgInfo::getDirectInReg();
1590 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001591}
1592
Rafael Espindolaa6472962012-07-24 00:01:07 +00001593void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001594 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001595 if (IsMCUABI)
1596 State.FreeRegs = 3;
1597 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001598 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001599 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1600 State.FreeRegs = 2;
1601 State.FreeSSERegs = 6;
1602 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001603 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001604 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1605 State.FreeRegs = 5;
1606 State.FreeSSERegs = 8;
1607 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001608 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001609
Reid Kleckner677539d2014-07-10 01:58:55 +00001610 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001611 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001612 } else if (FI.getReturnInfo().isIndirect()) {
1613 // The C++ ABI is not aware of register usage, so we have to check if the
1614 // return value was sret and put it in a register ourselves if appropriate.
1615 if (State.FreeRegs) {
1616 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001617 if (!IsMCUABI)
1618 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001619 }
1620 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001621
Peter Collingbournef7706832014-12-12 23:41:25 +00001622 // The chain argument effectively gives us another free register.
1623 if (FI.isChainCall())
1624 ++State.FreeRegs;
1625
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001626 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001627 for (auto &I : FI.arguments()) {
1628 I.info = classifyArgumentType(I.type, State);
1629 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001630 }
1631
1632 // If we needed to use inalloca for any argument, do a second pass and rewrite
1633 // all the memory arguments to use inalloca.
1634 if (UsedInAlloca)
1635 rewriteWithInAlloca(FI);
1636}
1637
1638void
1639X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001640 CharUnits &StackOffset, ABIArgInfo &Info,
1641 QualType Type) const {
1642 // Arguments are always 4-byte-aligned.
1643 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1644
1645 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001646 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1647 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001648 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001649
John McCall7f416cc2015-09-08 08:05:57 +00001650 // Insert padding bytes to respect alignment.
1651 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001652 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001653 if (StackOffset != FieldEnd) {
1654 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001655 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001656 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001657 FrameFields.push_back(Ty);
1658 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001659}
1660
Reid Kleckner852361d2014-07-26 00:12:26 +00001661static bool isArgInAlloca(const ABIArgInfo &Info) {
1662 // Leave ignored and inreg arguments alone.
1663 switch (Info.getKind()) {
1664 case ABIArgInfo::InAlloca:
1665 return true;
1666 case ABIArgInfo::Indirect:
1667 assert(Info.getIndirectByVal());
1668 return true;
1669 case ABIArgInfo::Ignore:
1670 return false;
1671 case ABIArgInfo::Direct:
1672 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001673 if (Info.getInReg())
1674 return false;
1675 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001676 case ABIArgInfo::Expand:
1677 case ABIArgInfo::CoerceAndExpand:
1678 // These are aggregate types which are never passed in registers when
1679 // inalloca is involved.
1680 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001681 }
1682 llvm_unreachable("invalid enum");
1683}
1684
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001685void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1686 assert(IsWin32StructABI && "inalloca only supported on win32");
1687
1688 // Build a packed struct type for all of the arguments in memory.
1689 SmallVector<llvm::Type *, 6> FrameFields;
1690
John McCall7f416cc2015-09-08 08:05:57 +00001691 // The stack alignment is always 4.
1692 CharUnits StackAlign = CharUnits::fromQuantity(4);
1693
1694 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001695 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1696
1697 // Put 'this' into the struct before 'sret', if necessary.
1698 bool IsThisCall =
1699 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1700 ABIArgInfo &Ret = FI.getReturnInfo();
1701 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1702 isArgInAlloca(I->info)) {
1703 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1704 ++I;
1705 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001706
1707 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001708 if (Ret.isIndirect() && !Ret.getInReg()) {
1709 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1710 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001711 // On Windows, the hidden sret parameter is always returned in eax.
1712 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001713 }
1714
1715 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001716 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001717 ++I;
1718
1719 // Put arguments passed in memory into the struct.
1720 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001721 if (isArgInAlloca(I->info))
1722 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001723 }
1724
1725 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001726 /*isPacked=*/true),
1727 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001728}
1729
John McCall7f416cc2015-09-08 08:05:57 +00001730Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1731 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001732
John McCall7f416cc2015-09-08 08:05:57 +00001733 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001734
John McCall7f416cc2015-09-08 08:05:57 +00001735 // x86-32 changes the alignment of certain arguments on the stack.
1736 //
1737 // Just messing with TypeInfo like this works because we never pass
1738 // anything indirectly.
1739 TypeInfo.second = CharUnits::fromQuantity(
1740 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001741
John McCall7f416cc2015-09-08 08:05:57 +00001742 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1743 TypeInfo, CharUnits::fromQuantity(4),
1744 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001745}
1746
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001747bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1748 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1749 assert(Triple.getArch() == llvm::Triple::x86);
1750
1751 switch (Opts.getStructReturnConvention()) {
1752 case CodeGenOptions::SRCK_Default:
1753 break;
1754 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1755 return false;
1756 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1757 return true;
1758 }
1759
Michael Kupersteind749f232015-10-27 07:46:22 +00001760 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001761 return true;
1762
1763 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001764 case llvm::Triple::DragonFly:
1765 case llvm::Triple::FreeBSD:
1766 case llvm::Triple::OpenBSD:
1767 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001768 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001769 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001770 default:
1771 return false;
1772 }
1773}
1774
Eric Christopher162c91c2015-06-05 22:03:00 +00001775void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001776 llvm::GlobalValue *GV,
1777 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001778 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001779 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1780 // Get the LLVM function.
1781 llvm::Function *Fn = cast<llvm::Function>(GV);
1782
1783 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001784 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001785 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001786 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1787 llvm::AttributeSet::get(CGM.getLLVMContext(),
1788 llvm::AttributeSet::FunctionIndex,
1789 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001790 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001791 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1792 llvm::Function *Fn = cast<llvm::Function>(GV);
1793 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1794 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001795 }
1796}
1797
John McCallbeec5a02010-03-06 00:35:14 +00001798bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1799 CodeGen::CodeGenFunction &CGF,
1800 llvm::Value *Address) const {
1801 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001802
Chris Lattnerece04092012-02-07 00:39:47 +00001803 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001804
John McCallbeec5a02010-03-06 00:35:14 +00001805 // 0-7 are the eight integer registers; the order is different
1806 // on Darwin (for EH), but the range is the same.
1807 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001808 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001809
John McCallc8e01702013-04-16 22:48:15 +00001810 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001811 // 12-16 are st(0..4). Not sure why we stop at 4.
1812 // These have size 16, which is sizeof(long double) on
1813 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001814 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001815 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001816
John McCallbeec5a02010-03-06 00:35:14 +00001817 } else {
1818 // 9 is %eflags, which doesn't get a size on Darwin for some
1819 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001820 Builder.CreateAlignedStore(
1821 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1822 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001823
1824 // 11-16 are st(0..5). Not sure why we stop at 5.
1825 // These have size 12, which is sizeof(long double) on
1826 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001827 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001828 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1829 }
John McCallbeec5a02010-03-06 00:35:14 +00001830
1831 return false;
1832}
1833
Chris Lattner0cf24192010-06-28 20:05:43 +00001834//===----------------------------------------------------------------------===//
1835// X86-64 ABI Implementation
1836//===----------------------------------------------------------------------===//
1837
1838
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001839namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001840/// The AVX ABI level for X86 targets.
1841enum class X86AVXABILevel {
1842 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001843 AVX,
1844 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001845};
1846
1847/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1848static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1849 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001850 case X86AVXABILevel::AVX512:
1851 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001852 case X86AVXABILevel::AVX:
1853 return 256;
1854 case X86AVXABILevel::None:
1855 return 128;
1856 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001857 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001858}
1859
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001860/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001861class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001862 enum Class {
1863 Integer = 0,
1864 SSE,
1865 SSEUp,
1866 X87,
1867 X87Up,
1868 ComplexX87,
1869 NoClass,
1870 Memory
1871 };
1872
1873 /// merge - Implement the X86_64 ABI merging algorithm.
1874 ///
1875 /// Merge an accumulating classification \arg Accum with a field
1876 /// classification \arg Field.
1877 ///
1878 /// \param Accum - The accumulating classification. This should
1879 /// always be either NoClass or the result of a previous merge
1880 /// call. In addition, this should never be Memory (the caller
1881 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001882 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001883
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001884 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1885 ///
1886 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1887 /// final MEMORY or SSE classes when necessary.
1888 ///
1889 /// \param AggregateSize - The size of the current aggregate in
1890 /// the classification process.
1891 ///
1892 /// \param Lo - The classification for the parts of the type
1893 /// residing in the low word of the containing object.
1894 ///
1895 /// \param Hi - The classification for the parts of the type
1896 /// residing in the higher words of the containing object.
1897 ///
1898 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1899
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001900 /// classify - Determine the x86_64 register classes in which the
1901 /// given type T should be passed.
1902 ///
1903 /// \param Lo - The classification for the parts of the type
1904 /// residing in the low word of the containing object.
1905 ///
1906 /// \param Hi - The classification for the parts of the type
1907 /// residing in the high word of the containing object.
1908 ///
1909 /// \param OffsetBase - The bit offset of this type in the
1910 /// containing object. Some parameters are classified different
1911 /// depending on whether they straddle an eightbyte boundary.
1912 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001913 /// \param isNamedArg - Whether the argument in question is a "named"
1914 /// argument, as used in AMD64-ABI 3.5.7.
1915 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001916 /// If a word is unused its result will be NoClass; if a type should
1917 /// be passed in Memory then at least the classification of \arg Lo
1918 /// will be Memory.
1919 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001920 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001921 ///
1922 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1923 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001924 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1925 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001926
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001927 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001928 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1929 unsigned IROffset, QualType SourceTy,
1930 unsigned SourceOffset) const;
1931 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1932 unsigned IROffset, QualType SourceTy,
1933 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001934
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001935 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001936 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001937 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001938
1939 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001940 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001941 ///
1942 /// \param freeIntRegs - The number of free integer registers remaining
1943 /// available.
1944 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001945
Chris Lattner458b2aa2010-07-29 02:16:43 +00001946 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001947
Erich Keane757d3172016-11-02 18:29:35 +00001948 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
1949 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00001950 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001951
Erich Keane757d3172016-11-02 18:29:35 +00001952 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
1953 unsigned &NeededSSE) const;
1954
1955 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
1956 unsigned &NeededSSE) const;
1957
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001958 bool IsIllegalVectorType(QualType Ty) const;
1959
John McCalle0fda732011-04-21 01:20:55 +00001960 /// The 0.98 ABI revision clarified a lot of ambiguities,
1961 /// unfortunately in ways that were not always consistent with
1962 /// certain previous compilers. In particular, platforms which
1963 /// required strict binary compatibility with older versions of GCC
1964 /// may need to exempt themselves.
1965 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001966 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001967 }
1968
David Majnemere2ae2282016-03-04 05:26:16 +00001969 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1970 // compilers require us to classify it as INTEGER.
1971 bool classifyIntegerMMXAsSSE() const {
1972 const llvm::Triple &Triple = getTarget().getTriple();
1973 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1974 return false;
1975 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1976 return false;
1977 return true;
1978 }
1979
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001980 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001981 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1982 // 64-bit hardware.
1983 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001984
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001985public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001986 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00001987 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001988 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001989 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001990
John McCalla729c622012-02-17 03:33:10 +00001991 bool isPassedUsingAVXType(QualType type) const {
1992 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001993 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001994 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1995 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001996 if (info.isDirect()) {
1997 llvm::Type *ty = info.getCoerceToType();
1998 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1999 return (vectorTy->getBitWidth() > 128);
2000 }
2001 return false;
2002 }
2003
Craig Topper4f12f102014-03-12 06:41:41 +00002004 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002005
John McCall7f416cc2015-09-08 08:05:57 +00002006 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2007 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002008 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2009 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002010
2011 bool has64BitPointers() const {
2012 return Has64BitPointers;
2013 }
John McCall12f23522016-04-04 18:33:08 +00002014
2015 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2016 ArrayRef<llvm::Type*> scalars,
2017 bool asReturnValue) const override {
2018 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2019 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002020 bool isSwiftErrorInRegister() const override {
2021 return true;
2022 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002023};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002024
Chris Lattner04dc9572010-08-31 16:44:54 +00002025/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002026class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002027public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002028 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002029 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002030 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002031
Craig Topper4f12f102014-03-12 06:41:41 +00002032 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002033
John McCall7f416cc2015-09-08 08:05:57 +00002034 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2035 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002036
2037 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2038 // FIXME: Assumes vectorcall is in use.
2039 return isX86VectorTypeForVectorCall(getContext(), Ty);
2040 }
2041
2042 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2043 uint64_t NumMembers) const override {
2044 // FIXME: Assumes vectorcall is in use.
2045 return isX86VectorCallAggregateSmallEnough(NumMembers);
2046 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002047
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002048 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2049 ArrayRef<llvm::Type *> scalars,
2050 bool asReturnValue) const override {
2051 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2052 }
2053
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002054 bool isSwiftErrorInRegister() const override {
2055 return true;
2056 }
2057
Reid Kleckner11a17192015-10-28 22:29:52 +00002058private:
2059 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2060 bool IsReturnType) const;
2061
2062 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002063};
2064
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002065class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2066public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002067 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002068 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002069
John McCalla729c622012-02-17 03:33:10 +00002070 const X86_64ABIInfo &getABIInfo() const {
2071 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2072 }
2073
Craig Topper4f12f102014-03-12 06:41:41 +00002074 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002075 return 7;
2076 }
2077
2078 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002079 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002080 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002081
John McCall943fae92010-05-27 06:19:26 +00002082 // 0-15 are the 16 integer registers.
2083 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002084 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002085 return false;
2086 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002087
Jay Foad7c57be32011-07-11 09:56:20 +00002088 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002089 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002090 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002091 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2092 }
2093
John McCalla729c622012-02-17 03:33:10 +00002094 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002095 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002096 // The default CC on x86-64 sets %al to the number of SSA
2097 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002098 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002099 // that when AVX types are involved: the ABI explicitly states it is
2100 // undefined, and it doesn't work in practice because of how the ABI
2101 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002102 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002103 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002104 for (CallArgList::const_iterator
2105 it = args.begin(), ie = args.end(); it != ie; ++it) {
2106 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2107 HasAVXType = true;
2108 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002109 }
2110 }
John McCalla729c622012-02-17 03:33:10 +00002111
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002112 if (!HasAVXType)
2113 return true;
2114 }
John McCallcbc038a2011-09-21 08:08:30 +00002115
John McCalla729c622012-02-17 03:33:10 +00002116 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002117 }
2118
Craig Topper4f12f102014-03-12 06:41:41 +00002119 llvm::Constant *
2120 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002121 unsigned Sig;
2122 if (getABIInfo().has64BitPointers())
2123 Sig = (0xeb << 0) | // jmp rel8
2124 (0x0a << 8) | // .+0x0c
2125 ('F' << 16) |
2126 ('T' << 24);
2127 else
2128 Sig = (0xeb << 0) | // jmp rel8
2129 (0x06 << 8) | // .+0x08
2130 ('F' << 16) |
2131 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002132 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2133 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002134
2135 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2136 CodeGen::CodeGenModule &CGM) const override {
2137 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2138 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2139 llvm::Function *Fn = cast<llvm::Function>(GV);
2140 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2141 }
2142 }
2143 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002144};
2145
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002146class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2147public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002148 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2149 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002150
2151 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002152 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002153 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002154 // If the argument contains a space, enclose it in quotes.
2155 if (Lib.find(" ") != StringRef::npos)
2156 Opt += "\"" + Lib.str() + "\"";
2157 else
2158 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002159 }
2160};
2161
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002162static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002163 // If the argument does not end in .lib, automatically add the suffix.
2164 // If the argument contains a space, enclose it in quotes.
2165 // This matches the behavior of MSVC.
2166 bool Quote = (Lib.find(" ") != StringRef::npos);
2167 std::string ArgStr = Quote ? "\"" : "";
2168 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002169 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002170 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002171 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002172 return ArgStr;
2173}
2174
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002175class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2176public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002177 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002178 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2179 unsigned NumRegisterParameters)
2180 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002181 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002182
Eric Christopher162c91c2015-06-05 22:03:00 +00002183 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002184 CodeGen::CodeGenModule &CGM) const override;
2185
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002186 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002187 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002188 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002189 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002190 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002191
2192 void getDetectMismatchOption(llvm::StringRef Name,
2193 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002194 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002195 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002196 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002197};
2198
Hans Wennborg77dc2362015-01-20 19:45:50 +00002199static void addStackProbeSizeTargetAttribute(const Decl *D,
2200 llvm::GlobalValue *GV,
2201 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002202 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002203 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2204 llvm::Function *Fn = cast<llvm::Function>(GV);
2205
Eric Christopher7565e0d2015-05-29 23:09:49 +00002206 Fn->addFnAttr("stack-probe-size",
2207 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002208 }
2209 }
2210}
2211
Eric Christopher162c91c2015-06-05 22:03:00 +00002212void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002213 llvm::GlobalValue *GV,
2214 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002215 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002216
2217 addStackProbeSizeTargetAttribute(D, GV, CGM);
2218}
2219
Chris Lattner04dc9572010-08-31 16:44:54 +00002220class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2221public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002222 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2223 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002224 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002225
Eric Christopher162c91c2015-06-05 22:03:00 +00002226 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002227 CodeGen::CodeGenModule &CGM) const override;
2228
Craig Topper4f12f102014-03-12 06:41:41 +00002229 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002230 return 7;
2231 }
2232
2233 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002234 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002235 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002236
Chris Lattner04dc9572010-08-31 16:44:54 +00002237 // 0-15 are the 16 integer registers.
2238 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002239 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002240 return false;
2241 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002242
2243 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002244 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002245 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002246 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002247 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002248
2249 void getDetectMismatchOption(llvm::StringRef Name,
2250 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002251 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002252 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002253 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002254};
2255
Eric Christopher162c91c2015-06-05 22:03:00 +00002256void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002257 llvm::GlobalValue *GV,
2258 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002259 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002260
Alexey Bataevd51e9932016-01-15 04:06:31 +00002261 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2262 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2263 llvm::Function *Fn = cast<llvm::Function>(GV);
2264 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2265 }
2266 }
2267
Hans Wennborg77dc2362015-01-20 19:45:50 +00002268 addStackProbeSizeTargetAttribute(D, GV, CGM);
2269}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002270}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002271
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002272void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2273 Class &Hi) const {
2274 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2275 //
2276 // (a) If one of the classes is Memory, the whole argument is passed in
2277 // memory.
2278 //
2279 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2280 // memory.
2281 //
2282 // (c) If the size of the aggregate exceeds two eightbytes and the first
2283 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2284 // argument is passed in memory. NOTE: This is necessary to keep the
2285 // ABI working for processors that don't support the __m256 type.
2286 //
2287 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2288 //
2289 // Some of these are enforced by the merging logic. Others can arise
2290 // only with unions; for example:
2291 // union { _Complex double; unsigned; }
2292 //
2293 // Note that clauses (b) and (c) were added in 0.98.
2294 //
2295 if (Hi == Memory)
2296 Lo = Memory;
2297 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2298 Lo = Memory;
2299 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2300 Lo = Memory;
2301 if (Hi == SSEUp && Lo != SSE)
2302 Hi = SSE;
2303}
2304
Chris Lattnerd776fb12010-06-28 21:43:59 +00002305X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002306 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2307 // classified recursively so that always two fields are
2308 // considered. The resulting class is calculated according to
2309 // the classes of the fields in the eightbyte:
2310 //
2311 // (a) If both classes are equal, this is the resulting class.
2312 //
2313 // (b) If one of the classes is NO_CLASS, the resulting class is
2314 // the other class.
2315 //
2316 // (c) If one of the classes is MEMORY, the result is the MEMORY
2317 // class.
2318 //
2319 // (d) If one of the classes is INTEGER, the result is the
2320 // INTEGER.
2321 //
2322 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2323 // MEMORY is used as class.
2324 //
2325 // (f) Otherwise class SSE is used.
2326
2327 // Accum should never be memory (we should have returned) or
2328 // ComplexX87 (because this cannot be passed in a structure).
2329 assert((Accum != Memory && Accum != ComplexX87) &&
2330 "Invalid accumulated classification during merge.");
2331 if (Accum == Field || Field == NoClass)
2332 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002333 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002334 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002335 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002336 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002337 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002339 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2340 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002341 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002342 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002343}
2344
Chris Lattner5c740f12010-06-30 19:14:05 +00002345void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002346 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002347 // FIXME: This code can be simplified by introducing a simple value class for
2348 // Class pairs with appropriate constructor methods for the various
2349 // situations.
2350
2351 // FIXME: Some of the split computations are wrong; unaligned vectors
2352 // shouldn't be passed in registers for example, so there is no chance they
2353 // can straddle an eightbyte. Verify & simplify.
2354
2355 Lo = Hi = NoClass;
2356
2357 Class &Current = OffsetBase < 64 ? Lo : Hi;
2358 Current = Memory;
2359
John McCall9dd450b2009-09-21 23:43:11 +00002360 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002361 BuiltinType::Kind k = BT->getKind();
2362
2363 if (k == BuiltinType::Void) {
2364 Current = NoClass;
2365 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2366 Lo = Integer;
2367 Hi = Integer;
2368 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2369 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002370 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002371 Current = SSE;
2372 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002373 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2374 if (LDF == &llvm::APFloat::IEEEquad) {
2375 Lo = SSE;
2376 Hi = SSEUp;
2377 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2378 Lo = X87;
2379 Hi = X87Up;
2380 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2381 Current = SSE;
2382 } else
2383 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002384 }
2385 // FIXME: _Decimal32 and _Decimal64 are SSE.
2386 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002387 return;
2388 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002389
Chris Lattnerd776fb12010-06-28 21:43:59 +00002390 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002391 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002392 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002393 return;
2394 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002395
Chris Lattnerd776fb12010-06-28 21:43:59 +00002396 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002397 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002398 return;
2399 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002400
Chris Lattnerd776fb12010-06-28 21:43:59 +00002401 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002402 if (Ty->isMemberFunctionPointerType()) {
2403 if (Has64BitPointers) {
2404 // If Has64BitPointers, this is an {i64, i64}, so classify both
2405 // Lo and Hi now.
2406 Lo = Hi = Integer;
2407 } else {
2408 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2409 // straddles an eightbyte boundary, Hi should be classified as well.
2410 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2411 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2412 if (EB_FuncPtr != EB_ThisAdj) {
2413 Lo = Hi = Integer;
2414 } else {
2415 Current = Integer;
2416 }
2417 }
2418 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002419 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002420 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002421 return;
2422 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002423
Chris Lattnerd776fb12010-06-28 21:43:59 +00002424 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002425 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002426 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2427 // gcc passes the following as integer:
2428 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2429 // 2 bytes - <2 x char>, <1 x short>
2430 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002431 Current = Integer;
2432
2433 // If this type crosses an eightbyte boundary, it should be
2434 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002435 uint64_t EB_Lo = (OffsetBase) / 64;
2436 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2437 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002438 Hi = Lo;
2439 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002440 QualType ElementType = VT->getElementType();
2441
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002442 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002443 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002444 return;
2445
David Majnemere2ae2282016-03-04 05:26:16 +00002446 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2447 // pass them as integer. For platforms where clang is the de facto
2448 // platform compiler, we must continue to use integer.
2449 if (!classifyIntegerMMXAsSSE() &&
2450 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2451 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2452 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2453 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454 Current = Integer;
2455 else
2456 Current = SSE;
2457
2458 // If this type crosses an eightbyte boundary, it should be
2459 // split.
2460 if (OffsetBase && OffsetBase != 64)
2461 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002462 } else if (Size == 128 ||
2463 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002464 // Arguments of 256-bits are split into four eightbyte chunks. The
2465 // least significant one belongs to class SSE and all the others to class
2466 // SSEUP. The original Lo and Hi design considers that types can't be
2467 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2468 // This design isn't correct for 256-bits, but since there're no cases
2469 // where the upper parts would need to be inspected, avoid adding
2470 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002471 //
2472 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2473 // registers if they are "named", i.e. not part of the "..." of a
2474 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002475 //
2476 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2477 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002478 Lo = SSE;
2479 Hi = SSEUp;
2480 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002481 return;
2482 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002483
Chris Lattnerd776fb12010-06-28 21:43:59 +00002484 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002485 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002486
Chris Lattner2b037972010-07-29 02:01:43 +00002487 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002488 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002489 if (Size <= 64)
2490 Current = Integer;
2491 else if (Size <= 128)
2492 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002493 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002494 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002495 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002496 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002497 } else if (ET == getContext().LongDoubleTy) {
2498 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2499 if (LDF == &llvm::APFloat::IEEEquad)
2500 Current = Memory;
2501 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2502 Current = ComplexX87;
2503 else if (LDF == &llvm::APFloat::IEEEdouble)
2504 Lo = Hi = SSE;
2505 else
2506 llvm_unreachable("unexpected long double representation!");
2507 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002508
2509 // If this complex type crosses an eightbyte boundary then it
2510 // should be split.
2511 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002512 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002513 if (Hi == NoClass && EB_Real != EB_Imag)
2514 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002515
Chris Lattnerd776fb12010-06-28 21:43:59 +00002516 return;
2517 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002518
Chris Lattner2b037972010-07-29 02:01:43 +00002519 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002520 // Arrays are treated like structures.
2521
Chris Lattner2b037972010-07-29 02:01:43 +00002522 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002523
2524 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002525 // than eight eightbytes, ..., it has class MEMORY.
2526 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 return;
2528
2529 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2530 // fields, it has class MEMORY.
2531 //
2532 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002533 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002534 return;
2535
2536 // Otherwise implement simplified merge. We could be smarter about
2537 // this, but it isn't worth it and would be harder to verify.
2538 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002539 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002540 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002541
2542 // The only case a 256-bit wide vector could be used is when the array
2543 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2544 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002545 //
2546 if (Size > 128 &&
2547 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002548 return;
2549
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002550 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2551 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002552 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002553 Lo = merge(Lo, FieldLo);
2554 Hi = merge(Hi, FieldHi);
2555 if (Lo == Memory || Hi == Memory)
2556 break;
2557 }
2558
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002559 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002560 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002561 return;
2562 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002563
Chris Lattnerd776fb12010-06-28 21:43:59 +00002564 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002565 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566
2567 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002568 // than eight eightbytes, ..., it has class MEMORY.
2569 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002570 return;
2571
Anders Carlsson20759ad2009-09-16 15:53:40 +00002572 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2573 // copy constructor or a non-trivial destructor, it is passed by invisible
2574 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002575 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002576 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002577
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002578 const RecordDecl *RD = RT->getDecl();
2579
2580 // Assume variable sized types are passed in memory.
2581 if (RD->hasFlexibleArrayMember())
2582 return;
2583
Chris Lattner2b037972010-07-29 02:01:43 +00002584 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002585
2586 // Reset Lo class, this will be recomputed.
2587 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002588
2589 // If this is a C++ record, classify the bases first.
2590 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002591 for (const auto &I : CXXRD->bases()) {
2592 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002593 "Unexpected base class!");
2594 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002595 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002596
2597 // Classify this field.
2598 //
2599 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2600 // single eightbyte, each is classified separately. Each eightbyte gets
2601 // initialized to class NO_CLASS.
2602 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002603 uint64_t Offset =
2604 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002605 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002606 Lo = merge(Lo, FieldLo);
2607 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002608 if (Lo == Memory || Hi == Memory) {
2609 postMerge(Size, Lo, Hi);
2610 return;
2611 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002612 }
2613 }
2614
2615 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002617 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002618 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002619 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2620 bool BitField = i->isBitField();
2621
David Majnemerb439dfe2016-08-15 07:20:40 +00002622 // Ignore padding bit-fields.
2623 if (BitField && i->isUnnamedBitfield())
2624 continue;
2625
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002626 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2627 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002628 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002629 // The only case a 256-bit wide vector could be used is when the struct
2630 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2631 // to work for sizes wider than 128, early check and fallback to memory.
2632 //
David Majnemerb229cb02016-08-15 06:39:18 +00002633 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2634 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002635 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002636 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002637 return;
2638 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002639 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002640 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002641 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002642 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002643 return;
2644 }
2645
2646 // Classify this field.
2647 //
2648 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2649 // exceeds a single eightbyte, each is classified
2650 // separately. Each eightbyte gets initialized to class
2651 // NO_CLASS.
2652 Class FieldLo, FieldHi;
2653
2654 // Bit-fields require special handling, they do not force the
2655 // structure to be passed in memory even if unaligned, and
2656 // therefore they can straddle an eightbyte.
2657 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002658 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002659 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002660 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002661
2662 uint64_t EB_Lo = Offset / 64;
2663 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002664
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002665 if (EB_Lo) {
2666 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2667 FieldLo = NoClass;
2668 FieldHi = Integer;
2669 } else {
2670 FieldLo = Integer;
2671 FieldHi = EB_Hi ? Integer : NoClass;
2672 }
2673 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002674 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002675 Lo = merge(Lo, FieldLo);
2676 Hi = merge(Hi, FieldHi);
2677 if (Lo == Memory || Hi == Memory)
2678 break;
2679 }
2680
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002681 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682 }
2683}
2684
Chris Lattner22a931e2010-06-29 06:01:59 +00002685ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002686 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2687 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002688 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002689 // Treat an enum type as its underlying type.
2690 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2691 Ty = EnumTy->getDecl()->getIntegerType();
2692
2693 return (Ty->isPromotableIntegerType() ?
2694 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2695 }
2696
John McCall7f416cc2015-09-08 08:05:57 +00002697 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002698}
2699
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002700bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2701 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2702 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002703 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002704 if (Size <= 64 || Size > LargestVector)
2705 return true;
2706 }
2707
2708 return false;
2709}
2710
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002711ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2712 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002713 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2714 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002715 //
2716 // This assumption is optimistic, as there could be free registers available
2717 // when we need to pass this argument in memory, and LLVM could try to pass
2718 // the argument in the free register. This does not seem to happen currently,
2719 // but this code would be much safer if we could mark the argument with
2720 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002721 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002722 // Treat an enum type as its underlying type.
2723 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2724 Ty = EnumTy->getDecl()->getIntegerType();
2725
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002726 return (Ty->isPromotableIntegerType() ?
2727 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002728 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002729
Mark Lacey3825e832013-10-06 01:33:34 +00002730 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002731 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002732
Chris Lattner44c2b902011-05-22 23:21:23 +00002733 // Compute the byval alignment. We specify the alignment of the byval in all
2734 // cases so that the mid-level optimizer knows the alignment of the byval.
2735 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002736
2737 // Attempt to avoid passing indirect results using byval when possible. This
2738 // is important for good codegen.
2739 //
2740 // We do this by coercing the value into a scalar type which the backend can
2741 // handle naturally (i.e., without using byval).
2742 //
2743 // For simplicity, we currently only do this when we have exhausted all of the
2744 // free integer registers. Doing this when there are free integer registers
2745 // would require more care, as we would have to ensure that the coerced value
2746 // did not claim the unused register. That would require either reording the
2747 // arguments to the function (so that any subsequent inreg values came first),
2748 // or only doing this optimization when there were no following arguments that
2749 // might be inreg.
2750 //
2751 // We currently expect it to be rare (particularly in well written code) for
2752 // arguments to be passed on the stack when there are still free integer
2753 // registers available (this would typically imply large structs being passed
2754 // by value), so this seems like a fair tradeoff for now.
2755 //
2756 // We can revisit this if the backend grows support for 'onstack' parameter
2757 // attributes. See PR12193.
2758 if (freeIntRegs == 0) {
2759 uint64_t Size = getContext().getTypeSize(Ty);
2760
2761 // If this type fits in an eightbyte, coerce it into the matching integral
2762 // type, which will end up on the stack (with alignment 8).
2763 if (Align == 8 && Size <= 64)
2764 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2765 Size));
2766 }
2767
John McCall7f416cc2015-09-08 08:05:57 +00002768 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002769}
2770
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002771/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2772/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002773llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002774 // Wrapper structs/arrays that only contain vectors are passed just like
2775 // vectors; strip them off if present.
2776 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2777 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002778
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002779 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002780 if (isa<llvm::VectorType>(IRType) ||
2781 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002782 return IRType;
2783
2784 // We couldn't find the preferred IR vector type for 'Ty'.
2785 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002786 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002787
2788 // Return a LLVM IR vector type based on the size of 'Ty'.
2789 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2790 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002791}
2792
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002793/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2794/// is known to either be off the end of the specified type or being in
2795/// alignment padding. The user type specified is known to be at most 128 bits
2796/// in size, and have passed through X86_64ABIInfo::classify with a successful
2797/// classification that put one of the two halves in the INTEGER class.
2798///
2799/// It is conservatively correct to return false.
2800static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2801 unsigned EndBit, ASTContext &Context) {
2802 // If the bytes being queried are off the end of the type, there is no user
2803 // data hiding here. This handles analysis of builtins, vectors and other
2804 // types that don't contain interesting padding.
2805 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2806 if (TySize <= StartBit)
2807 return true;
2808
Chris Lattner98076a22010-07-29 07:43:55 +00002809 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2810 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2811 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2812
2813 // Check each element to see if the element overlaps with the queried range.
2814 for (unsigned i = 0; i != NumElts; ++i) {
2815 // If the element is after the span we care about, then we're done..
2816 unsigned EltOffset = i*EltSize;
2817 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002818
Chris Lattner98076a22010-07-29 07:43:55 +00002819 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2820 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2821 EndBit-EltOffset, Context))
2822 return false;
2823 }
2824 // If it overlaps no elements, then it is safe to process as padding.
2825 return true;
2826 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002827
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002828 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2829 const RecordDecl *RD = RT->getDecl();
2830 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002831
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002832 // If this is a C++ record, check the bases first.
2833 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002834 for (const auto &I : CXXRD->bases()) {
2835 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002836 "Unexpected base class!");
2837 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002838 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002839
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002840 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002841 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002842 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002843
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002844 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002845 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002846 EndBit-BaseOffset, Context))
2847 return false;
2848 }
2849 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002850
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002851 // Verify that no field has data that overlaps the region of interest. Yes
2852 // this could be sped up a lot by being smarter about queried fields,
2853 // however we're only looking at structs up to 16 bytes, so we don't care
2854 // much.
2855 unsigned idx = 0;
2856 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2857 i != e; ++i, ++idx) {
2858 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002859
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002860 // If we found a field after the region we care about, then we're done.
2861 if (FieldOffset >= EndBit) break;
2862
2863 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2864 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2865 Context))
2866 return false;
2867 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002868
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002869 // If nothing in this record overlapped the area of interest, then we're
2870 // clean.
2871 return true;
2872 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002873
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002874 return false;
2875}
2876
Chris Lattnere556a712010-07-29 18:39:32 +00002877/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2878/// float member at the specified offset. For example, {int,{float}} has a
2879/// float at offset 4. It is conservatively correct for this routine to return
2880/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002881static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002882 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002883 // Base case if we find a float.
2884 if (IROffset == 0 && IRType->isFloatTy())
2885 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002886
Chris Lattnere556a712010-07-29 18:39:32 +00002887 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002888 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002889 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2890 unsigned Elt = SL->getElementContainingOffset(IROffset);
2891 IROffset -= SL->getElementOffset(Elt);
2892 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2893 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002894
Chris Lattnere556a712010-07-29 18:39:32 +00002895 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002896 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2897 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002898 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2899 IROffset -= IROffset/EltSize*EltSize;
2900 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2901 }
2902
2903 return false;
2904}
2905
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002906
2907/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2908/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002909llvm::Type *X86_64ABIInfo::
2910GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002911 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002912 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002913 // pass as float if the last 4 bytes is just padding. This happens for
2914 // structs that contain 3 floats.
2915 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2916 SourceOffset*8+64, getContext()))
2917 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002918
Chris Lattnere556a712010-07-29 18:39:32 +00002919 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2920 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2921 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002922 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2923 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002924 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002925
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002926 return llvm::Type::getDoubleTy(getVMContext());
2927}
2928
2929
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002930/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2931/// an 8-byte GPR. This means that we either have a scalar or we are talking
2932/// about the high or low part of an up-to-16-byte struct. This routine picks
2933/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002934/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2935/// etc).
2936///
2937/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2938/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2939/// the 8-byte value references. PrefType may be null.
2940///
Alp Toker9907f082014-07-09 14:06:35 +00002941/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002942/// an offset into this that we're processing (which is always either 0 or 8).
2943///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002944llvm::Type *X86_64ABIInfo::
2945GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002946 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002947 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2948 // returning an 8-byte unit starting with it. See if we can safely use it.
2949 if (IROffset == 0) {
2950 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002951 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2952 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002953 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002954
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002955 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2956 // goodness in the source type is just tail padding. This is allowed to
2957 // kick in for struct {double,int} on the int, but not on
2958 // struct{double,int,int} because we wouldn't return the second int. We
2959 // have to do this analysis on the source type because we can't depend on
2960 // unions being lowered a specific way etc.
2961 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002962 IRType->isIntegerTy(32) ||
2963 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2964 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2965 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002966
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002967 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2968 SourceOffset*8+64, getContext()))
2969 return IRType;
2970 }
2971 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002972
Chris Lattner2192fe52011-07-18 04:24:23 +00002973 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002974 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002975 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002976 if (IROffset < SL->getSizeInBytes()) {
2977 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2978 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002979
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002980 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2981 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002982 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002983 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002984
Chris Lattner2192fe52011-07-18 04:24:23 +00002985 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002986 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002987 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002988 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002989 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2990 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002991 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002992
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002993 // Okay, we don't have any better idea of what to pass, so we pass this in an
2994 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002995 unsigned TySizeInBytes =
2996 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002997
Chris Lattner3f763422010-07-29 17:34:39 +00002998 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002999
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003000 // It is always safe to classify this as an integer type up to i64 that
3001 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003002 return llvm::IntegerType::get(getVMContext(),
3003 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003004}
3005
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003006
3007/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3008/// be used as elements of a two register pair to pass or return, return a
3009/// first class aggregate to represent them. For example, if the low part of
3010/// a by-value argument should be passed as i32* and the high part as float,
3011/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003012static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003013GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003014 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003015 // In order to correctly satisfy the ABI, we need to the high part to start
3016 // at offset 8. If the high and low parts we inferred are both 4-byte types
3017 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3018 // the second element at offset 8. Check for this:
3019 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3020 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003021 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003022 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003023
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003024 // To handle this, we have to increase the size of the low part so that the
3025 // second element will start at an 8 byte offset. We can't increase the size
3026 // of the second element because it might make us access off the end of the
3027 // struct.
3028 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003029 // There are usually two sorts of types the ABI generation code can produce
3030 // for the low part of a pair that aren't 8 bytes in size: float or
3031 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3032 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003033 // Promote these to a larger type.
3034 if (Lo->isFloatTy())
3035 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3036 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003037 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3038 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003039 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3040 }
3041 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003042
Reid Kleckneree7cf842014-12-01 22:02:27 +00003043 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003044
3045
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003046 // Verify that the second element is at an 8-byte offset.
3047 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3048 "Invalid x86-64 argument pair!");
3049 return Result;
3050}
3051
Chris Lattner31faff52010-07-28 23:06:14 +00003052ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003053classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003054 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3055 // classification algorithm.
3056 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003057 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003058
3059 // Check some invariants.
3060 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003061 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3062
Craig Topper8a13c412014-05-21 05:09:00 +00003063 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003064 switch (Lo) {
3065 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003066 if (Hi == NoClass)
3067 return ABIArgInfo::getIgnore();
3068 // If the low part is just padding, it takes no register, leave ResType
3069 // null.
3070 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3071 "Unknown missing lo part");
3072 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003073
3074 case SSEUp:
3075 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003076 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003077
3078 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3079 // hidden argument.
3080 case Memory:
3081 return getIndirectReturnResult(RetTy);
3082
3083 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3084 // available register of the sequence %rax, %rdx is used.
3085 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003086 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003087
Chris Lattner1f3a0632010-07-29 21:42:50 +00003088 // If we have a sign or zero extended integer, make sure to return Extend
3089 // so that the parameter gets the right LLVM IR attributes.
3090 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3091 // Treat an enum type as its underlying type.
3092 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3093 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003094
Chris Lattner1f3a0632010-07-29 21:42:50 +00003095 if (RetTy->isIntegralOrEnumerationType() &&
3096 RetTy->isPromotableIntegerType())
3097 return ABIArgInfo::getExtend();
3098 }
Chris Lattner31faff52010-07-28 23:06:14 +00003099 break;
3100
3101 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3102 // available SSE register of the sequence %xmm0, %xmm1 is used.
3103 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003104 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003105 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003106
3107 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3108 // returned on the X87 stack in %st0 as 80-bit x87 number.
3109 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003110 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003111 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003112
3113 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3114 // part of the value is returned in %st0 and the imaginary part in
3115 // %st1.
3116 case ComplexX87:
3117 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003118 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003119 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003120 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003121 break;
3122 }
3123
Craig Topper8a13c412014-05-21 05:09:00 +00003124 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003125 switch (Hi) {
3126 // Memory was handled previously and X87 should
3127 // never occur as a hi class.
3128 case Memory:
3129 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003130 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003131
3132 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003133 case NoClass:
3134 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003135
Chris Lattner52b3c132010-09-01 00:20:33 +00003136 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003137 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003138 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3139 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003140 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003141 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003142 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003143 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3144 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003145 break;
3146
3147 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003148 // is passed in the next available eightbyte chunk if the last used
3149 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003150 //
Chris Lattner57540c52011-04-15 05:22:18 +00003151 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003152 case SSEUp:
3153 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003154 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003155 break;
3156
3157 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3158 // returned together with the previous X87 value in %st0.
3159 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003160 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003161 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003162 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003163 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003164 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003165 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003166 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3167 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003168 }
Chris Lattner31faff52010-07-28 23:06:14 +00003169 break;
3170 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003171
Chris Lattner52b3c132010-09-01 00:20:33 +00003172 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003173 // known to pass in the high eightbyte of the result. We do this by forming a
3174 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003175 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003176 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003177
Chris Lattner1f3a0632010-07-29 21:42:50 +00003178 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003179}
3180
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003181ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003182 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3183 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003184 const
3185{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003186 Ty = useFirstFieldIfTransparentUnion(Ty);
3187
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003188 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003189 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003190
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003191 // Check some invariants.
3192 // FIXME: Enforce these by construction.
3193 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003194 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3195
3196 neededInt = 0;
3197 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003198 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003199 switch (Lo) {
3200 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003201 if (Hi == NoClass)
3202 return ABIArgInfo::getIgnore();
3203 // If the low part is just padding, it takes no register, leave ResType
3204 // null.
3205 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3206 "Unknown missing lo part");
3207 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003208
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003209 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3210 // on the stack.
3211 case Memory:
3212
3213 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3214 // COMPLEX_X87, it is passed in memory.
3215 case X87:
3216 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003217 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003218 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003219 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003220
3221 case SSEUp:
3222 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003223 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003224
3225 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3226 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3227 // and %r9 is used.
3228 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003229 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003230
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003231 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003232 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003233
3234 // If we have a sign or zero extended integer, make sure to return Extend
3235 // so that the parameter gets the right LLVM IR attributes.
3236 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3237 // Treat an enum type as its underlying type.
3238 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3239 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003240
Chris Lattner1f3a0632010-07-29 21:42:50 +00003241 if (Ty->isIntegralOrEnumerationType() &&
3242 Ty->isPromotableIntegerType())
3243 return ABIArgInfo::getExtend();
3244 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003245
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003246 break;
3247
3248 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3249 // available SSE register is used, the registers are taken in the
3250 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003251 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003252 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003253 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003254 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003255 break;
3256 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003257 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003258
Craig Topper8a13c412014-05-21 05:09:00 +00003259 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003260 switch (Hi) {
3261 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003262 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003263 // which is passed in memory.
3264 case Memory:
3265 case X87:
3266 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003267 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003268
3269 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003270
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003271 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003272 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003273 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003274 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003275
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003276 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3277 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003278 break;
3279
3280 // X87Up generally doesn't occur here (long double is passed in
3281 // memory), except in situations involving unions.
3282 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003283 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003284 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003285
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003286 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3287 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003288
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003289 ++neededSSE;
3290 break;
3291
3292 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3293 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003294 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003295 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003296 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003297 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003298 break;
3299 }
3300
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003301 // If a high part was specified, merge it together with the low part. It is
3302 // known to pass in the high eightbyte of the result. We do this by forming a
3303 // first class struct aggregate with the high and low part: {low, high}
3304 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003305 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003306
Chris Lattner1f3a0632010-07-29 21:42:50 +00003307 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003308}
3309
Erich Keane757d3172016-11-02 18:29:35 +00003310ABIArgInfo
3311X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3312 unsigned &NeededSSE) const {
3313 auto RT = Ty->getAs<RecordType>();
3314 assert(RT && "classifyRegCallStructType only valid with struct types");
3315
3316 if (RT->getDecl()->hasFlexibleArrayMember())
3317 return getIndirectReturnResult(Ty);
3318
3319 // Sum up bases
3320 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3321 if (CXXRD->isDynamicClass()) {
3322 NeededInt = NeededSSE = 0;
3323 return getIndirectReturnResult(Ty);
3324 }
3325
3326 for (const auto &I : CXXRD->bases())
3327 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3328 .isIndirect()) {
3329 NeededInt = NeededSSE = 0;
3330 return getIndirectReturnResult(Ty);
3331 }
3332 }
3333
3334 // Sum up members
3335 for (const auto *FD : RT->getDecl()->fields()) {
3336 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3337 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3338 .isIndirect()) {
3339 NeededInt = NeededSSE = 0;
3340 return getIndirectReturnResult(Ty);
3341 }
3342 } else {
3343 unsigned LocalNeededInt, LocalNeededSSE;
3344 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3345 LocalNeededSSE, true)
3346 .isIndirect()) {
3347 NeededInt = NeededSSE = 0;
3348 return getIndirectReturnResult(Ty);
3349 }
3350 NeededInt += LocalNeededInt;
3351 NeededSSE += LocalNeededSSE;
3352 }
3353 }
3354
3355 return ABIArgInfo::getDirect();
3356}
3357
3358ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3359 unsigned &NeededInt,
3360 unsigned &NeededSSE) const {
3361
3362 NeededInt = 0;
3363 NeededSSE = 0;
3364
3365 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3366}
3367
Chris Lattner22326a12010-07-29 02:31:05 +00003368void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003369
Erich Keane757d3172016-11-02 18:29:35 +00003370 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003371
3372 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003373 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3374 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3375 unsigned NeededInt, NeededSSE;
3376
3377 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3378 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3379 FI.getReturnInfo() =
3380 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3381 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3382 FreeIntRegs -= NeededInt;
3383 FreeSSERegs -= NeededSSE;
3384 } else {
3385 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3386 }
3387 } else if (!getCXXABI().classifyReturnType(FI))
3388 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003389
3390 // If the return value is indirect, then the hidden argument is consuming one
3391 // integer register.
3392 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003393 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003394
Peter Collingbournef7706832014-12-12 23:41:25 +00003395 // The chain argument effectively gives us another free register.
3396 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003397 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003398
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003399 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003400 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3401 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003402 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003403 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003404 it != ie; ++it, ++ArgNo) {
3405 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003406
Erich Keane757d3172016-11-02 18:29:35 +00003407 if (IsRegCall && it->type->isStructureOrClassType())
3408 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3409 else
3410 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3411 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003412
3413 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3414 // eightbyte of an argument, the whole argument is passed on the
3415 // stack. If registers have already been assigned for some
3416 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003417 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3418 FreeIntRegs -= NeededInt;
3419 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003420 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003421 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003422 }
3423 }
3424}
3425
John McCall7f416cc2015-09-08 08:05:57 +00003426static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3427 Address VAListAddr, QualType Ty) {
3428 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3429 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003430 llvm::Value *overflow_arg_area =
3431 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3432
3433 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3434 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003435 // It isn't stated explicitly in the standard, but in practice we use
3436 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003437 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3438 if (Align > CharUnits::fromQuantity(8)) {
3439 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3440 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003441 }
3442
3443 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003444 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003445 llvm::Value *Res =
3446 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003447 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003448
3449 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3450 // l->overflow_arg_area + sizeof(type).
3451 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3452 // an 8 byte boundary.
3453
3454 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003455 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003456 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003457 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3458 "overflow_arg_area.next");
3459 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3460
3461 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003462 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003463}
3464
John McCall7f416cc2015-09-08 08:05:57 +00003465Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3466 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003467 // Assume that va_list type is correct; should be pointer to LLVM type:
3468 // struct {
3469 // i32 gp_offset;
3470 // i32 fp_offset;
3471 // i8* overflow_arg_area;
3472 // i8* reg_save_area;
3473 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003474 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003475
John McCall7f416cc2015-09-08 08:05:57 +00003476 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003477 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003478 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003479
3480 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3481 // in the registers. If not go to step 7.
3482 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003483 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003484
3485 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3486 // general purpose registers needed to pass type and num_fp to hold
3487 // the number of floating point registers needed.
3488
3489 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3490 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3491 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3492 //
3493 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3494 // register save space).
3495
Craig Topper8a13c412014-05-21 05:09:00 +00003496 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003497 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3498 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003499 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003500 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003501 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3502 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003503 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003504 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3505 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003506 }
3507
3508 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003509 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003510 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3511 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003512 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3513 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003514 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3515 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003516 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3517 }
3518
3519 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3520 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3521 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3522 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3523
3524 // Emit code to load the value if it was passed in registers.
3525
3526 CGF.EmitBlock(InRegBlock);
3527
3528 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3529 // an offset of l->gp_offset and/or l->fp_offset. This may require
3530 // copying to a temporary location in case the parameter is passed
3531 // in different register classes or requires an alignment greater
3532 // than 8 for general purpose registers and 16 for XMM registers.
3533 //
3534 // FIXME: This really results in shameful code when we end up needing to
3535 // collect arguments from different places; often what should result in a
3536 // simple assembling of a structure from scattered addresses has many more
3537 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003538 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003539 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3540 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3541 "reg_save_area");
3542
3543 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003544 if (neededInt && neededSSE) {
3545 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003546 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003547 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003548 Address Tmp = CGF.CreateMemTemp(Ty);
3549 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003550 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003551 llvm::Type *TyLo = ST->getElementType(0);
3552 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003553 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003554 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003555 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3556 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003557 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3558 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003559 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3560 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003561
John McCall7f416cc2015-09-08 08:05:57 +00003562 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003563 // FIXME: Our choice of alignment here and below is probably pessimistic.
3564 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3565 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3566 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003567 CGF.Builder.CreateStore(V,
3568 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3569
3570 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003571 V = CGF.Builder.CreateAlignedLoad(
3572 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3573 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003574 CharUnits Offset = CharUnits::fromQuantity(
3575 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3576 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3577
3578 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003579 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003580 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3581 CharUnits::fromQuantity(8));
3582 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003583
3584 // Copy to a temporary if necessary to ensure the appropriate alignment.
3585 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003586 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003587 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003588 CharUnits TyAlign = SizeAlign.second;
3589
3590 // Copy into a temporary if the type is more aligned than the
3591 // register save area.
3592 if (TyAlign.getQuantity() > 8) {
3593 Address Tmp = CGF.CreateMemTemp(Ty);
3594 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003595 RegAddr = Tmp;
3596 }
John McCall7f416cc2015-09-08 08:05:57 +00003597
Chris Lattner0cf24192010-06-28 20:05:43 +00003598 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003599 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3600 CharUnits::fromQuantity(16));
3601 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003602 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003603 assert(neededSSE == 2 && "Invalid number of needed registers!");
3604 // SSE registers are spaced 16 bytes apart in the register save
3605 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003606 // The ABI isn't explicit about this, but it seems reasonable
3607 // to assume that the slots are 16-byte aligned, since the stack is
3608 // naturally 16-byte aligned and the prologue is expected to store
3609 // all the SSE registers to the RSA.
3610 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3611 CharUnits::fromQuantity(16));
3612 Address RegAddrHi =
3613 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3614 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003615 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003616 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003617 llvm::Value *V;
3618 Address Tmp = CGF.CreateMemTemp(Ty);
3619 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3620 V = CGF.Builder.CreateLoad(
3621 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3622 CGF.Builder.CreateStore(V,
3623 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3624 V = CGF.Builder.CreateLoad(
3625 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3626 CGF.Builder.CreateStore(V,
3627 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3628
3629 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003630 }
3631
3632 // AMD64-ABI 3.5.7p5: Step 5. Set:
3633 // l->gp_offset = l->gp_offset + num_gp * 8
3634 // l->fp_offset = l->fp_offset + num_fp * 16.
3635 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003636 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003637 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3638 gp_offset_p);
3639 }
3640 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003641 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003642 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3643 fp_offset_p);
3644 }
3645 CGF.EmitBranch(ContBlock);
3646
3647 // Emit code to load the value if it was passed in memory.
3648
3649 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003650 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003651
3652 // Return the appropriate result.
3653
3654 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003655 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3656 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003657 return ResAddr;
3658}
3659
Charles Davisc7d5c942015-09-17 20:55:33 +00003660Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3661 QualType Ty) const {
3662 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3663 CGF.getContext().getTypeInfoInChars(Ty),
3664 CharUnits::fromQuantity(8),
3665 /*allowHigherAlign*/ false);
3666}
3667
Reid Kleckner80944df2014-10-31 22:00:51 +00003668ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3669 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003670
3671 if (Ty->isVoidType())
3672 return ABIArgInfo::getIgnore();
3673
3674 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3675 Ty = EnumTy->getDecl()->getIntegerType();
3676
Reid Kleckner80944df2014-10-31 22:00:51 +00003677 TypeInfo Info = getContext().getTypeInfo(Ty);
3678 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003679 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003680
Reid Kleckner9005f412014-05-02 00:51:20 +00003681 const RecordType *RT = Ty->getAs<RecordType>();
3682 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003683 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003684 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003685 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003686 }
3687
3688 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003689 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003690
Reid Kleckner9005f412014-05-02 00:51:20 +00003691 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003692
Reid Kleckner80944df2014-10-31 22:00:51 +00003693 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3694 // other targets.
3695 const Type *Base = nullptr;
3696 uint64_t NumElts = 0;
3697 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3698 if (FreeSSERegs >= NumElts) {
3699 FreeSSERegs -= NumElts;
3700 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3701 return ABIArgInfo::getDirect();
3702 return ABIArgInfo::getExpand();
3703 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003704 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003705 }
3706
3707
Reid Klecknerec87fec2014-05-02 01:17:12 +00003708 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003709 // If the member pointer is represented by an LLVM int or ptr, pass it
3710 // directly.
3711 llvm::Type *LLTy = CGT.ConvertType(Ty);
3712 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3713 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003714 }
3715
Michael Kuperstein4f818702015-02-24 09:35:58 +00003716 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003717 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3718 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003719 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003720 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003721
Reid Kleckner9005f412014-05-02 00:51:20 +00003722 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003723 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003724 }
3725
Julien Lerouge10dcff82014-08-27 00:36:55 +00003726 // Bool type is always extended to the ABI, other builtin types are not
3727 // extended.
3728 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3729 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003730 return ABIArgInfo::getExtend();
3731
Reid Kleckner11a17192015-10-28 22:29:52 +00003732 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3733 // passes them indirectly through memory.
3734 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3735 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3736 if (LDF == &llvm::APFloat::x87DoubleExtended)
3737 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3738 }
3739
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003740 return ABIArgInfo::getDirect();
3741}
3742
3743void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003744 bool IsVectorCall =
3745 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003746 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003747
Erich Keane757d3172016-11-02 18:29:35 +00003748 unsigned FreeSSERegs = 0;
3749 if (IsVectorCall) {
3750 // We can use up to 4 SSE return registers with vectorcall.
3751 FreeSSERegs = 4;
3752 } else if (IsRegCall) {
3753 // RegCall gives us 16 SSE registers.
3754 FreeSSERegs = 16;
3755 }
3756
Reid Kleckner80944df2014-10-31 22:00:51 +00003757 if (!getCXXABI().classifyReturnType(FI))
3758 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3759
Erich Keane757d3172016-11-02 18:29:35 +00003760 if (IsVectorCall) {
3761 // We can use up to 6 SSE register parameters with vectorcall.
3762 FreeSSERegs = 6;
3763 } else if (IsRegCall) {
3764 FreeSSERegs = 16;
3765 }
3766
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003767 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003768 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003769}
3770
John McCall7f416cc2015-09-08 08:05:57 +00003771Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3772 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003773
3774 bool IsIndirect = false;
3775
3776 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3777 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3778 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3779 uint64_t Width = getContext().getTypeSize(Ty);
3780 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3781 }
3782
3783 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00003784 CGF.getContext().getTypeInfoInChars(Ty),
3785 CharUnits::fromQuantity(8),
3786 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003787}
Chris Lattner0cf24192010-06-28 20:05:43 +00003788
John McCallea8d8bb2010-03-11 00:10:12 +00003789// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003790namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003791/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3792class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003793bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003794public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003795 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3796 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003797
John McCall7f416cc2015-09-08 08:05:57 +00003798 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3799 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003800};
3801
3802class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3803public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003804 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3805 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003806
Craig Topper4f12f102014-03-12 06:41:41 +00003807 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003808 // This is recovered from gcc output.
3809 return 1; // r1 is the dedicated stack pointer
3810 }
3811
3812 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003813 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003814};
3815
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003816}
John McCallea8d8bb2010-03-11 00:10:12 +00003817
James Y Knight29b5f082016-02-24 02:59:33 +00003818// TODO: this implementation is now likely redundant with
3819// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003820Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3821 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003822 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003823 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3824 // TODO: Implement this. For now ignore.
3825 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003826 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003827 }
3828
John McCall7f416cc2015-09-08 08:05:57 +00003829 // struct __va_list_tag {
3830 // unsigned char gpr;
3831 // unsigned char fpr;
3832 // unsigned short reserved;
3833 // void *overflow_arg_area;
3834 // void *reg_save_area;
3835 // };
3836
Roman Divacky8a12d842014-11-03 18:32:54 +00003837 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003838 bool isInt =
3839 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003840 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003841
3842 // All aggregates are passed indirectly? That doesn't seem consistent
3843 // with the argument-lowering code.
3844 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003845
3846 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003847
3848 // The calling convention either uses 1-2 GPRs or 1 FPR.
3849 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003850 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003851 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3852 } else {
3853 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003854 }
John McCall7f416cc2015-09-08 08:05:57 +00003855
3856 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3857
3858 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003859 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003860 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3861 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3862 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003863
Eric Christopher7565e0d2015-05-29 23:09:49 +00003864 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003865 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003866
3867 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3868 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3869 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3870
3871 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3872
John McCall7f416cc2015-09-08 08:05:57 +00003873 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3874 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003875
John McCall7f416cc2015-09-08 08:05:57 +00003876 // Case 1: consume registers.
3877 Address RegAddr = Address::invalid();
3878 {
3879 CGF.EmitBlock(UsingRegs);
3880
3881 Address RegSaveAreaPtr =
3882 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3883 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3884 CharUnits::fromQuantity(8));
3885 assert(RegAddr.getElementType() == CGF.Int8Ty);
3886
3887 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003888 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003889 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3890 CharUnits::fromQuantity(32));
3891 }
3892
3893 // Get the address of the saved value by scaling the number of
3894 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003895 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003896 llvm::Value *RegOffset =
3897 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3898 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3899 RegAddr.getPointer(), RegOffset),
3900 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3901 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3902
3903 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003904 NumRegs =
3905 Builder.CreateAdd(NumRegs,
3906 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003907 Builder.CreateStore(NumRegs, NumRegsAddr);
3908
3909 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003910 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003911
John McCall7f416cc2015-09-08 08:05:57 +00003912 // Case 2: consume space in the overflow area.
3913 Address MemAddr = Address::invalid();
3914 {
3915 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003916
Roman Divacky039b9702016-02-20 08:31:24 +00003917 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3918
John McCall7f416cc2015-09-08 08:05:57 +00003919 // Everything in the overflow area is rounded up to a size of at least 4.
3920 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3921
3922 CharUnits Size;
3923 if (!isIndirect) {
3924 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003925 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003926 } else {
3927 Size = CGF.getPointerSize();
3928 }
3929
3930 Address OverflowAreaAddr =
3931 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003932 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003933 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003934 // Round up address of argument to alignment
3935 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3936 if (Align > OverflowAreaAlign) {
3937 llvm::Value *Ptr = OverflowArea.getPointer();
3938 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3939 Align);
3940 }
3941
John McCall7f416cc2015-09-08 08:05:57 +00003942 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3943
3944 // Increase the overflow area.
3945 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3946 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3947 CGF.EmitBranch(Cont);
3948 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003949
3950 CGF.EmitBlock(Cont);
3951
John McCall7f416cc2015-09-08 08:05:57 +00003952 // Merge the cases with a phi.
3953 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3954 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003955
John McCall7f416cc2015-09-08 08:05:57 +00003956 // Load the pointer if the argument was passed indirectly.
3957 if (isIndirect) {
3958 Result = Address(Builder.CreateLoad(Result, "aggr"),
3959 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003960 }
3961
3962 return Result;
3963}
3964
John McCallea8d8bb2010-03-11 00:10:12 +00003965bool
3966PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3967 llvm::Value *Address) const {
3968 // This is calculated from the LLVM and GCC tables and verified
3969 // against gcc output. AFAIK all ABIs use the same encoding.
3970
3971 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003972
Chris Lattnerece04092012-02-07 00:39:47 +00003973 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003974 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3975 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3976 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3977
3978 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003979 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003980
3981 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003982 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003983
3984 // 64-76 are various 4-byte special-purpose registers:
3985 // 64: mq
3986 // 65: lr
3987 // 66: ctr
3988 // 67: ap
3989 // 68-75 cr0-7
3990 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003991 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003992
3993 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003994 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003995
3996 // 109: vrsave
3997 // 110: vscr
3998 // 111: spe_acc
3999 // 112: spefscr
4000 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004001 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004002
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004003 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004004}
4005
Roman Divackyd966e722012-05-09 18:22:46 +00004006// PowerPC-64
4007
4008namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004009/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004010class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004011public:
4012 enum ABIKind {
4013 ELFv1 = 0,
4014 ELFv2
4015 };
4016
4017private:
4018 static const unsigned GPRBits = 64;
4019 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004020 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004021 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004022
4023 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4024 // will be passed in a QPX register.
4025 bool IsQPXVectorTy(const Type *Ty) const {
4026 if (!HasQPX)
4027 return false;
4028
4029 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4030 unsigned NumElements = VT->getNumElements();
4031 if (NumElements == 1)
4032 return false;
4033
4034 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4035 if (getContext().getTypeSize(Ty) <= 256)
4036 return true;
4037 } else if (VT->getElementType()->
4038 isSpecificBuiltinType(BuiltinType::Float)) {
4039 if (getContext().getTypeSize(Ty) <= 128)
4040 return true;
4041 }
4042 }
4043
4044 return false;
4045 }
4046
4047 bool IsQPXVectorTy(QualType Ty) const {
4048 return IsQPXVectorTy(Ty.getTypePtr());
4049 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004050
4051public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004052 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4053 bool SoftFloatABI)
4054 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4055 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004056
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004057 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004058 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004059
4060 ABIArgInfo classifyReturnType(QualType RetTy) const;
4061 ABIArgInfo classifyArgumentType(QualType Ty) const;
4062
Reid Klecknere9f6a712014-10-31 17:10:41 +00004063 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4064 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4065 uint64_t Members) const override;
4066
Bill Schmidt84d37792012-10-12 19:26:17 +00004067 // TODO: We can add more logic to computeInfo to improve performance.
4068 // Example: For aggregate arguments that fit in a register, we could
4069 // use getDirectInReg (as is done below for structs containing a single
4070 // floating-point value) to avoid pushing them to memory on function
4071 // entry. This would require changing the logic in PPCISelLowering
4072 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004073 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004074 if (!getCXXABI().classifyReturnType(FI))
4075 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004076 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004077 // We rely on the default argument classification for the most part.
4078 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004079 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004080 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004081 if (T) {
4082 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004083 if (IsQPXVectorTy(T) ||
4084 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004085 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004086 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004087 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004088 continue;
4089 }
4090 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004091 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004092 }
4093 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004094
John McCall7f416cc2015-09-08 08:05:57 +00004095 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4096 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004097};
4098
4099class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004100
Bill Schmidt25cb3492012-10-03 19:18:57 +00004101public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004102 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004103 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4104 bool SoftFloatABI)
4105 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4106 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004107
Craig Topper4f12f102014-03-12 06:41:41 +00004108 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004109 // This is recovered from gcc output.
4110 return 1; // r1 is the dedicated stack pointer
4111 }
4112
4113 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004114 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004115};
4116
Roman Divackyd966e722012-05-09 18:22:46 +00004117class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4118public:
4119 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4120
Craig Topper4f12f102014-03-12 06:41:41 +00004121 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004122 // This is recovered from gcc output.
4123 return 1; // r1 is the dedicated stack pointer
4124 }
4125
4126 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004127 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004128};
4129
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004130}
Roman Divackyd966e722012-05-09 18:22:46 +00004131
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004132// Return true if the ABI requires Ty to be passed sign- or zero-
4133// extended to 64 bits.
4134bool
4135PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4136 // Treat an enum type as its underlying type.
4137 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4138 Ty = EnumTy->getDecl()->getIntegerType();
4139
4140 // Promotable integer types are required to be promoted by the ABI.
4141 if (Ty->isPromotableIntegerType())
4142 return true;
4143
4144 // In addition to the usual promotable integer types, we also need to
4145 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4146 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4147 switch (BT->getKind()) {
4148 case BuiltinType::Int:
4149 case BuiltinType::UInt:
4150 return true;
4151 default:
4152 break;
4153 }
4154
4155 return false;
4156}
4157
John McCall7f416cc2015-09-08 08:05:57 +00004158/// isAlignedParamType - Determine whether a type requires 16-byte or
4159/// higher alignment in the parameter area. Always returns at least 8.
4160CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004161 // Complex types are passed just like their elements.
4162 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4163 Ty = CTy->getElementType();
4164
4165 // Only vector types of size 16 bytes need alignment (larger types are
4166 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004167 if (IsQPXVectorTy(Ty)) {
4168 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004169 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004170
John McCall7f416cc2015-09-08 08:05:57 +00004171 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004172 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004173 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004174 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004175
4176 // For single-element float/vector structs, we consider the whole type
4177 // to have the same alignment requirements as its single element.
4178 const Type *AlignAsType = nullptr;
4179 const Type *EltType = isSingleElementStruct(Ty, getContext());
4180 if (EltType) {
4181 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004182 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004183 getContext().getTypeSize(EltType) == 128) ||
4184 (BT && BT->isFloatingPoint()))
4185 AlignAsType = EltType;
4186 }
4187
Ulrich Weigandb7122372014-07-21 00:48:09 +00004188 // Likewise for ELFv2 homogeneous aggregates.
4189 const Type *Base = nullptr;
4190 uint64_t Members = 0;
4191 if (!AlignAsType && Kind == ELFv2 &&
4192 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4193 AlignAsType = Base;
4194
Ulrich Weigand581badc2014-07-10 17:20:07 +00004195 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004196 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4197 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004198 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004199
John McCall7f416cc2015-09-08 08:05:57 +00004200 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004201 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004202 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004203 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004204
4205 // Otherwise, we only need alignment for any aggregate type that
4206 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004207 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4208 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004209 return CharUnits::fromQuantity(32);
4210 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004211 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004212
John McCall7f416cc2015-09-08 08:05:57 +00004213 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004214}
4215
Ulrich Weigandb7122372014-07-21 00:48:09 +00004216/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4217/// aggregate. Base is set to the base element type, and Members is set
4218/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004219bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4220 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004221 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4222 uint64_t NElements = AT->getSize().getZExtValue();
4223 if (NElements == 0)
4224 return false;
4225 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4226 return false;
4227 Members *= NElements;
4228 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4229 const RecordDecl *RD = RT->getDecl();
4230 if (RD->hasFlexibleArrayMember())
4231 return false;
4232
4233 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004234
4235 // If this is a C++ record, check the bases first.
4236 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4237 for (const auto &I : CXXRD->bases()) {
4238 // Ignore empty records.
4239 if (isEmptyRecord(getContext(), I.getType(), true))
4240 continue;
4241
4242 uint64_t FldMembers;
4243 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4244 return false;
4245
4246 Members += FldMembers;
4247 }
4248 }
4249
Ulrich Weigandb7122372014-07-21 00:48:09 +00004250 for (const auto *FD : RD->fields()) {
4251 // Ignore (non-zero arrays of) empty records.
4252 QualType FT = FD->getType();
4253 while (const ConstantArrayType *AT =
4254 getContext().getAsConstantArrayType(FT)) {
4255 if (AT->getSize().getZExtValue() == 0)
4256 return false;
4257 FT = AT->getElementType();
4258 }
4259 if (isEmptyRecord(getContext(), FT, true))
4260 continue;
4261
4262 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4263 if (getContext().getLangOpts().CPlusPlus &&
4264 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4265 continue;
4266
4267 uint64_t FldMembers;
4268 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4269 return false;
4270
4271 Members = (RD->isUnion() ?
4272 std::max(Members, FldMembers) : Members + FldMembers);
4273 }
4274
4275 if (!Base)
4276 return false;
4277
4278 // Ensure there is no padding.
4279 if (getContext().getTypeSize(Base) * Members !=
4280 getContext().getTypeSize(Ty))
4281 return false;
4282 } else {
4283 Members = 1;
4284 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4285 Members = 2;
4286 Ty = CT->getElementType();
4287 }
4288
Reid Klecknere9f6a712014-10-31 17:10:41 +00004289 // Most ABIs only support float, double, and some vector type widths.
4290 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004291 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004292
4293 // The base type must be the same for all members. Types that
4294 // agree in both total size and mode (float vs. vector) are
4295 // treated as being equivalent here.
4296 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004297 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004298 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004299 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4300 // so make sure to widen it explicitly.
4301 if (const VectorType *VT = Base->getAs<VectorType>()) {
4302 QualType EltTy = VT->getElementType();
4303 unsigned NumElements =
4304 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4305 Base = getContext()
4306 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4307 .getTypePtr();
4308 }
4309 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004310
4311 if (Base->isVectorType() != TyPtr->isVectorType() ||
4312 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4313 return false;
4314 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004315 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4316}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004317
Reid Klecknere9f6a712014-10-31 17:10:41 +00004318bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4319 // Homogeneous aggregates for ELFv2 must have base types of float,
4320 // double, long double, or 128-bit vectors.
4321 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4322 if (BT->getKind() == BuiltinType::Float ||
4323 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004324 BT->getKind() == BuiltinType::LongDouble) {
4325 if (IsSoftFloatABI)
4326 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004327 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004328 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004329 }
4330 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004331 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004332 return true;
4333 }
4334 return false;
4335}
4336
4337bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4338 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004339 // Vector types require one register, floating point types require one
4340 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004341 uint32_t NumRegs =
4342 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004343
4344 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004345 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004346}
4347
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004348ABIArgInfo
4349PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004350 Ty = useFirstFieldIfTransparentUnion(Ty);
4351
Bill Schmidt90b22c92012-11-27 02:46:43 +00004352 if (Ty->isAnyComplexType())
4353 return ABIArgInfo::getDirect();
4354
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004355 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4356 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004357 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004358 uint64_t Size = getContext().getTypeSize(Ty);
4359 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004360 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004361 else if (Size < 128) {
4362 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4363 return ABIArgInfo::getDirect(CoerceTy);
4364 }
4365 }
4366
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004367 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004368 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004369 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004370
John McCall7f416cc2015-09-08 08:05:57 +00004371 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4372 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004373
4374 // ELFv2 homogeneous aggregates are passed as array types.
4375 const Type *Base = nullptr;
4376 uint64_t Members = 0;
4377 if (Kind == ELFv2 &&
4378 isHomogeneousAggregate(Ty, Base, Members)) {
4379 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4380 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4381 return ABIArgInfo::getDirect(CoerceTy);
4382 }
4383
Ulrich Weigand601957f2014-07-21 00:56:36 +00004384 // If an aggregate may end up fully in registers, we do not
4385 // use the ByVal method, but pass the aggregate as array.
4386 // This is usually beneficial since we avoid forcing the
4387 // back-end to store the argument to memory.
4388 uint64_t Bits = getContext().getTypeSize(Ty);
4389 if (Bits > 0 && Bits <= 8 * GPRBits) {
4390 llvm::Type *CoerceTy;
4391
4392 // Types up to 8 bytes are passed as integer type (which will be
4393 // properly aligned in the argument save area doubleword).
4394 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004395 CoerceTy =
4396 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004397 // Larger types are passed as arrays, with the base type selected
4398 // according to the required alignment in the save area.
4399 else {
4400 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004401 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004402 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4403 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4404 }
4405
4406 return ABIArgInfo::getDirect(CoerceTy);
4407 }
4408
Ulrich Weigandb7122372014-07-21 00:48:09 +00004409 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004410 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4411 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004412 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004413 }
4414
4415 return (isPromotableTypeForABI(Ty) ?
4416 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4417}
4418
4419ABIArgInfo
4420PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4421 if (RetTy->isVoidType())
4422 return ABIArgInfo::getIgnore();
4423
Bill Schmidta3d121c2012-12-17 04:20:17 +00004424 if (RetTy->isAnyComplexType())
4425 return ABIArgInfo::getDirect();
4426
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004427 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4428 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004429 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004430 uint64_t Size = getContext().getTypeSize(RetTy);
4431 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004432 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004433 else if (Size < 128) {
4434 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4435 return ABIArgInfo::getDirect(CoerceTy);
4436 }
4437 }
4438
Ulrich Weigandb7122372014-07-21 00:48:09 +00004439 if (isAggregateTypeForABI(RetTy)) {
4440 // ELFv2 homogeneous aggregates are returned as array types.
4441 const Type *Base = nullptr;
4442 uint64_t Members = 0;
4443 if (Kind == ELFv2 &&
4444 isHomogeneousAggregate(RetTy, Base, Members)) {
4445 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4446 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4447 return ABIArgInfo::getDirect(CoerceTy);
4448 }
4449
4450 // ELFv2 small aggregates are returned in up to two registers.
4451 uint64_t Bits = getContext().getTypeSize(RetTy);
4452 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4453 if (Bits == 0)
4454 return ABIArgInfo::getIgnore();
4455
4456 llvm::Type *CoerceTy;
4457 if (Bits > GPRBits) {
4458 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004459 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004460 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004461 CoerceTy =
4462 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004463 return ABIArgInfo::getDirect(CoerceTy);
4464 }
4465
4466 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004467 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004468 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004469
4470 return (isPromotableTypeForABI(RetTy) ?
4471 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4472}
4473
Bill Schmidt25cb3492012-10-03 19:18:57 +00004474// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004475Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4476 QualType Ty) const {
4477 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4478 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004479
John McCall7f416cc2015-09-08 08:05:57 +00004480 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004481
Bill Schmidt924c4782013-01-14 17:45:36 +00004482 // If we have a complex type and the base type is smaller than 8 bytes,
4483 // the ABI calls for the real and imaginary parts to be right-adjusted
4484 // in separate doublewords. However, Clang expects us to produce a
4485 // pointer to a structure with the two parts packed tightly. So generate
4486 // loads of the real and imaginary parts relative to the va_list pointer,
4487 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004488 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4489 CharUnits EltSize = TypeInfo.first / 2;
4490 if (EltSize < SlotSize) {
4491 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4492 SlotSize * 2, SlotSize,
4493 SlotSize, /*AllowHigher*/ true);
4494
4495 Address RealAddr = Addr;
4496 Address ImagAddr = RealAddr;
4497 if (CGF.CGM.getDataLayout().isBigEndian()) {
4498 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4499 SlotSize - EltSize);
4500 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4501 2 * SlotSize - EltSize);
4502 } else {
4503 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4504 }
4505
4506 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4507 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4508 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4509 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4510 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4511
4512 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4513 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4514 /*init*/ true);
4515 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004516 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004517 }
4518
John McCall7f416cc2015-09-08 08:05:57 +00004519 // Otherwise, just use the general rule.
4520 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4521 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004522}
4523
4524static bool
4525PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4526 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004527 // This is calculated from the LLVM and GCC tables and verified
4528 // against gcc output. AFAIK all ABIs use the same encoding.
4529
4530 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4531
4532 llvm::IntegerType *i8 = CGF.Int8Ty;
4533 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4534 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4535 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4536
4537 // 0-31: r0-31, the 8-byte general-purpose registers
4538 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4539
4540 // 32-63: fp0-31, the 8-byte floating-point registers
4541 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4542
Hal Finkel84832a72016-08-30 02:38:34 +00004543 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004544 // 64: mq
4545 // 65: lr
4546 // 66: ctr
4547 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004548 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4549
4550 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004551 // 68-75 cr0-7
4552 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004553 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004554
4555 // 77-108: v0-31, the 16-byte vector registers
4556 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4557
4558 // 109: vrsave
4559 // 110: vscr
4560 // 111: spe_acc
4561 // 112: spefscr
4562 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004563 // 114: tfhar
4564 // 115: tfiar
4565 // 116: texasr
4566 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004567
4568 return false;
4569}
John McCallea8d8bb2010-03-11 00:10:12 +00004570
Bill Schmidt25cb3492012-10-03 19:18:57 +00004571bool
4572PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4573 CodeGen::CodeGenFunction &CGF,
4574 llvm::Value *Address) const {
4575
4576 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4577}
4578
4579bool
4580PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4581 llvm::Value *Address) const {
4582
4583 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4584}
4585
Chris Lattner0cf24192010-06-28 20:05:43 +00004586//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004587// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004588//===----------------------------------------------------------------------===//
4589
4590namespace {
4591
John McCall12f23522016-04-04 18:33:08 +00004592class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004593public:
4594 enum ABIKind {
4595 AAPCS = 0,
4596 DarwinPCS
4597 };
4598
4599private:
4600 ABIKind Kind;
4601
4602public:
John McCall12f23522016-04-04 18:33:08 +00004603 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4604 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004605
4606private:
4607 ABIKind getABIKind() const { return Kind; }
4608 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4609
4610 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004611 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004612 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4613 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4614 uint64_t Members) const override;
4615
Tim Northovera2ee4332014-03-29 15:09:45 +00004616 bool isIllegalVectorType(QualType Ty) const;
4617
David Blaikie1cbb9712014-11-14 19:09:44 +00004618 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004619 if (!getCXXABI().classifyReturnType(FI))
4620 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004621
Tim Northoverb047bfa2014-11-27 21:02:49 +00004622 for (auto &it : FI.arguments())
4623 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004624 }
4625
John McCall7f416cc2015-09-08 08:05:57 +00004626 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4627 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004628
John McCall7f416cc2015-09-08 08:05:57 +00004629 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4630 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004631
John McCall7f416cc2015-09-08 08:05:57 +00004632 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4633 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004634 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4635 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4636 }
John McCall12f23522016-04-04 18:33:08 +00004637
4638 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4639 ArrayRef<llvm::Type*> scalars,
4640 bool asReturnValue) const override {
4641 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4642 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004643 bool isSwiftErrorInRegister() const override {
4644 return true;
4645 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004646};
4647
Tim Northover573cbee2014-05-24 12:52:07 +00004648class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004649public:
Tim Northover573cbee2014-05-24 12:52:07 +00004650 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4651 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004652
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004653 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004654 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4655 }
4656
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004657 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4658 return 31;
4659 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004660
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004661 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004662};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004663}
Tim Northovera2ee4332014-03-29 15:09:45 +00004664
Tim Northoverb047bfa2014-11-27 21:02:49 +00004665ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004666 Ty = useFirstFieldIfTransparentUnion(Ty);
4667
Tim Northovera2ee4332014-03-29 15:09:45 +00004668 // Handle illegal vector types here.
4669 if (isIllegalVectorType(Ty)) {
4670 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004671 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004672 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004673 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4674 return ABIArgInfo::getDirect(ResType);
4675 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004676 if (Size <= 32) {
4677 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004678 return ABIArgInfo::getDirect(ResType);
4679 }
4680 if (Size == 64) {
4681 llvm::Type *ResType =
4682 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004683 return ABIArgInfo::getDirect(ResType);
4684 }
4685 if (Size == 128) {
4686 llvm::Type *ResType =
4687 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004688 return ABIArgInfo::getDirect(ResType);
4689 }
John McCall7f416cc2015-09-08 08:05:57 +00004690 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004691 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004692
4693 if (!isAggregateTypeForABI(Ty)) {
4694 // Treat an enum type as its underlying type.
4695 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4696 Ty = EnumTy->getDecl()->getIntegerType();
4697
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4699 ? ABIArgInfo::getExtend()
4700 : ABIArgInfo::getDirect());
4701 }
4702
4703 // Structures with either a non-trivial destructor or a non-trivial
4704 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004705 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004706 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4707 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004708 }
4709
4710 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4711 // elsewhere for GNU compatibility.
4712 if (isEmptyRecord(getContext(), Ty, true)) {
4713 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4714 return ABIArgInfo::getIgnore();
4715
Tim Northovera2ee4332014-03-29 15:09:45 +00004716 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4717 }
4718
4719 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004720 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004721 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004722 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004723 return ABIArgInfo::getDirect(
4724 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004725 }
4726
4727 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4728 uint64_t Size = getContext().getTypeSize(Ty);
4729 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004730 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4731 // same size and alignment.
4732 if (getTarget().isRenderScriptTarget()) {
4733 return coerceToIntArray(Ty, getContext(), getVMContext());
4734 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004735 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004736 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004737
Tim Northovera2ee4332014-03-29 15:09:45 +00004738 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4739 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004740 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004741 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4742 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4743 }
4744 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4745 }
4746
John McCall7f416cc2015-09-08 08:05:57 +00004747 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004748}
4749
Tim Northover573cbee2014-05-24 12:52:07 +00004750ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004751 if (RetTy->isVoidType())
4752 return ABIArgInfo::getIgnore();
4753
4754 // Large vector types should be returned via memory.
4755 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004756 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004757
4758 if (!isAggregateTypeForABI(RetTy)) {
4759 // Treat an enum type as its underlying type.
4760 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4761 RetTy = EnumTy->getDecl()->getIntegerType();
4762
Tim Northover4dab6982014-04-18 13:46:08 +00004763 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4764 ? ABIArgInfo::getExtend()
4765 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004766 }
4767
Tim Northovera2ee4332014-03-29 15:09:45 +00004768 if (isEmptyRecord(getContext(), RetTy, true))
4769 return ABIArgInfo::getIgnore();
4770
Craig Topper8a13c412014-05-21 05:09:00 +00004771 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004772 uint64_t Members = 0;
4773 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004774 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4775 return ABIArgInfo::getDirect();
4776
4777 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4778 uint64_t Size = getContext().getTypeSize(RetTy);
4779 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004780 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4781 // same size and alignment.
4782 if (getTarget().isRenderScriptTarget()) {
4783 return coerceToIntArray(RetTy, getContext(), getVMContext());
4784 }
Pete Cooper635b5092015-04-17 22:16:24 +00004785 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004786 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004787
4788 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4789 // For aggregates with 16-byte alignment, we use i128.
4790 if (Alignment < 128 && Size == 128) {
4791 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4792 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4793 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004794 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4795 }
4796
John McCall7f416cc2015-09-08 08:05:57 +00004797 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004798}
4799
Tim Northover573cbee2014-05-24 12:52:07 +00004800/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4801bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004802 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4803 // Check whether VT is legal.
4804 unsigned NumElements = VT->getNumElements();
4805 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004806 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004807 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004808 return true;
4809 return Size != 64 && (Size != 128 || NumElements == 1);
4810 }
4811 return false;
4812}
4813
Reid Klecknere9f6a712014-10-31 17:10:41 +00004814bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4815 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4816 // point type or a short-vector type. This is the same as the 32-bit ABI,
4817 // but with the difference that any floating-point type is allowed,
4818 // including __fp16.
4819 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4820 if (BT->isFloatingPoint())
4821 return true;
4822 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4823 unsigned VecSize = getContext().getTypeSize(VT);
4824 if (VecSize == 64 || VecSize == 128)
4825 return true;
4826 }
4827 return false;
4828}
4829
4830bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4831 uint64_t Members) const {
4832 return Members <= 4;
4833}
4834
John McCall7f416cc2015-09-08 08:05:57 +00004835Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004836 QualType Ty,
4837 CodeGenFunction &CGF) const {
4838 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004839 bool IsIndirect = AI.isIndirect();
4840
Tim Northoverb047bfa2014-11-27 21:02:49 +00004841 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4842 if (IsIndirect)
4843 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4844 else if (AI.getCoerceToType())
4845 BaseTy = AI.getCoerceToType();
4846
4847 unsigned NumRegs = 1;
4848 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4849 BaseTy = ArrTy->getElementType();
4850 NumRegs = ArrTy->getNumElements();
4851 }
4852 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4853
Tim Northovera2ee4332014-03-29 15:09:45 +00004854 // The AArch64 va_list type and handling is specified in the Procedure Call
4855 // Standard, section B.4:
4856 //
4857 // struct {
4858 // void *__stack;
4859 // void *__gr_top;
4860 // void *__vr_top;
4861 // int __gr_offs;
4862 // int __vr_offs;
4863 // };
4864
4865 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4866 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4867 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4868 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004869
John McCall7f416cc2015-09-08 08:05:57 +00004870 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4871 CharUnits TyAlign = TyInfo.second;
4872
4873 Address reg_offs_p = Address::invalid();
4874 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004875 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004876 CharUnits reg_top_offset;
4877 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004878 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004879 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004880 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004881 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4882 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004883 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4884 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004885 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004886 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004887 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004888 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004889 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004890 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4891 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004892 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4893 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004894 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004895 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004896 }
4897
4898 //=======================================
4899 // Find out where argument was passed
4900 //=======================================
4901
4902 // If reg_offs >= 0 we're already using the stack for this type of
4903 // argument. We don't want to keep updating reg_offs (in case it overflows,
4904 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4905 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004906 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004907 UsingStack = CGF.Builder.CreateICmpSGE(
4908 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4909
4910 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4911
4912 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004913 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004914 CGF.EmitBlock(MaybeRegBlock);
4915
4916 // Integer arguments may need to correct register alignment (for example a
4917 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4918 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004919 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4920 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004921
4922 reg_offs = CGF.Builder.CreateAdd(
4923 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4924 "align_regoffs");
4925 reg_offs = CGF.Builder.CreateAnd(
4926 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4927 "aligned_regoffs");
4928 }
4929
4930 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004931 // The fact that this is done unconditionally reflects the fact that
4932 // allocating an argument to the stack also uses up all the remaining
4933 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004934 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004935 NewOffset = CGF.Builder.CreateAdd(
4936 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4937 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4938
4939 // Now we're in a position to decide whether this argument really was in
4940 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004941 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004942 InRegs = CGF.Builder.CreateICmpSLE(
4943 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4944
4945 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4946
4947 //=======================================
4948 // Argument was in registers
4949 //=======================================
4950
4951 // Now we emit the code for if the argument was originally passed in
4952 // registers. First start the appropriate block:
4953 CGF.EmitBlock(InRegBlock);
4954
John McCall7f416cc2015-09-08 08:05:57 +00004955 llvm::Value *reg_top = nullptr;
4956 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4957 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004958 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004959 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4960 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4961 Address RegAddr = Address::invalid();
4962 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004963
4964 if (IsIndirect) {
4965 // If it's been passed indirectly (actually a struct), whatever we find from
4966 // stored registers or on the stack will actually be a struct **.
4967 MemTy = llvm::PointerType::getUnqual(MemTy);
4968 }
4969
Craig Topper8a13c412014-05-21 05:09:00 +00004970 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004971 uint64_t NumMembers = 0;
4972 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004973 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004974 // Homogeneous aggregates passed in registers will have their elements split
4975 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4976 // qN+1, ...). We reload and store into a temporary local variable
4977 // contiguously.
4978 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004979 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004980 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4981 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004982 Address Tmp = CGF.CreateTempAlloca(HFATy,
4983 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004984
John McCall7f416cc2015-09-08 08:05:57 +00004985 // On big-endian platforms, the value will be right-aligned in its slot.
4986 int Offset = 0;
4987 if (CGF.CGM.getDataLayout().isBigEndian() &&
4988 BaseTyInfo.first.getQuantity() < 16)
4989 Offset = 16 - BaseTyInfo.first.getQuantity();
4990
Tim Northovera2ee4332014-03-29 15:09:45 +00004991 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004992 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4993 Address LoadAddr =
4994 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4995 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4996
4997 Address StoreAddr =
4998 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004999
5000 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5001 CGF.Builder.CreateStore(Elem, StoreAddr);
5002 }
5003
John McCall7f416cc2015-09-08 08:05:57 +00005004 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005005 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005006 // Otherwise the object is contiguous in memory.
5007
5008 // It might be right-aligned in its slot.
5009 CharUnits SlotSize = BaseAddr.getAlignment();
5010 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005011 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005012 TyInfo.first < SlotSize) {
5013 CharUnits Offset = SlotSize - TyInfo.first;
5014 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005015 }
5016
John McCall7f416cc2015-09-08 08:05:57 +00005017 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005018 }
5019
5020 CGF.EmitBranch(ContBlock);
5021
5022 //=======================================
5023 // Argument was on the stack
5024 //=======================================
5025 CGF.EmitBlock(OnStackBlock);
5026
John McCall7f416cc2015-09-08 08:05:57 +00005027 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5028 CharUnits::Zero(), "stack_p");
5029 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005030
John McCall7f416cc2015-09-08 08:05:57 +00005031 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005032 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005033 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5034 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005035
John McCall7f416cc2015-09-08 08:05:57 +00005036 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005037
John McCall7f416cc2015-09-08 08:05:57 +00005038 OnStackPtr = CGF.Builder.CreateAdd(
5039 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005040 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005041 OnStackPtr = CGF.Builder.CreateAnd(
5042 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005043 "align_stack");
5044
John McCall7f416cc2015-09-08 08:05:57 +00005045 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005046 }
John McCall7f416cc2015-09-08 08:05:57 +00005047 Address OnStackAddr(OnStackPtr,
5048 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005049
John McCall7f416cc2015-09-08 08:05:57 +00005050 // All stack slots are multiples of 8 bytes.
5051 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5052 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005053 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005054 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005055 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005056 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005057
John McCall7f416cc2015-09-08 08:05:57 +00005058 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005059 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005060 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005061
5062 // Write the new value of __stack for the next call to va_arg
5063 CGF.Builder.CreateStore(NewStack, stack_p);
5064
5065 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005066 TyInfo.first < StackSlotSize) {
5067 CharUnits Offset = StackSlotSize - TyInfo.first;
5068 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005069 }
5070
John McCall7f416cc2015-09-08 08:05:57 +00005071 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005072
5073 CGF.EmitBranch(ContBlock);
5074
5075 //=======================================
5076 // Tidy up
5077 //=======================================
5078 CGF.EmitBlock(ContBlock);
5079
John McCall7f416cc2015-09-08 08:05:57 +00005080 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5081 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005082
5083 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005084 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5085 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005086
5087 return ResAddr;
5088}
5089
John McCall7f416cc2015-09-08 08:05:57 +00005090Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5091 CodeGenFunction &CGF) const {
5092 // The backend's lowering doesn't support va_arg for aggregates or
5093 // illegal vector types. Lower VAArg here for these cases and use
5094 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005095 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005096 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005097
John McCall7f416cc2015-09-08 08:05:57 +00005098 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005099
John McCall7f416cc2015-09-08 08:05:57 +00005100 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005101 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005102 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5103 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5104 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005105 }
5106
John McCall7f416cc2015-09-08 08:05:57 +00005107 // The size of the actual thing passed, which might end up just
5108 // being a pointer for indirect types.
5109 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5110
5111 // Arguments bigger than 16 bytes which aren't homogeneous
5112 // aggregates should be passed indirectly.
5113 bool IsIndirect = false;
5114 if (TyInfo.first.getQuantity() > 16) {
5115 const Type *Base = nullptr;
5116 uint64_t Members = 0;
5117 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005118 }
5119
John McCall7f416cc2015-09-08 08:05:57 +00005120 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5121 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005122}
5123
5124//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005125// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005126//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005127
5128namespace {
5129
John McCall12f23522016-04-04 18:33:08 +00005130class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005131public:
5132 enum ABIKind {
5133 APCS = 0,
5134 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005135 AAPCS_VFP = 2,
5136 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005137 };
5138
5139private:
5140 ABIKind Kind;
5141
5142public:
John McCall12f23522016-04-04 18:33:08 +00005143 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5144 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005145 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005146 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005147
John McCall3480ef22011-08-30 01:42:09 +00005148 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005149 switch (getTarget().getTriple().getEnvironment()) {
5150 case llvm::Triple::Android:
5151 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005152 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005153 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005154 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005155 case llvm::Triple::MuslEABI:
5156 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005157 return true;
5158 default:
5159 return false;
5160 }
John McCall3480ef22011-08-30 01:42:09 +00005161 }
5162
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005163 bool isEABIHF() const {
5164 switch (getTarget().getTriple().getEnvironment()) {
5165 case llvm::Triple::EABIHF:
5166 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005167 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005168 return true;
5169 default:
5170 return false;
5171 }
5172 }
5173
Daniel Dunbar020daa92009-09-12 01:00:39 +00005174 ABIKind getABIKind() const { return Kind; }
5175
Tim Northovera484bc02013-10-01 14:34:25 +00005176private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005177 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005178 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005179 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005180
Reid Klecknere9f6a712014-10-31 17:10:41 +00005181 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5182 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5183 uint64_t Members) const override;
5184
Craig Topper4f12f102014-03-12 06:41:41 +00005185 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005186
John McCall7f416cc2015-09-08 08:05:57 +00005187 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5188 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005189
5190 llvm::CallingConv::ID getLLVMDefaultCC() const;
5191 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005192 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005193
5194 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5195 ArrayRef<llvm::Type*> scalars,
5196 bool asReturnValue) const override {
5197 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5198 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005199 bool isSwiftErrorInRegister() const override {
5200 return true;
5201 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005202};
5203
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005204class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5205public:
Chris Lattner2b037972010-07-29 02:01:43 +00005206 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5207 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005208
John McCall3480ef22011-08-30 01:42:09 +00005209 const ARMABIInfo &getABIInfo() const {
5210 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5211 }
5212
Craig Topper4f12f102014-03-12 06:41:41 +00005213 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005214 return 13;
5215 }
Roman Divackyc1617352011-05-18 19:36:54 +00005216
Craig Topper4f12f102014-03-12 06:41:41 +00005217 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005218 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5219 }
5220
Roman Divackyc1617352011-05-18 19:36:54 +00005221 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005222 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005223 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005224
5225 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005226 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005227 return false;
5228 }
John McCall3480ef22011-08-30 01:42:09 +00005229
Craig Topper4f12f102014-03-12 06:41:41 +00005230 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005231 if (getABIInfo().isEABI()) return 88;
5232 return TargetCodeGenInfo::getSizeOfUnwindException();
5233 }
Tim Northovera484bc02013-10-01 14:34:25 +00005234
Eric Christopher162c91c2015-06-05 22:03:00 +00005235 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005236 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005237 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005238 if (!FD)
5239 return;
5240
5241 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5242 if (!Attr)
5243 return;
5244
5245 const char *Kind;
5246 switch (Attr->getInterrupt()) {
5247 case ARMInterruptAttr::Generic: Kind = ""; break;
5248 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5249 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5250 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5251 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5252 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5253 }
5254
5255 llvm::Function *Fn = cast<llvm::Function>(GV);
5256
5257 Fn->addFnAttr("interrupt", Kind);
5258
Tim Northover5627d392015-10-30 16:30:45 +00005259 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5260 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005261 return;
5262
5263 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5264 // however this is not necessarily true on taking any interrupt. Instruct
5265 // the backend to perform a realignment as part of the function prologue.
5266 llvm::AttrBuilder B;
5267 B.addStackAlignmentAttr(8);
5268 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5269 llvm::AttributeSet::get(CGM.getLLVMContext(),
5270 llvm::AttributeSet::FunctionIndex,
5271 B));
5272 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005273};
5274
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005275class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005276public:
5277 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5278 : ARMTargetCodeGenInfo(CGT, K) {}
5279
Eric Christopher162c91c2015-06-05 22:03:00 +00005280 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005281 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005282
5283 void getDependentLibraryOption(llvm::StringRef Lib,
5284 llvm::SmallString<24> &Opt) const override {
5285 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5286 }
5287
5288 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5289 llvm::SmallString<32> &Opt) const override {
5290 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5291 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005292};
5293
Eric Christopher162c91c2015-06-05 22:03:00 +00005294void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005295 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005296 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005297 addStackProbeSizeTargetAttribute(D, GV, CGM);
5298}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005299}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005300
Chris Lattner22326a12010-07-29 02:31:05 +00005301void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005302 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005303 FI.getReturnInfo() =
5304 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005305
Tim Northoverbc784d12015-02-24 17:22:40 +00005306 for (auto &I : FI.arguments())
5307 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005308
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005309 // Always honor user-specified calling convention.
5310 if (FI.getCallingConvention() != llvm::CallingConv::C)
5311 return;
5312
John McCall882987f2013-02-28 19:01:20 +00005313 llvm::CallingConv::ID cc = getRuntimeCC();
5314 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005315 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005316}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005317
John McCall882987f2013-02-28 19:01:20 +00005318/// Return the default calling convention that LLVM will use.
5319llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5320 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005321 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005322 return llvm::CallingConv::ARM_AAPCS_VFP;
5323 else if (isEABI())
5324 return llvm::CallingConv::ARM_AAPCS;
5325 else
5326 return llvm::CallingConv::ARM_APCS;
5327}
5328
5329/// Return the calling convention that our ABI would like us to use
5330/// as the C calling convention.
5331llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005332 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005333 case APCS: return llvm::CallingConv::ARM_APCS;
5334 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5335 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005336 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005337 }
John McCall882987f2013-02-28 19:01:20 +00005338 llvm_unreachable("bad ABI kind");
5339}
5340
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005341void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005342 assert(getRuntimeCC() == llvm::CallingConv::C);
5343
5344 // Don't muddy up the IR with a ton of explicit annotations if
5345 // they'd just match what LLVM will infer from the triple.
5346 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5347 if (abiCC != getLLVMDefaultCC())
5348 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005349
Tim Northover5627d392015-10-30 16:30:45 +00005350 // AAPCS apparently requires runtime support functions to be soft-float, but
5351 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5352 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5353 switch (getABIKind()) {
5354 case APCS:
5355 case AAPCS16_VFP:
5356 if (abiCC != getLLVMDefaultCC())
5357 BuiltinCC = abiCC;
5358 break;
5359 case AAPCS:
5360 case AAPCS_VFP:
5361 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5362 break;
5363 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005364}
5365
Tim Northoverbc784d12015-02-24 17:22:40 +00005366ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5367 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005368 // 6.1.2.1 The following argument types are VFP CPRCs:
5369 // A single-precision floating-point type (including promoted
5370 // half-precision types); A double-precision floating-point type;
5371 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5372 // with a Base Type of a single- or double-precision floating-point type,
5373 // 64-bit containerized vectors or 128-bit containerized vectors with one
5374 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005375 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005376
Reid Klecknerb1be6832014-11-15 01:41:41 +00005377 Ty = useFirstFieldIfTransparentUnion(Ty);
5378
Manman Renfef9e312012-10-16 19:18:39 +00005379 // Handle illegal vector types here.
5380 if (isIllegalVectorType(Ty)) {
5381 uint64_t Size = getContext().getTypeSize(Ty);
5382 if (Size <= 32) {
5383 llvm::Type *ResType =
5384 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005385 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005386 }
5387 if (Size == 64) {
5388 llvm::Type *ResType = llvm::VectorType::get(
5389 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005390 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005391 }
5392 if (Size == 128) {
5393 llvm::Type *ResType = llvm::VectorType::get(
5394 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005395 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005396 }
John McCall7f416cc2015-09-08 08:05:57 +00005397 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005398 }
5399
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005400 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5401 // unspecified. This is not done for OpenCL as it handles the half type
5402 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005403 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005404 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5405 llvm::Type::getFloatTy(getVMContext()) :
5406 llvm::Type::getInt32Ty(getVMContext());
5407 return ABIArgInfo::getDirect(ResType);
5408 }
5409
John McCalla1dee5302010-08-22 10:59:02 +00005410 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005411 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005412 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005413 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005414 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005415
Tim Northover5a1558e2014-11-07 22:30:50 +00005416 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5417 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005418 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005419
Oliver Stannard405bded2014-02-11 09:25:50 +00005420 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005421 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005422 }
Tim Northover1060eae2013-06-21 22:49:34 +00005423
Daniel Dunbar09d33622009-09-14 21:54:03 +00005424 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005425 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005426 return ABIArgInfo::getIgnore();
5427
Tim Northover5a1558e2014-11-07 22:30:50 +00005428 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005429 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5430 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005431 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005432 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005433 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005434 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005435 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005436 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005437 }
Tim Northover5627d392015-10-30 16:30:45 +00005438 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5439 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5440 // this convention even for a variadic function: the backend will use GPRs
5441 // if needed.
5442 const Type *Base = nullptr;
5443 uint64_t Members = 0;
5444 if (isHomogeneousAggregate(Ty, Base, Members)) {
5445 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5446 llvm::Type *Ty =
5447 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5448 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5449 }
5450 }
5451
5452 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5453 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5454 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5455 // bigger than 128-bits, they get placed in space allocated by the caller,
5456 // and a pointer is passed.
5457 return ABIArgInfo::getIndirect(
5458 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005459 }
5460
Manman Ren6c30e132012-08-13 21:23:55 +00005461 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005462 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5463 // most 8-byte. We realign the indirect argument if type alignment is bigger
5464 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005465 uint64_t ABIAlign = 4;
5466 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5467 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005468 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005469 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005470
Manman Ren8cd99812012-11-06 04:58:01 +00005471 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005472 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005473 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5474 /*ByVal=*/true,
5475 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005476 }
5477
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005478 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5479 // same size and alignment.
5480 if (getTarget().isRenderScriptTarget()) {
5481 return coerceToIntArray(Ty, getContext(), getVMContext());
5482 }
5483
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005484 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005485 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005486 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005487 // FIXME: Try to match the types of the arguments more accurately where
5488 // we can.
5489 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005490 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5491 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005492 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005493 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5494 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005495 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005496
Tim Northover5a1558e2014-11-07 22:30:50 +00005497 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005498}
5499
Chris Lattner458b2aa2010-07-29 02:16:43 +00005500static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005501 llvm::LLVMContext &VMContext) {
5502 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5503 // is called integer-like if its size is less than or equal to one word, and
5504 // the offset of each of its addressable sub-fields is zero.
5505
5506 uint64_t Size = Context.getTypeSize(Ty);
5507
5508 // Check that the type fits in a word.
5509 if (Size > 32)
5510 return false;
5511
5512 // FIXME: Handle vector types!
5513 if (Ty->isVectorType())
5514 return false;
5515
Daniel Dunbard53bac72009-09-14 02:20:34 +00005516 // Float types are never treated as "integer like".
5517 if (Ty->isRealFloatingType())
5518 return false;
5519
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005520 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005521 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005522 return true;
5523
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005524 // Small complex integer types are "integer like".
5525 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5526 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005527
5528 // Single element and zero sized arrays should be allowed, by the definition
5529 // above, but they are not.
5530
5531 // Otherwise, it must be a record type.
5532 const RecordType *RT = Ty->getAs<RecordType>();
5533 if (!RT) return false;
5534
5535 // Ignore records with flexible arrays.
5536 const RecordDecl *RD = RT->getDecl();
5537 if (RD->hasFlexibleArrayMember())
5538 return false;
5539
5540 // Check that all sub-fields are at offset 0, and are themselves "integer
5541 // like".
5542 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5543
5544 bool HadField = false;
5545 unsigned idx = 0;
5546 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5547 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005548 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005549
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005550 // Bit-fields are not addressable, we only need to verify they are "integer
5551 // like". We still have to disallow a subsequent non-bitfield, for example:
5552 // struct { int : 0; int x }
5553 // is non-integer like according to gcc.
5554 if (FD->isBitField()) {
5555 if (!RD->isUnion())
5556 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005557
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005558 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5559 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005560
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005561 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005562 }
5563
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005564 // Check if this field is at offset 0.
5565 if (Layout.getFieldOffset(idx) != 0)
5566 return false;
5567
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005568 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5569 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005570
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005571 // Only allow at most one field in a structure. This doesn't match the
5572 // wording above, but follows gcc in situations with a field following an
5573 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005574 if (!RD->isUnion()) {
5575 if (HadField)
5576 return false;
5577
5578 HadField = true;
5579 }
5580 }
5581
5582 return true;
5583}
5584
Oliver Stannard405bded2014-02-11 09:25:50 +00005585ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5586 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005587 bool IsEffectivelyAAPCS_VFP =
5588 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005589
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005590 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005591 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005592
Daniel Dunbar19964db2010-09-23 01:54:32 +00005593 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005594 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005595 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005596 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005597
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005598 // __fp16 gets returned as if it were an int or float, but with the top 16
5599 // bits unspecified. This is not done for OpenCL as it handles the half type
5600 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005601 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005602 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5603 llvm::Type::getFloatTy(getVMContext()) :
5604 llvm::Type::getInt32Ty(getVMContext());
5605 return ABIArgInfo::getDirect(ResType);
5606 }
5607
John McCalla1dee5302010-08-22 10:59:02 +00005608 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005609 // Treat an enum type as its underlying type.
5610 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5611 RetTy = EnumTy->getDecl()->getIntegerType();
5612
Tim Northover5a1558e2014-11-07 22:30:50 +00005613 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5614 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005615 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005616
5617 // Are we following APCS?
5618 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005619 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005620 return ABIArgInfo::getIgnore();
5621
Daniel Dunbareedf1512010-02-01 23:31:19 +00005622 // Complex types are all returned as packed integers.
5623 //
5624 // FIXME: Consider using 2 x vector types if the back end handles them
5625 // correctly.
5626 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005627 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5628 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005629
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005630 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005631 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005632 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005633 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005634 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005635 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005636 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005637 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5638 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005639 }
5640
5641 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005642 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005643 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005644
5645 // Otherwise this is an AAPCS variant.
5646
Chris Lattner458b2aa2010-07-29 02:16:43 +00005647 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005648 return ABIArgInfo::getIgnore();
5649
Bob Wilson1d9269a2011-11-02 04:51:36 +00005650 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005651 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005652 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005653 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005654 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005655 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005656 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005657 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005658 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005659 }
5660
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005661 // Aggregates <= 4 bytes are returned in r0; other aggregates
5662 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005663 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005664 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005665 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5666 // same size and alignment.
5667 if (getTarget().isRenderScriptTarget()) {
5668 return coerceToIntArray(RetTy, getContext(), getVMContext());
5669 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005670 if (getDataLayout().isBigEndian())
5671 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005672 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005673
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005674 // Return in the smallest viable integer type.
5675 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005676 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005677 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005678 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5679 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005680 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5681 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5682 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005683 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005684 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005685 }
5686
John McCall7f416cc2015-09-08 08:05:57 +00005687 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005688}
5689
Manman Renfef9e312012-10-16 19:18:39 +00005690/// isIllegalVector - check whether Ty is an illegal vector type.
5691bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005692 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5693 if (isAndroid()) {
5694 // Android shipped using Clang 3.1, which supported a slightly different
5695 // vector ABI. The primary differences were that 3-element vector types
5696 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5697 // accepts that legacy behavior for Android only.
5698 // Check whether VT is legal.
5699 unsigned NumElements = VT->getNumElements();
5700 // NumElements should be power of 2 or equal to 3.
5701 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5702 return true;
5703 } else {
5704 // Check whether VT is legal.
5705 unsigned NumElements = VT->getNumElements();
5706 uint64_t Size = getContext().getTypeSize(VT);
5707 // NumElements should be power of 2.
5708 if (!llvm::isPowerOf2_32(NumElements))
5709 return true;
5710 // Size should be greater than 32 bits.
5711 return Size <= 32;
5712 }
Manman Renfef9e312012-10-16 19:18:39 +00005713 }
5714 return false;
5715}
5716
Reid Klecknere9f6a712014-10-31 17:10:41 +00005717bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5718 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5719 // double, or 64-bit or 128-bit vectors.
5720 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5721 if (BT->getKind() == BuiltinType::Float ||
5722 BT->getKind() == BuiltinType::Double ||
5723 BT->getKind() == BuiltinType::LongDouble)
5724 return true;
5725 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5726 unsigned VecSize = getContext().getTypeSize(VT);
5727 if (VecSize == 64 || VecSize == 128)
5728 return true;
5729 }
5730 return false;
5731}
5732
5733bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5734 uint64_t Members) const {
5735 return Members <= 4;
5736}
5737
John McCall7f416cc2015-09-08 08:05:57 +00005738Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5739 QualType Ty) const {
5740 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005741
John McCall7f416cc2015-09-08 08:05:57 +00005742 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005743 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005744 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5745 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5746 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005747 }
5748
John McCall7f416cc2015-09-08 08:05:57 +00005749 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5750 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005751
John McCall7f416cc2015-09-08 08:05:57 +00005752 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5753 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005754 const Type *Base = nullptr;
5755 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005756 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5757 IsIndirect = true;
5758
Tim Northover5627d392015-10-30 16:30:45 +00005759 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5760 // allocated by the caller.
5761 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5762 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5763 !isHomogeneousAggregate(Ty, Base, Members)) {
5764 IsIndirect = true;
5765
John McCall7f416cc2015-09-08 08:05:57 +00005766 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005767 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5768 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005769 // Our callers should be prepared to handle an under-aligned address.
5770 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5771 getABIKind() == ARMABIInfo::AAPCS) {
5772 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5773 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005774 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5775 // ARMv7k allows type alignment up to 16 bytes.
5776 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5777 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005778 } else {
5779 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005780 }
John McCall7f416cc2015-09-08 08:05:57 +00005781 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005782
John McCall7f416cc2015-09-08 08:05:57 +00005783 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5784 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005785}
5786
Chris Lattner0cf24192010-06-28 20:05:43 +00005787//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005788// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005789//===----------------------------------------------------------------------===//
5790
5791namespace {
5792
Justin Holewinski83e96682012-05-24 17:43:12 +00005793class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005794public:
Justin Holewinski36837432013-03-30 14:38:24 +00005795 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005796
5797 ABIArgInfo classifyReturnType(QualType RetTy) const;
5798 ABIArgInfo classifyArgumentType(QualType Ty) const;
5799
Craig Topper4f12f102014-03-12 06:41:41 +00005800 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005801 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5802 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005803};
5804
Justin Holewinski83e96682012-05-24 17:43:12 +00005805class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005806public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005807 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5808 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005809
Eric Christopher162c91c2015-06-05 22:03:00 +00005810 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005811 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005812private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005813 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5814 // resulting MDNode to the nvvm.annotations MDNode.
5815 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005816};
5817
Justin Holewinski83e96682012-05-24 17:43:12 +00005818ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005819 if (RetTy->isVoidType())
5820 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005821
5822 // note: this is different from default ABI
5823 if (!RetTy->isScalarType())
5824 return ABIArgInfo::getDirect();
5825
5826 // Treat an enum type as its underlying type.
5827 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5828 RetTy = EnumTy->getDecl()->getIntegerType();
5829
5830 return (RetTy->isPromotableIntegerType() ?
5831 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005832}
5833
Justin Holewinski83e96682012-05-24 17:43:12 +00005834ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005835 // Treat an enum type as its underlying type.
5836 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5837 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005838
Eli Bendersky95338a02014-10-29 13:43:21 +00005839 // Return aggregates type as indirect by value
5840 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005841 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005842
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005843 return (Ty->isPromotableIntegerType() ?
5844 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005845}
5846
Justin Holewinski83e96682012-05-24 17:43:12 +00005847void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005848 if (!getCXXABI().classifyReturnType(FI))
5849 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005850 for (auto &I : FI.arguments())
5851 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005852
5853 // Always honor user-specified calling convention.
5854 if (FI.getCallingConvention() != llvm::CallingConv::C)
5855 return;
5856
John McCall882987f2013-02-28 19:01:20 +00005857 FI.setEffectiveCallingConvention(getRuntimeCC());
5858}
5859
John McCall7f416cc2015-09-08 08:05:57 +00005860Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5861 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005862 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005863}
5864
Justin Holewinski83e96682012-05-24 17:43:12 +00005865void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005866setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005867 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005868 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005869 if (!FD) return;
5870
5871 llvm::Function *F = cast<llvm::Function>(GV);
5872
5873 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005874 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005875 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005876 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005877 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005878 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005879 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5880 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005881 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005882 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005883 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005884 }
Justin Holewinski38031972011-10-05 17:58:44 +00005885
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005886 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005887 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005888 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005889 // __global__ functions cannot be called from the device, we do not
5890 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005891 if (FD->hasAttr<CUDAGlobalAttr>()) {
5892 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5893 addNVVMMetadata(F, "kernel", 1);
5894 }
Artem Belevich7093e402015-04-21 22:55:54 +00005895 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005896 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005897 llvm::APSInt MaxThreads(32);
5898 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5899 if (MaxThreads > 0)
5900 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5901
5902 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5903 // not specified in __launch_bounds__ or if the user specified a 0 value,
5904 // we don't have to add a PTX directive.
5905 if (Attr->getMinBlocks()) {
5906 llvm::APSInt MinBlocks(32);
5907 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5908 if (MinBlocks > 0)
5909 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5910 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005911 }
5912 }
Justin Holewinski38031972011-10-05 17:58:44 +00005913 }
5914}
5915
Eli Benderskye06a2c42014-04-15 16:57:05 +00005916void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5917 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005918 llvm::Module *M = F->getParent();
5919 llvm::LLVMContext &Ctx = M->getContext();
5920
5921 // Get "nvvm.annotations" metadata node
5922 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5923
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005924 llvm::Metadata *MDVals[] = {
5925 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5926 llvm::ConstantAsMetadata::get(
5927 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005928 // Append metadata to nvvm.annotations
5929 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5930}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005931}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005932
5933//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005934// SystemZ ABI Implementation
5935//===----------------------------------------------------------------------===//
5936
5937namespace {
5938
Bryan Chane3f1ed52016-04-28 13:56:43 +00005939class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005940 bool HasVector;
5941
Ulrich Weigand47445072013-05-06 16:26:41 +00005942public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005943 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005944 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005945
5946 bool isPromotableIntegerType(QualType Ty) const;
5947 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005948 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005949 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005950 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005951
5952 ABIArgInfo classifyReturnType(QualType RetTy) const;
5953 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5954
Craig Topper4f12f102014-03-12 06:41:41 +00005955 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005956 if (!getCXXABI().classifyReturnType(FI))
5957 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005958 for (auto &I : FI.arguments())
5959 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005960 }
5961
John McCall7f416cc2015-09-08 08:05:57 +00005962 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5963 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005964
5965 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5966 ArrayRef<llvm::Type*> scalars,
5967 bool asReturnValue) const override {
5968 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5969 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005970 bool isSwiftErrorInRegister() const override {
5971 return true;
5972 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005973};
5974
5975class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5976public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005977 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5978 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005979};
5980
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005981}
Ulrich Weigand47445072013-05-06 16:26:41 +00005982
5983bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5984 // Treat an enum type as its underlying type.
5985 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5986 Ty = EnumTy->getDecl()->getIntegerType();
5987
5988 // Promotable integer types are required to be promoted by the ABI.
5989 if (Ty->isPromotableIntegerType())
5990 return true;
5991
5992 // 32-bit values must also be promoted.
5993 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5994 switch (BT->getKind()) {
5995 case BuiltinType::Int:
5996 case BuiltinType::UInt:
5997 return true;
5998 default:
5999 return false;
6000 }
6001 return false;
6002}
6003
6004bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006005 return (Ty->isAnyComplexType() ||
6006 Ty->isVectorType() ||
6007 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006008}
6009
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006010bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6011 return (HasVector &&
6012 Ty->isVectorType() &&
6013 getContext().getTypeSize(Ty) <= 128);
6014}
6015
Ulrich Weigand47445072013-05-06 16:26:41 +00006016bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6017 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6018 switch (BT->getKind()) {
6019 case BuiltinType::Float:
6020 case BuiltinType::Double:
6021 return true;
6022 default:
6023 return false;
6024 }
6025
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006026 return false;
6027}
6028
6029QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006030 if (const RecordType *RT = Ty->getAsStructureType()) {
6031 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006032 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006033
6034 // If this is a C++ record, check the bases first.
6035 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006036 for (const auto &I : CXXRD->bases()) {
6037 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006038
6039 // Empty bases don't affect things either way.
6040 if (isEmptyRecord(getContext(), Base, true))
6041 continue;
6042
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006043 if (!Found.isNull())
6044 return Ty;
6045 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006046 }
6047
6048 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006049 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006050 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006051 // Unlike isSingleElementStruct(), empty structure and array fields
6052 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006053 if (getContext().getLangOpts().CPlusPlus &&
6054 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6055 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006056
6057 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006058 // Nested structures still do though.
6059 if (!Found.isNull())
6060 return Ty;
6061 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006062 }
6063
6064 // Unlike isSingleElementStruct(), trailing padding is allowed.
6065 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006066 if (!Found.isNull())
6067 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006068 }
6069
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006070 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006071}
6072
John McCall7f416cc2015-09-08 08:05:57 +00006073Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6074 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006075 // Assume that va_list type is correct; should be pointer to LLVM type:
6076 // struct {
6077 // i64 __gpr;
6078 // i64 __fpr;
6079 // i8 *__overflow_arg_area;
6080 // i8 *__reg_save_area;
6081 // };
6082
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006083 // Every non-vector argument occupies 8 bytes and is passed by preference
6084 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6085 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006086 Ty = getContext().getCanonicalType(Ty);
6087 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006088 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006089 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006090 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006091 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006092 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006093 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006094 CharUnits UnpaddedSize;
6095 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006096 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006097 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6098 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006099 } else {
6100 if (AI.getCoerceToType())
6101 ArgTy = AI.getCoerceToType();
6102 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006103 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006104 UnpaddedSize = TyInfo.first;
6105 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006106 }
John McCall7f416cc2015-09-08 08:05:57 +00006107 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6108 if (IsVector && UnpaddedSize > PaddedSize)
6109 PaddedSize = CharUnits::fromQuantity(16);
6110 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006111
John McCall7f416cc2015-09-08 08:05:57 +00006112 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006113
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006114 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006115 llvm::Value *PaddedSizeV =
6116 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006117
6118 if (IsVector) {
6119 // Work out the address of a vector argument on the stack.
6120 // Vector arguments are always passed in the high bits of a
6121 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006122 Address OverflowArgAreaPtr =
6123 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006124 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006125 Address OverflowArgArea =
6126 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6127 TyInfo.second);
6128 Address MemAddr =
6129 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006130
6131 // Update overflow_arg_area_ptr pointer
6132 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006133 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6134 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006135 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6136
6137 return MemAddr;
6138 }
6139
John McCall7f416cc2015-09-08 08:05:57 +00006140 assert(PaddedSize.getQuantity() == 8);
6141
6142 unsigned MaxRegs, RegCountField, RegSaveIndex;
6143 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006144 if (InFPRs) {
6145 MaxRegs = 4; // Maximum of 4 FPR arguments
6146 RegCountField = 1; // __fpr
6147 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006148 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006149 } else {
6150 MaxRegs = 5; // Maximum of 5 GPR arguments
6151 RegCountField = 0; // __gpr
6152 RegSaveIndex = 2; // save offset for r2
6153 RegPadding = Padding; // values are passed in the low bits of a GPR
6154 }
6155
John McCall7f416cc2015-09-08 08:05:57 +00006156 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6157 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6158 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006159 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006160 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6161 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006162 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006163
6164 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6165 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6166 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6167 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6168
6169 // Emit code to load the value if it was passed in registers.
6170 CGF.EmitBlock(InRegBlock);
6171
6172 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006173 llvm::Value *ScaledRegCount =
6174 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6175 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006176 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6177 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006178 llvm::Value *RegOffset =
6179 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006180 Address RegSaveAreaPtr =
6181 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6182 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006183 llvm::Value *RegSaveArea =
6184 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006185 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6186 "raw_reg_addr"),
6187 PaddedSize);
6188 Address RegAddr =
6189 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006190
6191 // Update the register count
6192 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6193 llvm::Value *NewRegCount =
6194 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6195 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6196 CGF.EmitBranch(ContBlock);
6197
6198 // Emit code to load the value if it was passed in memory.
6199 CGF.EmitBlock(InMemBlock);
6200
6201 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006202 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6203 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6204 Address OverflowArgArea =
6205 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6206 PaddedSize);
6207 Address RawMemAddr =
6208 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6209 Address MemAddr =
6210 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006211
6212 // Update overflow_arg_area_ptr pointer
6213 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006214 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6215 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006216 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6217 CGF.EmitBranch(ContBlock);
6218
6219 // Return the appropriate result.
6220 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006221 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6222 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006223
6224 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006225 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6226 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006227
6228 return ResAddr;
6229}
6230
Ulrich Weigand47445072013-05-06 16:26:41 +00006231ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6232 if (RetTy->isVoidType())
6233 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006234 if (isVectorArgumentType(RetTy))
6235 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006236 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006237 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006238 return (isPromotableIntegerType(RetTy) ?
6239 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6240}
6241
6242ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6243 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006244 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006245 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006246
6247 // Integers and enums are extended to full register width.
6248 if (isPromotableIntegerType(Ty))
6249 return ABIArgInfo::getExtend();
6250
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006251 // Handle vector types and vector-like structure types. Note that
6252 // as opposed to float-like structure types, we do not allow any
6253 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006254 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006255 QualType SingleElementTy = GetSingleElementType(Ty);
6256 if (isVectorArgumentType(SingleElementTy) &&
6257 getContext().getTypeSize(SingleElementTy) == Size)
6258 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6259
6260 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006261 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006262 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006263
6264 // Handle small structures.
6265 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6266 // Structures with flexible arrays have variable length, so really
6267 // fail the size test above.
6268 const RecordDecl *RD = RT->getDecl();
6269 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006270 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006271
6272 // The structure is passed as an unextended integer, a float, or a double.
6273 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006274 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006275 assert(Size == 32 || Size == 64);
6276 if (Size == 32)
6277 PassTy = llvm::Type::getFloatTy(getVMContext());
6278 else
6279 PassTy = llvm::Type::getDoubleTy(getVMContext());
6280 } else
6281 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6282 return ABIArgInfo::getDirect(PassTy);
6283 }
6284
6285 // Non-structure compounds are passed indirectly.
6286 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006287 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006288
Craig Topper8a13c412014-05-21 05:09:00 +00006289 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006290}
6291
6292//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006293// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006294//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006295
6296namespace {
6297
6298class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6299public:
Chris Lattner2b037972010-07-29 02:01:43 +00006300 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6301 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006302 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006303 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006304};
6305
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006306}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006307
Eric Christopher162c91c2015-06-05 22:03:00 +00006308void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006309 llvm::GlobalValue *GV,
6310 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006311 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006312 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6313 // Handle 'interrupt' attribute:
6314 llvm::Function *F = cast<llvm::Function>(GV);
6315
6316 // Step 1: Set ISR calling convention.
6317 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6318
6319 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006320 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006321
6322 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006323 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006324 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6325 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006326 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006327 }
6328}
6329
Chris Lattner0cf24192010-06-28 20:05:43 +00006330//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006331// MIPS ABI Implementation. This works for both little-endian and
6332// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006333//===----------------------------------------------------------------------===//
6334
John McCall943fae92010-05-27 06:19:26 +00006335namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006336class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006337 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006338 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6339 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006340 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006341 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006342 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006343 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006344public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006345 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006346 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006347 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006348
6349 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006350 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006351 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006352 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6353 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006354 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006355};
6356
John McCall943fae92010-05-27 06:19:26 +00006357class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006358 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006359public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006360 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6361 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006362 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006363
Craig Topper4f12f102014-03-12 06:41:41 +00006364 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006365 return 29;
6366 }
6367
Eric Christopher162c91c2015-06-05 22:03:00 +00006368 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006369 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006370 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006371 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006372 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006373 if (FD->hasAttr<Mips16Attr>()) {
6374 Fn->addFnAttr("mips16");
6375 }
6376 else if (FD->hasAttr<NoMips16Attr>()) {
6377 Fn->addFnAttr("nomips16");
6378 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006379
6380 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6381 if (!Attr)
6382 return;
6383
6384 const char *Kind;
6385 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006386 case MipsInterruptAttr::eic: Kind = "eic"; break;
6387 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6388 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6389 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6390 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6391 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6392 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6393 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6394 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6395 }
6396
6397 Fn->addFnAttr("interrupt", Kind);
6398
Reed Kotler373feca2013-01-16 17:10:28 +00006399 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006400
John McCall943fae92010-05-27 06:19:26 +00006401 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006402 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006403
Craig Topper4f12f102014-03-12 06:41:41 +00006404 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006405 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006406 }
John McCall943fae92010-05-27 06:19:26 +00006407};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006408}
John McCall943fae92010-05-27 06:19:26 +00006409
Eric Christopher7565e0d2015-05-29 23:09:49 +00006410void MipsABIInfo::CoerceToIntArgs(
6411 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006412 llvm::IntegerType *IntTy =
6413 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006414
6415 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6416 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6417 ArgList.push_back(IntTy);
6418
6419 // If necessary, add one more integer type to ArgList.
6420 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6421
6422 if (R)
6423 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006424}
6425
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006426// In N32/64, an aligned double precision floating point field is passed in
6427// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006428llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006429 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6430
6431 if (IsO32) {
6432 CoerceToIntArgs(TySize, ArgList);
6433 return llvm::StructType::get(getVMContext(), ArgList);
6434 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006435
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006436 if (Ty->isComplexType())
6437 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006438
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006439 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006440
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006441 // Unions/vectors are passed in integer registers.
6442 if (!RT || !RT->isStructureOrClassType()) {
6443 CoerceToIntArgs(TySize, ArgList);
6444 return llvm::StructType::get(getVMContext(), ArgList);
6445 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006446
6447 const RecordDecl *RD = RT->getDecl();
6448 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006449 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006450
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006451 uint64_t LastOffset = 0;
6452 unsigned idx = 0;
6453 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6454
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006455 // Iterate over fields in the struct/class and check if there are any aligned
6456 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006457 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6458 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006459 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006460 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6461
6462 if (!BT || BT->getKind() != BuiltinType::Double)
6463 continue;
6464
6465 uint64_t Offset = Layout.getFieldOffset(idx);
6466 if (Offset % 64) // Ignore doubles that are not aligned.
6467 continue;
6468
6469 // Add ((Offset - LastOffset) / 64) args of type i64.
6470 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6471 ArgList.push_back(I64);
6472
6473 // Add double type.
6474 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6475 LastOffset = Offset + 64;
6476 }
6477
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006478 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6479 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006480
6481 return llvm::StructType::get(getVMContext(), ArgList);
6482}
6483
Akira Hatanakaddd66342013-10-29 18:41:15 +00006484llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6485 uint64_t Offset) const {
6486 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006487 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006488
Akira Hatanakaddd66342013-10-29 18:41:15 +00006489 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006490}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006491
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006492ABIArgInfo
6493MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006494 Ty = useFirstFieldIfTransparentUnion(Ty);
6495
Akira Hatanaka1632af62012-01-09 19:31:25 +00006496 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006497 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006498 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006499
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006500 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6501 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006502 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6503 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006504
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006505 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006506 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006507 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006508 return ABIArgInfo::getIgnore();
6509
Mark Lacey3825e832013-10-06 01:33:34 +00006510 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006511 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006512 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006513 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006514
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006515 // If we have reached here, aggregates are passed directly by coercing to
6516 // another structure type. Padding is inserted if the offset of the
6517 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006518 ABIArgInfo ArgInfo =
6519 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6520 getPaddingType(OrigOffset, CurrOffset));
6521 ArgInfo.setInReg(true);
6522 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006523 }
6524
6525 // Treat an enum type as its underlying type.
6526 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6527 Ty = EnumTy->getDecl()->getIntegerType();
6528
Daniel Sanders5b445b32014-10-24 14:42:42 +00006529 // All integral types are promoted to the GPR width.
6530 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006531 return ABIArgInfo::getExtend();
6532
Akira Hatanakaddd66342013-10-29 18:41:15 +00006533 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006534 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006535}
6536
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006537llvm::Type*
6538MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006539 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006540 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006541
Akira Hatanakab6f74432012-02-09 18:49:26 +00006542 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006543 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006544 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6545 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006546
Akira Hatanakab6f74432012-02-09 18:49:26 +00006547 // N32/64 returns struct/classes in floating point registers if the
6548 // following conditions are met:
6549 // 1. The size of the struct/class is no larger than 128-bit.
6550 // 2. The struct/class has one or two fields all of which are floating
6551 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006552 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006553 //
6554 // Any other composite results are returned in integer registers.
6555 //
6556 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6557 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6558 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006559 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006560
Akira Hatanakab6f74432012-02-09 18:49:26 +00006561 if (!BT || !BT->isFloatingPoint())
6562 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006563
David Blaikie2d7c57e2012-04-30 02:36:29 +00006564 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006565 }
6566
6567 if (b == e)
6568 return llvm::StructType::get(getVMContext(), RTList,
6569 RD->hasAttr<PackedAttr>());
6570
6571 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006572 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006573 }
6574
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006575 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006576 return llvm::StructType::get(getVMContext(), RTList);
6577}
6578
Akira Hatanakab579fe52011-06-02 00:09:17 +00006579ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006580 uint64_t Size = getContext().getTypeSize(RetTy);
6581
Daniel Sandersed39f582014-09-04 13:28:14 +00006582 if (RetTy->isVoidType())
6583 return ABIArgInfo::getIgnore();
6584
6585 // O32 doesn't treat zero-sized structs differently from other structs.
6586 // However, N32/N64 ignores zero sized return values.
6587 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006588 return ABIArgInfo::getIgnore();
6589
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006590 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006591 if (Size <= 128) {
6592 if (RetTy->isAnyComplexType())
6593 return ABIArgInfo::getDirect();
6594
Daniel Sanderse5018b62014-09-04 15:05:39 +00006595 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006596 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006597 if (!IsO32 ||
6598 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6599 ABIArgInfo ArgInfo =
6600 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6601 ArgInfo.setInReg(true);
6602 return ArgInfo;
6603 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006604 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006605
John McCall7f416cc2015-09-08 08:05:57 +00006606 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006607 }
6608
6609 // Treat an enum type as its underlying type.
6610 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6611 RetTy = EnumTy->getDecl()->getIntegerType();
6612
6613 return (RetTy->isPromotableIntegerType() ?
6614 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6615}
6616
6617void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006618 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006619 if (!getCXXABI().classifyReturnType(FI))
6620 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006621
Eric Christopher7565e0d2015-05-29 23:09:49 +00006622 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006623 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006624
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006625 for (auto &I : FI.arguments())
6626 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006627}
6628
John McCall7f416cc2015-09-08 08:05:57 +00006629Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6630 QualType OrigTy) const {
6631 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006632
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006633 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6634 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006635 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006636 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006637 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006638 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006639 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006640 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006641 DidPromote = true;
6642 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6643 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006644 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006645
John McCall7f416cc2015-09-08 08:05:57 +00006646 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006647
John McCall7f416cc2015-09-08 08:05:57 +00006648 // The alignment of things in the argument area is never larger than
6649 // StackAlignInBytes.
6650 TyInfo.second =
6651 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6652
6653 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6654 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6655
6656 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6657 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6658
6659
6660 // If there was a promotion, "unpromote" into a temporary.
6661 // TODO: can we just use a pointer into a subset of the original slot?
6662 if (DidPromote) {
6663 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6664 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6665
6666 // Truncate down to the right width.
6667 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6668 : CGF.IntPtrTy);
6669 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6670 if (OrigTy->isPointerType())
6671 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6672
6673 CGF.Builder.CreateStore(V, Temp);
6674 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006675 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006676
John McCall7f416cc2015-09-08 08:05:57 +00006677 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006678}
6679
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006680bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6681 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006682
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006683 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6684 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6685 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006686
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006687 return false;
6688}
6689
John McCall943fae92010-05-27 06:19:26 +00006690bool
6691MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6692 llvm::Value *Address) const {
6693 // This information comes from gcc's implementation, which seems to
6694 // as canonical as it gets.
6695
John McCall943fae92010-05-27 06:19:26 +00006696 // Everything on MIPS is 4 bytes. Double-precision FP registers
6697 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006698 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006699
6700 // 0-31 are the general purpose registers, $0 - $31.
6701 // 32-63 are the floating-point registers, $f0 - $f31.
6702 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6703 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006704 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006705
6706 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6707 // They are one bit wide and ignored here.
6708
6709 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6710 // (coprocessor 1 is the FP unit)
6711 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6712 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6713 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006714 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006715 return false;
6716}
6717
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006718//===----------------------------------------------------------------------===//
6719// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006720// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006721// handling.
6722//===----------------------------------------------------------------------===//
6723
6724namespace {
6725
6726class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6727public:
6728 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6729 : DefaultTargetCodeGenInfo(CGT) {}
6730
Eric Christopher162c91c2015-06-05 22:03:00 +00006731 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006732 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006733};
6734
Eric Christopher162c91c2015-06-05 22:03:00 +00006735void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006736 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006737 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006738 if (!FD) return;
6739
6740 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006741
David Blaikiebbafb8a2012-03-11 07:00:24 +00006742 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006743 if (FD->hasAttr<OpenCLKernelAttr>()) {
6744 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006745 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006746 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6747 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006748 // Convert the reqd_work_group_size() attributes to metadata.
6749 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006750 llvm::NamedMDNode *OpenCLMetadata =
6751 M.getModule().getOrInsertNamedMetadata(
6752 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006753
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006754 SmallVector<llvm::Metadata *, 5> Operands;
6755 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006756
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006757 Operands.push_back(
6758 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6759 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6760 Operands.push_back(
6761 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6762 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6763 Operands.push_back(
6764 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6765 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006766
Eric Christopher7565e0d2015-05-29 23:09:49 +00006767 // Add a boolean constant operand for "required" (true) or "hint"
6768 // (false) for implementing the work_group_size_hint attr later.
6769 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006770 Operands.push_back(
6771 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006772 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6773 }
6774 }
6775 }
6776}
6777
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006778}
John McCall943fae92010-05-27 06:19:26 +00006779
Tony Linthicum76329bf2011-12-12 21:14:55 +00006780//===----------------------------------------------------------------------===//
6781// Hexagon ABI Implementation
6782//===----------------------------------------------------------------------===//
6783
6784namespace {
6785
6786class HexagonABIInfo : public ABIInfo {
6787
6788
6789public:
6790 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6791
6792private:
6793
6794 ABIArgInfo classifyReturnType(QualType RetTy) const;
6795 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6796
Craig Topper4f12f102014-03-12 06:41:41 +00006797 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006798
John McCall7f416cc2015-09-08 08:05:57 +00006799 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6800 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006801};
6802
6803class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6804public:
6805 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6806 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6807
Craig Topper4f12f102014-03-12 06:41:41 +00006808 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006809 return 29;
6810 }
6811};
6812
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006813}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006814
6815void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006816 if (!getCXXABI().classifyReturnType(FI))
6817 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006818 for (auto &I : FI.arguments())
6819 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006820}
6821
6822ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6823 if (!isAggregateTypeForABI(Ty)) {
6824 // Treat an enum type as its underlying type.
6825 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6826 Ty = EnumTy->getDecl()->getIntegerType();
6827
6828 return (Ty->isPromotableIntegerType() ?
6829 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6830 }
6831
6832 // Ignore empty records.
6833 if (isEmptyRecord(getContext(), Ty, true))
6834 return ABIArgInfo::getIgnore();
6835
Mark Lacey3825e832013-10-06 01:33:34 +00006836 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006837 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006838
6839 uint64_t Size = getContext().getTypeSize(Ty);
6840 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006841 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006842 // Pass in the smallest viable integer type.
6843 else if (Size > 32)
6844 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6845 else if (Size > 16)
6846 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6847 else if (Size > 8)
6848 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6849 else
6850 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6851}
6852
6853ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6854 if (RetTy->isVoidType())
6855 return ABIArgInfo::getIgnore();
6856
6857 // Large vector types should be returned via memory.
6858 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006859 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006860
6861 if (!isAggregateTypeForABI(RetTy)) {
6862 // Treat an enum type as its underlying type.
6863 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6864 RetTy = EnumTy->getDecl()->getIntegerType();
6865
6866 return (RetTy->isPromotableIntegerType() ?
6867 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6868 }
6869
Tony Linthicum76329bf2011-12-12 21:14:55 +00006870 if (isEmptyRecord(getContext(), RetTy, true))
6871 return ABIArgInfo::getIgnore();
6872
6873 // Aggregates <= 8 bytes are returned in r0; other aggregates
6874 // are returned indirectly.
6875 uint64_t Size = getContext().getTypeSize(RetTy);
6876 if (Size <= 64) {
6877 // Return in the smallest viable integer type.
6878 if (Size <= 8)
6879 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6880 if (Size <= 16)
6881 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6882 if (Size <= 32)
6883 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6884 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6885 }
6886
John McCall7f416cc2015-09-08 08:05:57 +00006887 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006888}
6889
John McCall7f416cc2015-09-08 08:05:57 +00006890Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6891 QualType Ty) const {
6892 // FIXME: Someone needs to audit that this handle alignment correctly.
6893 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6894 getContext().getTypeInfoInChars(Ty),
6895 CharUnits::fromQuantity(4),
6896 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006897}
6898
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006899//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006900// Lanai ABI Implementation
6901//===----------------------------------------------------------------------===//
6902
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006903namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006904class LanaiABIInfo : public DefaultABIInfo {
6905public:
6906 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6907
6908 bool shouldUseInReg(QualType Ty, CCState &State) const;
6909
6910 void computeInfo(CGFunctionInfo &FI) const override {
6911 CCState State(FI.getCallingConvention());
6912 // Lanai uses 4 registers to pass arguments unless the function has the
6913 // regparm attribute set.
6914 if (FI.getHasRegParm()) {
6915 State.FreeRegs = FI.getRegParm();
6916 } else {
6917 State.FreeRegs = 4;
6918 }
6919
6920 if (!getCXXABI().classifyReturnType(FI))
6921 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6922 for (auto &I : FI.arguments())
6923 I.info = classifyArgumentType(I.type, State);
6924 }
6925
Jacques Pienaare74d9132016-04-26 00:09:29 +00006926 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006927 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6928};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006929} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006930
6931bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6932 unsigned Size = getContext().getTypeSize(Ty);
6933 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6934
6935 if (SizeInRegs == 0)
6936 return false;
6937
6938 if (SizeInRegs > State.FreeRegs) {
6939 State.FreeRegs = 0;
6940 return false;
6941 }
6942
6943 State.FreeRegs -= SizeInRegs;
6944
6945 return true;
6946}
6947
Jacques Pienaare74d9132016-04-26 00:09:29 +00006948ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6949 CCState &State) const {
6950 if (!ByVal) {
6951 if (State.FreeRegs) {
6952 --State.FreeRegs; // Non-byval indirects just use one pointer.
6953 return getNaturalAlignIndirectInReg(Ty);
6954 }
6955 return getNaturalAlignIndirect(Ty, false);
6956 }
6957
6958 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006959 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006960 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6961 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6962 /*Realign=*/TypeAlign >
6963 MinABIStackAlignInBytes);
6964}
6965
Jacques Pienaard964cc22016-03-28 21:02:54 +00006966ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6967 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006968 // Check with the C++ ABI first.
6969 const RecordType *RT = Ty->getAs<RecordType>();
6970 if (RT) {
6971 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6972 if (RAA == CGCXXABI::RAA_Indirect) {
6973 return getIndirectResult(Ty, /*ByVal=*/false, State);
6974 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6975 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6976 }
6977 }
6978
6979 if (isAggregateTypeForABI(Ty)) {
6980 // Structures with flexible arrays are always indirect.
6981 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6982 return getIndirectResult(Ty, /*ByVal=*/true, State);
6983
6984 // Ignore empty structs/unions.
6985 if (isEmptyRecord(getContext(), Ty, true))
6986 return ABIArgInfo::getIgnore();
6987
6988 llvm::LLVMContext &LLVMContext = getVMContext();
6989 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6990 if (SizeInRegs <= State.FreeRegs) {
6991 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
6992 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
6993 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
6994 State.FreeRegs -= SizeInRegs;
6995 return ABIArgInfo::getDirectInReg(Result);
6996 } else {
6997 State.FreeRegs = 0;
6998 }
6999 return getIndirectResult(Ty, true, State);
7000 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007001
7002 // Treat an enum type as its underlying type.
7003 if (const auto *EnumTy = Ty->getAs<EnumType>())
7004 Ty = EnumTy->getDecl()->getIntegerType();
7005
Jacques Pienaare74d9132016-04-26 00:09:29 +00007006 bool InReg = shouldUseInReg(Ty, State);
7007 if (Ty->isPromotableIntegerType()) {
7008 if (InReg)
7009 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007010 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007011 }
7012 if (InReg)
7013 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007014 return ABIArgInfo::getDirect();
7015}
7016
7017namespace {
7018class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7019public:
7020 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7021 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7022};
7023}
7024
7025//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007026// AMDGPU ABI Implementation
7027//===----------------------------------------------------------------------===//
7028
7029namespace {
7030
Matt Arsenault88d7da02016-08-22 19:25:59 +00007031class AMDGPUABIInfo final : public DefaultABIInfo {
7032public:
7033 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7034
7035private:
7036 ABIArgInfo classifyArgumentType(QualType Ty) const;
7037
7038 void computeInfo(CGFunctionInfo &FI) const override;
7039};
7040
7041void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7042 if (!getCXXABI().classifyReturnType(FI))
7043 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7044
7045 unsigned CC = FI.getCallingConvention();
7046 for (auto &Arg : FI.arguments())
7047 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7048 Arg.info = classifyArgumentType(Arg.type);
7049 else
7050 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7051}
7052
7053/// \brief Classify argument of given type \p Ty.
7054ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7055 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7056 if (!StrTy) {
7057 return DefaultABIInfo::classifyArgumentType(Ty);
7058 }
7059
7060 // Coerce single element structs to its element.
7061 if (StrTy->getNumElements() == 1) {
7062 return ABIArgInfo::getDirect();
7063 }
7064
7065 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7066 // individual elements, which confuses the Clover OpenCL backend; therefore we
7067 // have to set it to false here. Other args of getDirect() are just defaults.
7068 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7069}
7070
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007071class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7072public:
7073 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007074 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007075 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007076 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007077 unsigned getOpenCLKernelCallingConv() const override;
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007078};
7079
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007080}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007081
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007082static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7083
Eric Christopher162c91c2015-06-05 22:03:00 +00007084void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007085 const Decl *D,
7086 llvm::GlobalValue *GV,
7087 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007088 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007089 if (!FD)
7090 return;
7091
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007092 llvm::Function *F = cast<llvm::Function>(GV);
7093
7094 if (const auto *Attr = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7095 unsigned Min = Attr->getMin();
7096 unsigned Max = Attr->getMax();
7097
7098 if (Min != 0) {
7099 assert(Min <= Max && "Min must be less than or equal Max");
7100
7101 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7102 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7103 } else
7104 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007105 }
7106
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007107 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7108 unsigned Min = Attr->getMin();
7109 unsigned Max = Attr->getMax();
7110
7111 if (Min != 0) {
7112 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7113
7114 std::string AttrVal = llvm::utostr(Min);
7115 if (Max != 0)
7116 AttrVal = AttrVal + "," + llvm::utostr(Max);
7117 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7118 } else
7119 assert(Max == 0 && "Max must be zero");
7120 }
7121
7122 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007123 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007124
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007125 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007126 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7127 }
7128
7129 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7130 uint32_t NumVGPR = Attr->getNumVGPR();
7131
7132 if (NumVGPR != 0)
7133 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007134 }
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007135
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007136 appendOpenCLVersionMD(M);
7137}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007138
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007139unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7140 return llvm::CallingConv::AMDGPU_KERNEL;
7141}
7142
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007143//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007144// SPARC v8 ABI Implementation.
7145// Based on the SPARC Compliance Definition version 2.4.1.
7146//
7147// Ensures that complex values are passed in registers.
7148//
7149namespace {
7150class SparcV8ABIInfo : public DefaultABIInfo {
7151public:
7152 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7153
7154private:
7155 ABIArgInfo classifyReturnType(QualType RetTy) const;
7156 void computeInfo(CGFunctionInfo &FI) const override;
7157};
7158} // end anonymous namespace
7159
7160
7161ABIArgInfo
7162SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7163 if (Ty->isAnyComplexType()) {
7164 return ABIArgInfo::getDirect();
7165 }
7166 else {
7167 return DefaultABIInfo::classifyReturnType(Ty);
7168 }
7169}
7170
7171void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7172
7173 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7174 for (auto &Arg : FI.arguments())
7175 Arg.info = classifyArgumentType(Arg.type);
7176}
7177
7178namespace {
7179class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7180public:
7181 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7182 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7183};
7184} // end anonymous namespace
7185
7186//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007187// SPARC v9 ABI Implementation.
7188// Based on the SPARC Compliance Definition version 2.4.1.
7189//
7190// Function arguments a mapped to a nominal "parameter array" and promoted to
7191// registers depending on their type. Each argument occupies 8 or 16 bytes in
7192// the array, structs larger than 16 bytes are passed indirectly.
7193//
7194// One case requires special care:
7195//
7196// struct mixed {
7197// int i;
7198// float f;
7199// };
7200//
7201// When a struct mixed is passed by value, it only occupies 8 bytes in the
7202// parameter array, but the int is passed in an integer register, and the float
7203// is passed in a floating point register. This is represented as two arguments
7204// with the LLVM IR inreg attribute:
7205//
7206// declare void f(i32 inreg %i, float inreg %f)
7207//
7208// The code generator will only allocate 4 bytes from the parameter array for
7209// the inreg arguments. All other arguments are allocated a multiple of 8
7210// bytes.
7211//
7212namespace {
7213class SparcV9ABIInfo : public ABIInfo {
7214public:
7215 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7216
7217private:
7218 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007219 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007220 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7221 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007222
7223 // Coercion type builder for structs passed in registers. The coercion type
7224 // serves two purposes:
7225 //
7226 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7227 // in registers.
7228 // 2. Expose aligned floating point elements as first-level elements, so the
7229 // code generator knows to pass them in floating point registers.
7230 //
7231 // We also compute the InReg flag which indicates that the struct contains
7232 // aligned 32-bit floats.
7233 //
7234 struct CoerceBuilder {
7235 llvm::LLVMContext &Context;
7236 const llvm::DataLayout &DL;
7237 SmallVector<llvm::Type*, 8> Elems;
7238 uint64_t Size;
7239 bool InReg;
7240
7241 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7242 : Context(c), DL(dl), Size(0), InReg(false) {}
7243
7244 // Pad Elems with integers until Size is ToSize.
7245 void pad(uint64_t ToSize) {
7246 assert(ToSize >= Size && "Cannot remove elements");
7247 if (ToSize == Size)
7248 return;
7249
7250 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007251 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007252 if (Aligned > Size && Aligned <= ToSize) {
7253 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7254 Size = Aligned;
7255 }
7256
7257 // Add whole 64-bit words.
7258 while (Size + 64 <= ToSize) {
7259 Elems.push_back(llvm::Type::getInt64Ty(Context));
7260 Size += 64;
7261 }
7262
7263 // Final in-word padding.
7264 if (Size < ToSize) {
7265 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7266 Size = ToSize;
7267 }
7268 }
7269
7270 // Add a floating point element at Offset.
7271 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7272 // Unaligned floats are treated as integers.
7273 if (Offset % Bits)
7274 return;
7275 // The InReg flag is only required if there are any floats < 64 bits.
7276 if (Bits < 64)
7277 InReg = true;
7278 pad(Offset);
7279 Elems.push_back(Ty);
7280 Size = Offset + Bits;
7281 }
7282
7283 // Add a struct type to the coercion type, starting at Offset (in bits).
7284 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7285 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7286 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7287 llvm::Type *ElemTy = StrTy->getElementType(i);
7288 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7289 switch (ElemTy->getTypeID()) {
7290 case llvm::Type::StructTyID:
7291 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7292 break;
7293 case llvm::Type::FloatTyID:
7294 addFloat(ElemOffset, ElemTy, 32);
7295 break;
7296 case llvm::Type::DoubleTyID:
7297 addFloat(ElemOffset, ElemTy, 64);
7298 break;
7299 case llvm::Type::FP128TyID:
7300 addFloat(ElemOffset, ElemTy, 128);
7301 break;
7302 case llvm::Type::PointerTyID:
7303 if (ElemOffset % 64 == 0) {
7304 pad(ElemOffset);
7305 Elems.push_back(ElemTy);
7306 Size += 64;
7307 }
7308 break;
7309 default:
7310 break;
7311 }
7312 }
7313 }
7314
7315 // Check if Ty is a usable substitute for the coercion type.
7316 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007317 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007318 }
7319
7320 // Get the coercion type as a literal struct type.
7321 llvm::Type *getType() const {
7322 if (Elems.size() == 1)
7323 return Elems.front();
7324 else
7325 return llvm::StructType::get(Context, Elems);
7326 }
7327 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007328};
7329} // end anonymous namespace
7330
7331ABIArgInfo
7332SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7333 if (Ty->isVoidType())
7334 return ABIArgInfo::getIgnore();
7335
7336 uint64_t Size = getContext().getTypeSize(Ty);
7337
7338 // Anything too big to fit in registers is passed with an explicit indirect
7339 // pointer / sret pointer.
7340 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007341 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007342
7343 // Treat an enum type as its underlying type.
7344 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7345 Ty = EnumTy->getDecl()->getIntegerType();
7346
7347 // Integer types smaller than a register are extended.
7348 if (Size < 64 && Ty->isIntegerType())
7349 return ABIArgInfo::getExtend();
7350
7351 // Other non-aggregates go in registers.
7352 if (!isAggregateTypeForABI(Ty))
7353 return ABIArgInfo::getDirect();
7354
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007355 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7356 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7357 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007358 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007359
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007360 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007361 // Build a coercion type from the LLVM struct type.
7362 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7363 if (!StrTy)
7364 return ABIArgInfo::getDirect();
7365
7366 CoerceBuilder CB(getVMContext(), getDataLayout());
7367 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007368 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007369
7370 // Try to use the original type for coercion.
7371 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7372
7373 if (CB.InReg)
7374 return ABIArgInfo::getDirectInReg(CoerceTy);
7375 else
7376 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007377}
7378
John McCall7f416cc2015-09-08 08:05:57 +00007379Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7380 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007381 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7382 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7383 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7384 AI.setCoerceToType(ArgTy);
7385
John McCall7f416cc2015-09-08 08:05:57 +00007386 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007387
John McCall7f416cc2015-09-08 08:05:57 +00007388 CGBuilderTy &Builder = CGF.Builder;
7389 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7390 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7391
7392 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7393
7394 Address ArgAddr = Address::invalid();
7395 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007396 switch (AI.getKind()) {
7397 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007398 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007399 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007400 llvm_unreachable("Unsupported ABI kind for va_arg");
7401
John McCall7f416cc2015-09-08 08:05:57 +00007402 case ABIArgInfo::Extend: {
7403 Stride = SlotSize;
7404 CharUnits Offset = SlotSize - TypeInfo.first;
7405 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007406 break;
John McCall7f416cc2015-09-08 08:05:57 +00007407 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007408
John McCall7f416cc2015-09-08 08:05:57 +00007409 case ABIArgInfo::Direct: {
7410 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007411 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007412 ArgAddr = Addr;
7413 break;
John McCall7f416cc2015-09-08 08:05:57 +00007414 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007415
7416 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007417 Stride = SlotSize;
7418 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7419 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7420 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007421 break;
7422
7423 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007424 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007425 }
7426
7427 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007428 llvm::Value *NextPtr =
7429 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7430 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007431
John McCall7f416cc2015-09-08 08:05:57 +00007432 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007433}
7434
7435void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7436 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007437 for (auto &I : FI.arguments())
7438 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007439}
7440
7441namespace {
7442class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7443public:
7444 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7445 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007446
Craig Topper4f12f102014-03-12 06:41:41 +00007447 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007448 return 14;
7449 }
7450
7451 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007452 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007453};
7454} // end anonymous namespace
7455
Roman Divackyf02c9942014-02-24 18:46:27 +00007456bool
7457SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7458 llvm::Value *Address) const {
7459 // This is calculated from the LLVM and GCC tables and verified
7460 // against gcc output. AFAIK all ABIs use the same encoding.
7461
7462 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7463
7464 llvm::IntegerType *i8 = CGF.Int8Ty;
7465 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7466 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7467
7468 // 0-31: the 8-byte general-purpose registers
7469 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7470
7471 // 32-63: f0-31, the 4-byte floating-point registers
7472 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7473
7474 // Y = 64
7475 // PSR = 65
7476 // WIM = 66
7477 // TBR = 67
7478 // PC = 68
7479 // NPC = 69
7480 // FSR = 70
7481 // CSR = 71
7482 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007483
Roman Divackyf02c9942014-02-24 18:46:27 +00007484 // 72-87: d0-15, the 8-byte floating-point registers
7485 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7486
7487 return false;
7488}
7489
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007490
Robert Lytton0e076492013-08-13 09:43:10 +00007491//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007492// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007493//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007494
Robert Lytton0e076492013-08-13 09:43:10 +00007495namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007496
7497/// A SmallStringEnc instance is used to build up the TypeString by passing
7498/// it by reference between functions that append to it.
7499typedef llvm::SmallString<128> SmallStringEnc;
7500
7501/// TypeStringCache caches the meta encodings of Types.
7502///
7503/// The reason for caching TypeStrings is two fold:
7504/// 1. To cache a type's encoding for later uses;
7505/// 2. As a means to break recursive member type inclusion.
7506///
7507/// A cache Entry can have a Status of:
7508/// NonRecursive: The type encoding is not recursive;
7509/// Recursive: The type encoding is recursive;
7510/// Incomplete: An incomplete TypeString;
7511/// IncompleteUsed: An incomplete TypeString that has been used in a
7512/// Recursive type encoding.
7513///
7514/// A NonRecursive entry will have all of its sub-members expanded as fully
7515/// as possible. Whilst it may contain types which are recursive, the type
7516/// itself is not recursive and thus its encoding may be safely used whenever
7517/// the type is encountered.
7518///
7519/// A Recursive entry will have all of its sub-members expanded as fully as
7520/// possible. The type itself is recursive and it may contain other types which
7521/// are recursive. The Recursive encoding must not be used during the expansion
7522/// of a recursive type's recursive branch. For simplicity the code uses
7523/// IncompleteCount to reject all usage of Recursive encodings for member types.
7524///
7525/// An Incomplete entry is always a RecordType and only encodes its
7526/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7527/// are placed into the cache during type expansion as a means to identify and
7528/// handle recursive inclusion of types as sub-members. If there is recursion
7529/// the entry becomes IncompleteUsed.
7530///
7531/// During the expansion of a RecordType's members:
7532///
7533/// If the cache contains a NonRecursive encoding for the member type, the
7534/// cached encoding is used;
7535///
7536/// If the cache contains a Recursive encoding for the member type, the
7537/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7538///
7539/// If the member is a RecordType, an Incomplete encoding is placed into the
7540/// cache to break potential recursive inclusion of itself as a sub-member;
7541///
7542/// Once a member RecordType has been expanded, its temporary incomplete
7543/// entry is removed from the cache. If a Recursive encoding was swapped out
7544/// it is swapped back in;
7545///
7546/// If an incomplete entry is used to expand a sub-member, the incomplete
7547/// entry is marked as IncompleteUsed. The cache keeps count of how many
7548/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7549///
7550/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7551/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7552/// Else the member is part of a recursive type and thus the recursion has
7553/// been exited too soon for the encoding to be correct for the member.
7554///
7555class TypeStringCache {
7556 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7557 struct Entry {
7558 std::string Str; // The encoded TypeString for the type.
7559 enum Status State; // Information about the encoding in 'Str'.
7560 std::string Swapped; // A temporary place holder for a Recursive encoding
7561 // during the expansion of RecordType's members.
7562 };
7563 std::map<const IdentifierInfo *, struct Entry> Map;
7564 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7565 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7566public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007567 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007568 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7569 bool removeIncomplete(const IdentifierInfo *ID);
7570 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7571 bool IsRecursive);
7572 StringRef lookupStr(const IdentifierInfo *ID);
7573};
7574
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007575/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007576/// FieldEncoding is a helper for this ordering process.
7577class FieldEncoding {
7578 bool HasName;
7579 std::string Enc;
7580public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007581 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007582 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007583 bool operator<(const FieldEncoding &rhs) const {
7584 if (HasName != rhs.HasName) return HasName;
7585 return Enc < rhs.Enc;
7586 }
7587};
7588
Robert Lytton7d1db152013-08-19 09:46:39 +00007589class XCoreABIInfo : public DefaultABIInfo {
7590public:
7591 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007592 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7593 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007594};
7595
Robert Lyttond21e2d72014-03-03 13:45:29 +00007596class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007597 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007598public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007599 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007600 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007601 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7602 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007603};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007604
Robert Lytton2d196952013-10-11 10:29:34 +00007605} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007606
James Y Knight29b5f082016-02-24 02:59:33 +00007607// TODO: this implementation is likely now redundant with the default
7608// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007609Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7610 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007611 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007612
Robert Lytton2d196952013-10-11 10:29:34 +00007613 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007614 CharUnits SlotSize = CharUnits::fromQuantity(4);
7615 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007616
Robert Lytton2d196952013-10-11 10:29:34 +00007617 // Handle the argument.
7618 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007619 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007620 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7621 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7622 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007623 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007624
7625 Address Val = Address::invalid();
7626 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007627 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007628 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007629 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007630 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007631 llvm_unreachable("Unsupported ABI kind for va_arg");
7632 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007633 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7634 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007635 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007636 case ABIArgInfo::Extend:
7637 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007638 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7639 ArgSize = CharUnits::fromQuantity(
7640 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007641 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007642 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007643 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007644 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7645 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7646 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007647 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007648 }
Robert Lytton2d196952013-10-11 10:29:34 +00007649
7650 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007651 if (!ArgSize.isZero()) {
7652 llvm::Value *APN =
7653 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7654 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007655 }
John McCall7f416cc2015-09-08 08:05:57 +00007656
Robert Lytton2d196952013-10-11 10:29:34 +00007657 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007658}
Robert Lytton0e076492013-08-13 09:43:10 +00007659
Robert Lytton844aeeb2014-05-02 09:33:20 +00007660/// During the expansion of a RecordType, an incomplete TypeString is placed
7661/// into the cache as a means to identify and break recursion.
7662/// If there is a Recursive encoding in the cache, it is swapped out and will
7663/// be reinserted by removeIncomplete().
7664/// All other types of encoding should have been used rather than arriving here.
7665void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7666 std::string StubEnc) {
7667 if (!ID)
7668 return;
7669 Entry &E = Map[ID];
7670 assert( (E.Str.empty() || E.State == Recursive) &&
7671 "Incorrectly use of addIncomplete");
7672 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7673 E.Swapped.swap(E.Str); // swap out the Recursive
7674 E.Str.swap(StubEnc);
7675 E.State = Incomplete;
7676 ++IncompleteCount;
7677}
7678
7679/// Once the RecordType has been expanded, the temporary incomplete TypeString
7680/// must be removed from the cache.
7681/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7682/// Returns true if the RecordType was defined recursively.
7683bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7684 if (!ID)
7685 return false;
7686 auto I = Map.find(ID);
7687 assert(I != Map.end() && "Entry not present");
7688 Entry &E = I->second;
7689 assert( (E.State == Incomplete ||
7690 E.State == IncompleteUsed) &&
7691 "Entry must be an incomplete type");
7692 bool IsRecursive = false;
7693 if (E.State == IncompleteUsed) {
7694 // We made use of our Incomplete encoding, thus we are recursive.
7695 IsRecursive = true;
7696 --IncompleteUsedCount;
7697 }
7698 if (E.Swapped.empty())
7699 Map.erase(I);
7700 else {
7701 // Swap the Recursive back.
7702 E.Swapped.swap(E.Str);
7703 E.Swapped.clear();
7704 E.State = Recursive;
7705 }
7706 --IncompleteCount;
7707 return IsRecursive;
7708}
7709
7710/// Add the encoded TypeString to the cache only if it is NonRecursive or
7711/// Recursive (viz: all sub-members were expanded as fully as possible).
7712void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7713 bool IsRecursive) {
7714 if (!ID || IncompleteUsedCount)
7715 return; // No key or it is is an incomplete sub-type so don't add.
7716 Entry &E = Map[ID];
7717 if (IsRecursive && !E.Str.empty()) {
7718 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7719 "This is not the same Recursive entry");
7720 // The parent container was not recursive after all, so we could have used
7721 // this Recursive sub-member entry after all, but we assumed the worse when
7722 // we started viz: IncompleteCount!=0.
7723 return;
7724 }
7725 assert(E.Str.empty() && "Entry already present");
7726 E.Str = Str.str();
7727 E.State = IsRecursive? Recursive : NonRecursive;
7728}
7729
7730/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7731/// are recursively expanding a type (IncompleteCount != 0) and the cached
7732/// encoding is Recursive, return an empty StringRef.
7733StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7734 if (!ID)
7735 return StringRef(); // We have no key.
7736 auto I = Map.find(ID);
7737 if (I == Map.end())
7738 return StringRef(); // We have no encoding.
7739 Entry &E = I->second;
7740 if (E.State == Recursive && IncompleteCount)
7741 return StringRef(); // We don't use Recursive encodings for member types.
7742
7743 if (E.State == Incomplete) {
7744 // The incomplete type is being used to break out of recursion.
7745 E.State = IncompleteUsed;
7746 ++IncompleteUsedCount;
7747 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007748 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007749}
7750
7751/// The XCore ABI includes a type information section that communicates symbol
7752/// type information to the linker. The linker uses this information to verify
7753/// safety/correctness of things such as array bound and pointers et al.
7754/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7755/// This type information (TypeString) is emitted into meta data for all global
7756/// symbols: definitions, declarations, functions & variables.
7757///
7758/// The TypeString carries type, qualifier, name, size & value details.
7759/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007760/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007761/// The output is tested by test/CodeGen/xcore-stringtype.c.
7762///
7763static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7764 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7765
7766/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7767void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7768 CodeGen::CodeGenModule &CGM) const {
7769 SmallStringEnc Enc;
7770 if (getTypeString(Enc, D, CGM, TSC)) {
7771 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00007772 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
7773 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007774 llvm::NamedMDNode *MD =
7775 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7776 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7777 }
7778}
7779
Xiuli Pan972bea82016-03-24 03:57:17 +00007780//===----------------------------------------------------------------------===//
7781// SPIR ABI Implementation
7782//===----------------------------------------------------------------------===//
7783
7784namespace {
7785class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7786public:
7787 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7788 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7789 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7790 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007791 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00007792};
7793} // End anonymous namespace.
7794
7795/// Emit SPIR specific metadata: OpenCL and SPIR version.
7796void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7797 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007798 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7799 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7800 llvm::Module &M = CGM.getModule();
7801 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7802 // opencl.spir.version named metadata.
7803 llvm::Metadata *SPIRVerElts[] = {
7804 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 2)),
7805 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int32Ty, 0))};
7806 llvm::NamedMDNode *SPIRVerMD =
7807 M.getOrInsertNamedMetadata("opencl.spir.version");
7808 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007809 appendOpenCLVersionMD(CGM);
7810}
7811
Matt Arsenault8afb5cd2016-09-07 07:07:59 +00007812static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007813 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7814 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7815 llvm::Module &M = CGM.getModule();
Xiuli Pan972bea82016-03-24 03:57:17 +00007816 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7817 // opencl.ocl.version named metadata node.
7818 llvm::Metadata *OCLVerElts[] = {
7819 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7820 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7821 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7822 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7823 llvm::NamedMDNode *OCLVerMD =
7824 M.getOrInsertNamedMetadata("opencl.ocl.version");
7825 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7826}
7827
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007828unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7829 return llvm::CallingConv::SPIR_KERNEL;
7830}
7831
Robert Lytton844aeeb2014-05-02 09:33:20 +00007832static bool appendType(SmallStringEnc &Enc, QualType QType,
7833 const CodeGen::CodeGenModule &CGM,
7834 TypeStringCache &TSC);
7835
7836/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007837/// Builds a SmallVector containing the encoded field types in declaration
7838/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007839static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7840 const RecordDecl *RD,
7841 const CodeGen::CodeGenModule &CGM,
7842 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007843 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007844 SmallStringEnc Enc;
7845 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007846 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007847 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007848 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007849 Enc += "b(";
7850 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007851 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007852 Enc += ':';
7853 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007854 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007855 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007856 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007857 Enc += ')';
7858 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007859 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007860 }
7861 return true;
7862}
7863
7864/// Appends structure and union types to Enc and adds encoding to cache.
7865/// Recursively calls appendType (via extractFieldType) for each field.
7866/// Union types have their fields ordered according to the ABI.
7867static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7868 const CodeGen::CodeGenModule &CGM,
7869 TypeStringCache &TSC, const IdentifierInfo *ID) {
7870 // Append the cached TypeString if we have one.
7871 StringRef TypeString = TSC.lookupStr(ID);
7872 if (!TypeString.empty()) {
7873 Enc += TypeString;
7874 return true;
7875 }
7876
7877 // Start to emit an incomplete TypeString.
7878 size_t Start = Enc.size();
7879 Enc += (RT->isUnionType()? 'u' : 's');
7880 Enc += '(';
7881 if (ID)
7882 Enc += ID->getName();
7883 Enc += "){";
7884
7885 // We collect all encoded fields and order as necessary.
7886 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007887 const RecordDecl *RD = RT->getDecl()->getDefinition();
7888 if (RD && !RD->field_empty()) {
7889 // An incomplete TypeString stub is placed in the cache for this RecordType
7890 // so that recursive calls to this RecordType will use it whilst building a
7891 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007892 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007893 std::string StubEnc(Enc.substr(Start).str());
7894 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7895 TSC.addIncomplete(ID, std::move(StubEnc));
7896 if (!extractFieldType(FE, RD, CGM, TSC)) {
7897 (void) TSC.removeIncomplete(ID);
7898 return false;
7899 }
7900 IsRecursive = TSC.removeIncomplete(ID);
7901 // The ABI requires unions to be sorted but not structures.
7902 // See FieldEncoding::operator< for sort algorithm.
7903 if (RT->isUnionType())
7904 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007905 // We can now complete the TypeString.
7906 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007907 for (unsigned I = 0; I != E; ++I) {
7908 if (I)
7909 Enc += ',';
7910 Enc += FE[I].str();
7911 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007912 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007913 Enc += '}';
7914 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7915 return true;
7916}
7917
7918/// Appends enum types to Enc and adds the encoding to the cache.
7919static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7920 TypeStringCache &TSC,
7921 const IdentifierInfo *ID) {
7922 // Append the cached TypeString if we have one.
7923 StringRef TypeString = TSC.lookupStr(ID);
7924 if (!TypeString.empty()) {
7925 Enc += TypeString;
7926 return true;
7927 }
7928
7929 size_t Start = Enc.size();
7930 Enc += "e(";
7931 if (ID)
7932 Enc += ID->getName();
7933 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007934
7935 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007936 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007937 SmallVector<FieldEncoding, 16> FE;
7938 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7939 ++I) {
7940 SmallStringEnc EnumEnc;
7941 EnumEnc += "m(";
7942 EnumEnc += I->getName();
7943 EnumEnc += "){";
7944 I->getInitVal().toString(EnumEnc);
7945 EnumEnc += '}';
7946 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7947 }
7948 std::sort(FE.begin(), FE.end());
7949 unsigned E = FE.size();
7950 for (unsigned I = 0; I != E; ++I) {
7951 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007952 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007953 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007954 }
7955 }
7956 Enc += '}';
7957 TSC.addIfComplete(ID, Enc.substr(Start), false);
7958 return true;
7959}
7960
7961/// Appends type's qualifier to Enc.
7962/// This is done prior to appending the type's encoding.
7963static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7964 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007965 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007966 int Lookup = 0;
7967 if (QT.isConstQualified())
7968 Lookup += 1<<0;
7969 if (QT.isRestrictQualified())
7970 Lookup += 1<<1;
7971 if (QT.isVolatileQualified())
7972 Lookup += 1<<2;
7973 Enc += Table[Lookup];
7974}
7975
7976/// Appends built-in types to Enc.
7977static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7978 const char *EncType;
7979 switch (BT->getKind()) {
7980 case BuiltinType::Void:
7981 EncType = "0";
7982 break;
7983 case BuiltinType::Bool:
7984 EncType = "b";
7985 break;
7986 case BuiltinType::Char_U:
7987 EncType = "uc";
7988 break;
7989 case BuiltinType::UChar:
7990 EncType = "uc";
7991 break;
7992 case BuiltinType::SChar:
7993 EncType = "sc";
7994 break;
7995 case BuiltinType::UShort:
7996 EncType = "us";
7997 break;
7998 case BuiltinType::Short:
7999 EncType = "ss";
8000 break;
8001 case BuiltinType::UInt:
8002 EncType = "ui";
8003 break;
8004 case BuiltinType::Int:
8005 EncType = "si";
8006 break;
8007 case BuiltinType::ULong:
8008 EncType = "ul";
8009 break;
8010 case BuiltinType::Long:
8011 EncType = "sl";
8012 break;
8013 case BuiltinType::ULongLong:
8014 EncType = "ull";
8015 break;
8016 case BuiltinType::LongLong:
8017 EncType = "sll";
8018 break;
8019 case BuiltinType::Float:
8020 EncType = "ft";
8021 break;
8022 case BuiltinType::Double:
8023 EncType = "d";
8024 break;
8025 case BuiltinType::LongDouble:
8026 EncType = "ld";
8027 break;
8028 default:
8029 return false;
8030 }
8031 Enc += EncType;
8032 return true;
8033}
8034
8035/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8036static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8037 const CodeGen::CodeGenModule &CGM,
8038 TypeStringCache &TSC) {
8039 Enc += "p(";
8040 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8041 return false;
8042 Enc += ')';
8043 return true;
8044}
8045
8046/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008047static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8048 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008049 const CodeGen::CodeGenModule &CGM,
8050 TypeStringCache &TSC, StringRef NoSizeEnc) {
8051 if (AT->getSizeModifier() != ArrayType::Normal)
8052 return false;
8053 Enc += "a(";
8054 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8055 CAT->getSize().toStringUnsigned(Enc);
8056 else
8057 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8058 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008059 // The Qualifiers should be attached to the type rather than the array.
8060 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008061 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8062 return false;
8063 Enc += ')';
8064 return true;
8065}
8066
8067/// Appends a function encoding to Enc, calling appendType for the return type
8068/// and the arguments.
8069static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8070 const CodeGen::CodeGenModule &CGM,
8071 TypeStringCache &TSC) {
8072 Enc += "f{";
8073 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8074 return false;
8075 Enc += "}(";
8076 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8077 // N.B. we are only interested in the adjusted param types.
8078 auto I = FPT->param_type_begin();
8079 auto E = FPT->param_type_end();
8080 if (I != E) {
8081 do {
8082 if (!appendType(Enc, *I, CGM, TSC))
8083 return false;
8084 ++I;
8085 if (I != E)
8086 Enc += ',';
8087 } while (I != E);
8088 if (FPT->isVariadic())
8089 Enc += ",va";
8090 } else {
8091 if (FPT->isVariadic())
8092 Enc += "va";
8093 else
8094 Enc += '0';
8095 }
8096 }
8097 Enc += ')';
8098 return true;
8099}
8100
8101/// Handles the type's qualifier before dispatching a call to handle specific
8102/// type encodings.
8103static bool appendType(SmallStringEnc &Enc, QualType QType,
8104 const CodeGen::CodeGenModule &CGM,
8105 TypeStringCache &TSC) {
8106
8107 QualType QT = QType.getCanonicalType();
8108
Robert Lytton6adb20f2014-06-05 09:06:21 +00008109 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8110 // The Qualifiers should be attached to the type rather than the array.
8111 // Thus we don't call appendQualifier() here.
8112 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8113
Robert Lytton844aeeb2014-05-02 09:33:20 +00008114 appendQualifier(Enc, QT);
8115
8116 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8117 return appendBuiltinType(Enc, BT);
8118
Robert Lytton844aeeb2014-05-02 09:33:20 +00008119 if (const PointerType *PT = QT->getAs<PointerType>())
8120 return appendPointerType(Enc, PT, CGM, TSC);
8121
8122 if (const EnumType *ET = QT->getAs<EnumType>())
8123 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8124
8125 if (const RecordType *RT = QT->getAsStructureType())
8126 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8127
8128 if (const RecordType *RT = QT->getAsUnionType())
8129 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8130
8131 if (const FunctionType *FT = QT->getAs<FunctionType>())
8132 return appendFunctionType(Enc, FT, CGM, TSC);
8133
8134 return false;
8135}
8136
8137static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8138 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8139 if (!D)
8140 return false;
8141
8142 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8143 if (FD->getLanguageLinkage() != CLanguageLinkage)
8144 return false;
8145 return appendType(Enc, FD->getType(), CGM, TSC);
8146 }
8147
8148 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8149 if (VD->getLanguageLinkage() != CLanguageLinkage)
8150 return false;
8151 QualType QT = VD->getType().getCanonicalType();
8152 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8153 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008154 // The Qualifiers should be attached to the type rather than the array.
8155 // Thus we don't call appendQualifier() here.
8156 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008157 }
8158 return appendType(Enc, QT, CGM, TSC);
8159 }
8160 return false;
8161}
8162
8163
Robert Lytton0e076492013-08-13 09:43:10 +00008164//===----------------------------------------------------------------------===//
8165// Driver code
8166//===----------------------------------------------------------------------===//
8167
Rafael Espindola9f834732014-09-19 01:54:22 +00008168bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008169 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008170}
8171
Chris Lattner2b037972010-07-29 02:01:43 +00008172const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008173 if (TheTargetCodeGenInfo)
8174 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008175
Reid Kleckner9305fd12016-04-13 23:37:17 +00008176 // Helper to set the unique_ptr while still keeping the return value.
8177 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8178 this->TheTargetCodeGenInfo.reset(P);
8179 return *P;
8180 };
8181
John McCallc8e01702013-04-16 22:48:15 +00008182 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008183 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008184 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008185 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008186
Derek Schuff09338a22012-09-06 17:37:28 +00008187 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008188 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008189 case llvm::Triple::mips:
8190 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008191 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008192 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8193 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008194
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008195 case llvm::Triple::mips64:
8196 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008197 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008198
Tim Northover25e8a672014-05-24 12:51:25 +00008199 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008200 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008201 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008202 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008203 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00008204
Reid Kleckner9305fd12016-04-13 23:37:17 +00008205 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008206 }
8207
Dan Gohmanc2853072015-09-03 22:51:53 +00008208 case llvm::Triple::wasm32:
8209 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008210 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008211
Daniel Dunbard59655c2009-09-12 00:59:49 +00008212 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008213 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008214 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008215 case llvm::Triple::thumbeb: {
8216 if (Triple.getOS() == llvm::Triple::Win32) {
8217 return SetCGInfo(
8218 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008219 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008220
Reid Kleckner9305fd12016-04-13 23:37:17 +00008221 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8222 StringRef ABIStr = getTarget().getABI();
8223 if (ABIStr == "apcs-gnu")
8224 Kind = ARMABIInfo::APCS;
8225 else if (ABIStr == "aapcs16")
8226 Kind = ARMABIInfo::AAPCS16_VFP;
8227 else if (CodeGenOpts.FloatABI == "hard" ||
8228 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008229 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008230 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008231 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008232 Kind = ARMABIInfo::AAPCS_VFP;
8233
8234 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8235 }
8236
John McCallea8d8bb2010-03-11 00:10:12 +00008237 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008238 return SetCGInfo(
8239 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008240 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008241 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008242 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008243 if (getTarget().getABI() == "elfv2")
8244 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008245 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008246 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008247
Hal Finkel415c2a32016-10-02 02:10:45 +00008248 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8249 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008250 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008251 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008252 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008253 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008254 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008255 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008256 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008257 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008258 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008259
Hal Finkel415c2a32016-10-02 02:10:45 +00008260 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8261 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008262 }
John McCallea8d8bb2010-03-11 00:10:12 +00008263
Peter Collingbournec947aae2012-05-20 23:28:41 +00008264 case llvm::Triple::nvptx:
8265 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008266 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008267
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008268 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008269 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008270
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008271 case llvm::Triple::systemz: {
8272 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008273 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008274 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008275
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008276 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008277 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008278 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008279
Eli Friedman33465822011-07-08 23:31:17 +00008280 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008281 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008282 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008283 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008284 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008285
John McCall1fe2a8c2013-06-18 02:46:29 +00008286 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008287 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8288 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8289 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008290 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008291 return SetCGInfo(new X86_32TargetCodeGenInfo(
8292 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8293 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8294 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008295 }
Eli Friedman33465822011-07-08 23:31:17 +00008296 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008297
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008298 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008299 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008300 X86AVXABILevel AVXLevel =
8301 (ABI == "avx512"
8302 ? X86AVXABILevel::AVX512
8303 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008304
Chris Lattner04dc9572010-08-31 16:44:54 +00008305 switch (Triple.getOS()) {
8306 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008307 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008308 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008309 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008310 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008311 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008312 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008313 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008314 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008315 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008316 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008317 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008318 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008319 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008320 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008321 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008322 case llvm::Triple::sparc:
8323 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008324 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008325 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008326 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008327 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008328 case llvm::Triple::spir:
8329 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008330 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008331 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008332}