blob: 391eb53d25002f46afa6e114fc4fe9fccf48c69e [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
Yaxun Liu8f66b4b2016-12-09 19:01:11 +0000404llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
405 llvm::PointerType *T, QualType QT) const {
406 return llvm::ConstantPointerNull::get(T);
407}
408
409llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
410 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, QualType SrcTy,
411 QualType DestTy) const {
412 // Since target may map different address spaces in AST to the same address
413 // space, an address space conversion may end up as a bitcast.
414 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src,
415 CGF.ConvertType(DestTy));
416}
417
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000418static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000419
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000420/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000421/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000422static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
423 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000424 if (FD->isUnnamedBitfield())
425 return true;
426
427 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000428
Eli Friedman0b3f2012011-11-18 03:47:20 +0000429 // Constant arrays of empty records count as empty, strip them off.
430 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000431 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000432 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
433 if (AT->getSize() == 0)
434 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000435 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000436 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000437
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000438 const RecordType *RT = FT->getAs<RecordType>();
439 if (!RT)
440 return false;
441
442 // C++ record fields are never empty, at least in the Itanium ABI.
443 //
444 // FIXME: We should use a predicate for whether this behavior is true in the
445 // current ABI.
446 if (isa<CXXRecordDecl>(RT->getDecl()))
447 return false;
448
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000449 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000450}
451
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000452/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000453/// fields. Note that a structure with a flexible array member is not
454/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000455static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000456 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000457 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000458 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000459 const RecordDecl *RD = RT->getDecl();
460 if (RD->hasFlexibleArrayMember())
461 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000462
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000463 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000464 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000465 for (const auto &I : CXXRD->bases())
466 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000467 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000468
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000469 for (const auto *I : RD->fields())
470 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471 return false;
472 return true;
473}
474
475/// isSingleElementStruct - Determine if a structure is a "single
476/// element struct", i.e. it has exactly one non-empty field or
477/// exactly one field which is itself a single element
478/// struct. Structures with flexible array members are never
479/// considered single element structs.
480///
481/// \return The field declaration for the single non-empty field, if
482/// it exists.
483static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000484 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000485 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000486 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000487
488 const RecordDecl *RD = RT->getDecl();
489 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000490 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000491
Craig Topper8a13c412014-05-21 05:09:00 +0000492 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000493
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000494 // If this is a C++ record, check the bases first.
495 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000496 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000497 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000498 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000499 continue;
500
501 // If we already found an element then this isn't a single-element struct.
502 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000503 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000504
505 // If this is non-empty and not a single element struct, the composite
506 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000507 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000508 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000509 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000510 }
511 }
512
513 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000514 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000515 QualType FT = FD->getType();
516
517 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000518 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000519 continue;
520
521 // If we already found an element then this isn't a single-element
522 // struct.
523 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000524 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000525
526 // Treat single element arrays as the element.
527 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
528 if (AT->getSize().getZExtValue() != 1)
529 break;
530 FT = AT->getElementType();
531 }
532
John McCalla1dee5302010-08-22 10:59:02 +0000533 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000534 Found = FT.getTypePtr();
535 } else {
536 Found = isSingleElementStruct(FT, Context);
537 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000538 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000539 }
540 }
541
Eli Friedmanee945342011-11-18 01:25:50 +0000542 // We don't consider a struct a single-element struct if it has
543 // padding beyond the element type.
544 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000545 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000546
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000547 return Found;
548}
549
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000550namespace {
James Y Knight29b5f082016-02-24 02:59:33 +0000551Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
552 const ABIArgInfo &AI) {
553 // This default implementation defers to the llvm backend's va_arg
554 // instruction. It can handle only passing arguments directly
555 // (typically only handled in the backend for primitive types), or
556 // aggregates passed indirectly by pointer (NOTE: if the "byval"
557 // flag has ABI impact in the callee, this implementation cannot
558 // work.)
559
560 // Only a few cases are covered here at the moment -- those needed
561 // by the default abi.
562 llvm::Value *Val;
563
564 if (AI.isIndirect()) {
565 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000566 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000567 assert(
568 !AI.getIndirectRealign() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000569 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000570
571 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
572 CharUnits TyAlignForABI = TyInfo.second;
573
574 llvm::Type *BaseTy =
575 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
576 llvm::Value *Addr =
577 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
578 return Address(Addr, TyAlignForABI);
579 } else {
580 assert((AI.isDirect() || AI.isExtend()) &&
581 "Unexpected ArgInfo Kind in generic VAArg emitter!");
582
583 assert(!AI.getInReg() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000584 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000585 assert(!AI.getPaddingType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000586 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000587 assert(!AI.getDirectOffset() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000588 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000589 assert(!AI.getCoerceToType() &&
Richard Smith81ef0e12016-05-14 01:21:40 +0000590 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
James Y Knight29b5f082016-02-24 02:59:33 +0000591
592 Address Temp = CGF.CreateMemTemp(Ty, "varet");
593 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
594 CGF.Builder.CreateStore(Val, Temp);
595 return Temp;
596 }
597}
598
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000599/// DefaultABIInfo - The default implementation for ABI specific
600/// details. This implementation provides information which results in
601/// self-consistent and sensible LLVM IR generation, but does not
602/// conform to any particular ABI.
603class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000604public:
605 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000606
Chris Lattner458b2aa2010-07-29 02:16:43 +0000607 ABIArgInfo classifyReturnType(QualType RetTy) const;
608 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000609
Craig Topper4f12f102014-03-12 06:41:41 +0000610 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000611 if (!getCXXABI().classifyReturnType(FI))
612 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000613 for (auto &I : FI.arguments())
614 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000615 }
616
John McCall7f416cc2015-09-08 08:05:57 +0000617 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
James Y Knight29b5f082016-02-24 02:59:33 +0000618 QualType Ty) const override {
619 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
620 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000621};
622
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000623class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
624public:
Chris Lattner2b037972010-07-29 02:01:43 +0000625 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
626 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000627};
628
Chris Lattner458b2aa2010-07-29 02:16:43 +0000629ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000630 Ty = useFirstFieldIfTransparentUnion(Ty);
631
632 if (isAggregateTypeForABI(Ty)) {
633 // Records with non-trivial destructors/copy-constructors should not be
634 // passed by value.
635 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000636 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000637
John McCall7f416cc2015-09-08 08:05:57 +0000638 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000639 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000640
Chris Lattner9723d6c2010-03-11 18:19:55 +0000641 // Treat an enum type as its underlying type.
642 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
643 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000644
Chris Lattner9723d6c2010-03-11 18:19:55 +0000645 return (Ty->isPromotableIntegerType() ?
646 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000647}
648
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000649ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
650 if (RetTy->isVoidType())
651 return ABIArgInfo::getIgnore();
652
653 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000654 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000655
656 // Treat an enum type as its underlying type.
657 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
658 RetTy = EnumTy->getDecl()->getIntegerType();
659
660 return (RetTy->isPromotableIntegerType() ?
661 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
662}
663
Derek Schuff09338a22012-09-06 17:37:28 +0000664//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000665// WebAssembly ABI Implementation
666//
667// This is a very simple ABI that relies a lot on DefaultABIInfo.
668//===----------------------------------------------------------------------===//
669
670class WebAssemblyABIInfo final : public DefaultABIInfo {
671public:
672 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
673 : DefaultABIInfo(CGT) {}
674
675private:
676 ABIArgInfo classifyReturnType(QualType RetTy) const;
677 ABIArgInfo classifyArgumentType(QualType Ty) const;
678
679 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
Richard Smith81ef0e12016-05-14 01:21:40 +0000680 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
James Y Knight29b5f082016-02-24 02:59:33 +0000681 // overload them.
Dan Gohmanc2853072015-09-03 22:51:53 +0000682 void computeInfo(CGFunctionInfo &FI) const override {
683 if (!getCXXABI().classifyReturnType(FI))
684 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
685 for (auto &Arg : FI.arguments())
686 Arg.info = classifyArgumentType(Arg.type);
687 }
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000688
689 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
690 QualType Ty) const override;
Dan Gohmanc2853072015-09-03 22:51:53 +0000691};
692
693class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
694public:
695 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
696 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
697};
698
699/// \brief Classify argument of given type \p Ty.
700ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
701 Ty = useFirstFieldIfTransparentUnion(Ty);
702
703 if (isAggregateTypeForABI(Ty)) {
704 // Records with non-trivial destructors/copy-constructors should not be
705 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000706 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000707 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000708 // Ignore empty structs/unions.
709 if (isEmptyRecord(getContext(), Ty, true))
710 return ABIArgInfo::getIgnore();
711 // Lower single-element structs to just pass a regular value. TODO: We
712 // could do reasonable-size multiple-element structs too, using getExpand(),
713 // though watch out for things like bitfields.
714 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
715 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000716 }
717
718 // Otherwise just do the default thing.
719 return DefaultABIInfo::classifyArgumentType(Ty);
720}
721
722ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
723 if (isAggregateTypeForABI(RetTy)) {
724 // Records with non-trivial destructors/copy-constructors should not be
725 // returned by value.
726 if (!getRecordArgABI(RetTy, getCXXABI())) {
727 // Ignore empty structs/unions.
728 if (isEmptyRecord(getContext(), RetTy, true))
729 return ABIArgInfo::getIgnore();
730 // Lower single-element structs to just return a regular value. TODO: We
731 // could do reasonable-size multiple-element structs too, using
732 // ABIArgInfo::getDirect().
733 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
734 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
735 }
736 }
737
738 // Otherwise just do the default thing.
739 return DefaultABIInfo::classifyReturnType(RetTy);
740}
741
Dan Gohman1fcd10c2016-02-22 19:17:40 +0000742Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
743 QualType Ty) const {
744 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
745 getContext().getTypeInfoInChars(Ty),
746 CharUnits::fromQuantity(4),
747 /*AllowHigherAlign=*/ true);
748}
749
Dan Gohmanc2853072015-09-03 22:51:53 +0000750//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000751// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000752//
753// This is a simplified version of the x86_32 ABI. Arguments and return values
754// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000755//===----------------------------------------------------------------------===//
756
757class PNaClABIInfo : public ABIInfo {
758 public:
759 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
760
761 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000762 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000763
Craig Topper4f12f102014-03-12 06:41:41 +0000764 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000765 Address EmitVAArg(CodeGenFunction &CGF,
766 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000767};
768
769class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
770 public:
771 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
772 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
773};
774
775void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000776 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000777 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
778
Reid Kleckner40ca9132014-05-13 22:05:45 +0000779 for (auto &I : FI.arguments())
780 I.info = classifyArgumentType(I.type);
781}
Derek Schuff09338a22012-09-06 17:37:28 +0000782
John McCall7f416cc2015-09-08 08:05:57 +0000783Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
784 QualType Ty) const {
James Y Knight29b5f082016-02-24 02:59:33 +0000785 // The PNaCL ABI is a bit odd, in that varargs don't use normal
786 // function classification. Structs get passed directly for varargs
787 // functions, through a rewriting transform in
788 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
789 // this target to actually support a va_arg instructions with an
790 // aggregate type, unlike other targets.
791 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000792}
793
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000794/// \brief Classify argument of given type \p Ty.
795ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000796 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000797 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000798 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
799 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000800 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
801 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000802 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000803 } else if (Ty->isFloatingType()) {
804 // Floating-point types don't go inreg.
805 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000806 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000807
808 return (Ty->isPromotableIntegerType() ?
809 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000810}
811
812ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
813 if (RetTy->isVoidType())
814 return ABIArgInfo::getIgnore();
815
Eli Benderskye20dad62013-04-04 22:49:35 +0000816 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000817 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000818 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000819
820 // Treat an enum type as its underlying type.
821 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
822 RetTy = EnumTy->getDecl()->getIntegerType();
823
824 return (RetTy->isPromotableIntegerType() ?
825 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
826}
827
Chad Rosier651c1832013-03-25 21:00:27 +0000828/// IsX86_MMXType - Return true if this is an MMX type.
829bool IsX86_MMXType(llvm::Type *IRType) {
830 // 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 +0000831 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
832 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
833 IRType->getScalarSizeInBits() != 64;
834}
835
Jay Foad7c57be32011-07-11 09:56:20 +0000836static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000837 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000838 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000839 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
840 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
841 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000842 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000843 }
844
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000845 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000846 }
847
848 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000849 return Ty;
850}
851
Reid Kleckner80944df2014-10-31 22:00:51 +0000852/// Returns true if this type can be passed in SSE registers with the
853/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
854static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
855 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
856 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
857 return true;
858 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
859 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
860 // registers specially.
861 unsigned VecSize = Context.getTypeSize(VT);
862 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
863 return true;
864 }
865 return false;
866}
867
868/// Returns true if this aggregate is small enough to be passed in SSE registers
869/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
870static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
871 return NumMembers <= 4;
872}
873
Chris Lattner0cf24192010-06-28 20:05:43 +0000874//===----------------------------------------------------------------------===//
875// X86-32 ABI Implementation
876//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000877
Reid Kleckner661f35b2014-01-18 01:12:41 +0000878/// \brief Similar to llvm::CCState, but for Clang.
879struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000880 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000881
882 unsigned CC;
883 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000884 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000885};
886
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000887/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000888class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000889 enum Class {
890 Integer,
891 Float
892 };
893
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000894 static const unsigned MinABIStackAlignInBytes = 4;
895
David Chisnallde3a0692009-08-17 23:08:21 +0000896 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000897 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000898 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000899 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000900 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000901 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000902
903 static bool isRegisterSize(unsigned Size) {
904 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
905 }
906
Reid Kleckner80944df2014-10-31 22:00:51 +0000907 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
908 // FIXME: Assumes vectorcall is in use.
909 return isX86VectorTypeForVectorCall(getContext(), Ty);
910 }
911
912 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
913 uint64_t NumMembers) const override {
914 // FIXME: Assumes vectorcall is in use.
915 return isX86VectorCallAggregateSmallEnough(NumMembers);
916 }
917
Reid Kleckner40ca9132014-05-13 22:05:45 +0000918 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000919
Daniel Dunbar557893d2010-04-21 19:10:51 +0000920 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
921 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000922 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
923
John McCall7f416cc2015-09-08 08:05:57 +0000924 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000925
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000926 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000927 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000928
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000929 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000930 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000931 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000932 /// \brief Updates the number of available free registers, returns
933 /// true if any registers were allocated.
934 bool updateFreeRegs(QualType Ty, CCState &State) const;
935
936 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
937 bool &NeedsPadding) const;
938 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000939
Reid Kleckner04046052016-05-02 17:41:07 +0000940 bool canExpandIndirectArgument(QualType Ty) const;
941
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000942 /// \brief Rewrite the function info so that all memory arguments use
943 /// inalloca.
944 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
945
946 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000947 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000948 QualType Type) const;
949
Rafael Espindola75419dc2012-07-23 23:30:29 +0000950public:
951
Craig Topper4f12f102014-03-12 06:41:41 +0000952 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000953 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
954 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000955
Michael Kupersteindc745202015-10-19 07:52:25 +0000956 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
957 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000958 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000959 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000960 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
961 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000962 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000963 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000964 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000965
966 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
967 ArrayRef<llvm::Type*> scalars,
968 bool asReturnValue) const override {
969 // LLVM's x86-32 lowering currently only assigns up to three
970 // integer registers and three fp registers. Oddly, it'll use up to
971 // four vector registers for vectors, but those can overlap with the
972 // scalar registers.
973 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
974 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +0000975
976 bool isSwiftErrorInRegister() const override {
977 // x86-32 lowering does not support passing swifterror in a register.
978 return false;
979 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000981
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000982class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
983public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000984 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
985 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000986 unsigned NumRegisterParameters, bool SoftFloatABI)
987 : TargetCodeGenInfo(new X86_32ABIInfo(
988 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
989 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000990
John McCall1fe2a8c2013-06-18 02:46:29 +0000991 static bool isStructReturnInRegABI(
992 const llvm::Triple &Triple, const CodeGenOptions &Opts);
993
Eric Christopher162c91c2015-06-05 22:03:00 +0000994 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000995 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000996
Craig Topper4f12f102014-03-12 06:41:41 +0000997 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000998 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000999 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001000 return 4;
1001 }
1002
1003 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001004 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001005
Jay Foad7c57be32011-07-11 09:56:20 +00001006 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001007 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001008 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001009 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1010 }
1011
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001012 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1013 std::string &Constraints,
1014 std::vector<llvm::Type *> &ResultRegTypes,
1015 std::vector<llvm::Type *> &ResultTruncRegTypes,
1016 std::vector<LValue> &ResultRegDests,
1017 std::string &AsmString,
1018 unsigned NumOutputs) const override;
1019
Craig Topper4f12f102014-03-12 06:41:41 +00001020 llvm::Constant *
1021 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001022 unsigned Sig = (0xeb << 0) | // jmp rel8
1023 (0x06 << 8) | // .+0x08
1024 ('F' << 16) |
1025 ('T' << 24);
1026 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1027 }
John McCall01391782016-02-05 21:37:38 +00001028
1029 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1030 return "movl\t%ebp, %ebp"
1031 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1032 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001033};
1034
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001035}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001036
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001037/// Rewrite input constraint references after adding some output constraints.
1038/// In the case where there is one output and one input and we add one output,
1039/// we need to replace all operand references greater than or equal to 1:
1040/// mov $0, $1
1041/// mov eax, $1
1042/// The result will be:
1043/// mov $0, $2
1044/// mov eax, $2
1045static void rewriteInputConstraintReferences(unsigned FirstIn,
1046 unsigned NumNewOuts,
1047 std::string &AsmString) {
1048 std::string Buf;
1049 llvm::raw_string_ostream OS(Buf);
1050 size_t Pos = 0;
1051 while (Pos < AsmString.size()) {
1052 size_t DollarStart = AsmString.find('$', Pos);
1053 if (DollarStart == std::string::npos)
1054 DollarStart = AsmString.size();
1055 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1056 if (DollarEnd == std::string::npos)
1057 DollarEnd = AsmString.size();
1058 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1059 Pos = DollarEnd;
1060 size_t NumDollars = DollarEnd - DollarStart;
1061 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1062 // We have an operand reference.
1063 size_t DigitStart = Pos;
1064 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1065 if (DigitEnd == std::string::npos)
1066 DigitEnd = AsmString.size();
1067 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1068 unsigned OperandIndex;
1069 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1070 if (OperandIndex >= FirstIn)
1071 OperandIndex += NumNewOuts;
1072 OS << OperandIndex;
1073 } else {
1074 OS << OperandStr;
1075 }
1076 Pos = DigitEnd;
1077 }
1078 }
1079 AsmString = std::move(OS.str());
1080}
1081
1082/// Add output constraints for EAX:EDX because they are return registers.
1083void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1084 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1085 std::vector<llvm::Type *> &ResultRegTypes,
1086 std::vector<llvm::Type *> &ResultTruncRegTypes,
1087 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1088 unsigned NumOutputs) const {
1089 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1090
1091 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1092 // larger.
1093 if (!Constraints.empty())
1094 Constraints += ',';
1095 if (RetWidth <= 32) {
1096 Constraints += "={eax}";
1097 ResultRegTypes.push_back(CGF.Int32Ty);
1098 } else {
1099 // Use the 'A' constraint for EAX:EDX.
1100 Constraints += "=A";
1101 ResultRegTypes.push_back(CGF.Int64Ty);
1102 }
1103
1104 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1105 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1106 ResultTruncRegTypes.push_back(CoerceTy);
1107
1108 // Coerce the integer by bitcasting the return slot pointer.
1109 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1110 CoerceTy->getPointerTo()));
1111 ResultRegDests.push_back(ReturnSlot);
1112
1113 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1114}
1115
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001117/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001118bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1119 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001120 uint64_t Size = Context.getTypeSize(Ty);
1121
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001122 // For i386, type must be register sized.
1123 // For the MCU ABI, it only needs to be <= 8-byte
1124 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1125 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001126
1127 if (Ty->isVectorType()) {
1128 // 64- and 128- bit vectors inside structures are not returned in
1129 // registers.
1130 if (Size == 64 || Size == 128)
1131 return false;
1132
1133 return true;
1134 }
1135
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001136 // If this is a builtin, pointer, enum, complex type, member pointer, or
1137 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001138 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001139 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001140 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001141 return true;
1142
1143 // Arrays are treated like records.
1144 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001145 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001146
1147 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001148 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001149 if (!RT) return false;
1150
Anders Carlsson40446e82010-01-27 03:25:19 +00001151 // FIXME: Traverse bases here too.
1152
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001153 // Structure types are passed in register if all fields would be
1154 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001155 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001156 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001157 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001158 continue;
1159
1160 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001161 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001162 return false;
1163 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001164 return true;
1165}
1166
Reid Kleckner04046052016-05-02 17:41:07 +00001167static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1168 // Treat complex types as the element type.
1169 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1170 Ty = CTy->getElementType();
1171
1172 // Check for a type which we know has a simple scalar argument-passing
1173 // convention without any padding. (We're specifically looking for 32
1174 // and 64-bit integer and integer-equivalents, float, and double.)
1175 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1176 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1177 return false;
1178
1179 uint64_t Size = Context.getTypeSize(Ty);
1180 return Size == 32 || Size == 64;
1181}
1182
1183/// Test whether an argument type which is to be passed indirectly (on the
1184/// stack) would have the equivalent layout if it was expanded into separate
1185/// arguments. If so, we prefer to do the latter to avoid inhibiting
1186/// optimizations.
1187bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1188 // We can only expand structure types.
1189 const RecordType *RT = Ty->getAs<RecordType>();
1190 if (!RT)
1191 return false;
1192 const RecordDecl *RD = RT->getDecl();
1193 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1194 if (!IsWin32StructABI ) {
1195 // On non-Windows, we have to conservatively match our old bitcode
1196 // prototypes in order to be ABI-compatible at the bitcode level.
1197 if (!CXXRD->isCLike())
1198 return false;
1199 } else {
1200 // Don't do this for dynamic classes.
1201 if (CXXRD->isDynamicClass())
1202 return false;
1203 // Don't do this if there are any non-empty bases.
1204 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
1205 if (!isEmptyRecord(getContext(), Base.getType(), /*AllowArrays=*/true))
1206 return false;
1207 }
1208 }
1209 }
1210
1211 uint64_t Size = 0;
1212
1213 for (const auto *FD : RD->fields()) {
1214 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1215 // argument is smaller than 32-bits, expanding the struct will create
1216 // alignment padding.
1217 if (!is32Or64BitBasicType(FD->getType(), getContext()))
1218 return false;
1219
1220 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1221 // how to expand them yet, and the predicate for telling if a bitfield still
1222 // counts as "basic" is more complicated than what we were doing previously.
1223 if (FD->isBitField())
1224 return false;
1225
1226 Size += getContext().getTypeSize(FD->getType());
1227 }
1228
1229 // We can do this if there was no alignment padding.
1230 return Size == getContext().getTypeSize(Ty);
1231}
1232
John McCall7f416cc2015-09-08 08:05:57 +00001233ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001234 // If the return value is indirect, then the hidden argument is consuming one
1235 // integer register.
1236 if (State.FreeRegs) {
1237 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001238 if (!IsMCUABI)
1239 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001240 }
John McCall7f416cc2015-09-08 08:05:57 +00001241 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001242}
1243
Eric Christopher7565e0d2015-05-29 23:09:49 +00001244ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1245 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001246 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001247 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001248
Reid Kleckner80944df2014-10-31 22:00:51 +00001249 const Type *Base = nullptr;
1250 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001251 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1252 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001253 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1254 // The LLVM struct type for such an aggregate should lower properly.
1255 return ABIArgInfo::getDirect();
1256 }
1257
Chris Lattner458b2aa2010-07-29 02:16:43 +00001258 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001259 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001260 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001261 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001262
1263 // 128-bit vectors are a special case; they are returned in
1264 // registers and we need to make sure to pick a type the LLVM
1265 // backend will like.
1266 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001267 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001268 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001269
1270 // Always return in register if it fits in a general purpose
1271 // register, or if it is 64 bits and has a single element.
1272 if ((Size == 8 || Size == 16 || Size == 32) ||
1273 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001274 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001275 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001276
John McCall7f416cc2015-09-08 08:05:57 +00001277 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001278 }
1279
1280 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001281 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001282
John McCalla1dee5302010-08-22 10:59:02 +00001283 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001284 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001285 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001286 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001287 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001288 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001289
David Chisnallde3a0692009-08-17 23:08:21 +00001290 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001291 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001292 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001293
Denis Zobnin380b2242016-02-11 11:26:03 +00001294 // Ignore empty structs/unions.
1295 if (isEmptyRecord(getContext(), RetTy, true))
1296 return ABIArgInfo::getIgnore();
1297
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001298 // Small structures which are register sized are generally returned
1299 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001300 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001301 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001302
1303 // As a special-case, if the struct is a "single-element" struct, and
1304 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001305 // floating-point register. (MSVC does not apply this special case.)
1306 // We apply a similar transformation for pointer types to improve the
1307 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001308 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001309 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001310 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001311 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1312
1313 // FIXME: We should be able to narrow this integer in cases with dead
1314 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001315 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001316 }
1317
John McCall7f416cc2015-09-08 08:05:57 +00001318 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001319 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001320
Chris Lattner458b2aa2010-07-29 02:16:43 +00001321 // Treat an enum type as its underlying type.
1322 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1323 RetTy = EnumTy->getDecl()->getIntegerType();
1324
1325 return (RetTy->isPromotableIntegerType() ?
1326 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001327}
1328
Eli Friedman7919bea2012-06-05 19:40:46 +00001329static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1330 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1331}
1332
Daniel Dunbared23de32010-09-16 20:42:00 +00001333static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1334 const RecordType *RT = Ty->getAs<RecordType>();
1335 if (!RT)
1336 return 0;
1337 const RecordDecl *RD = RT->getDecl();
1338
1339 // If this is a C++ record, check the bases first.
1340 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001341 for (const auto &I : CXXRD->bases())
1342 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001343 return false;
1344
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001345 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001346 QualType FT = i->getType();
1347
Eli Friedman7919bea2012-06-05 19:40:46 +00001348 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001349 return true;
1350
1351 if (isRecordWithSSEVectorType(Context, FT))
1352 return true;
1353 }
1354
1355 return false;
1356}
1357
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001358unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1359 unsigned Align) const {
1360 // Otherwise, if the alignment is less than or equal to the minimum ABI
1361 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001362 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001363 return 0; // Use default alignment.
1364
1365 // On non-Darwin, the stack type alignment is always 4.
1366 if (!IsDarwinVectorABI) {
1367 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001368 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001369 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001370
Daniel Dunbared23de32010-09-16 20:42:00 +00001371 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001372 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1373 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001374 return 16;
1375
1376 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001377}
1378
Rafael Espindola703c47f2012-10-19 05:04:37 +00001379ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001380 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001381 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001382 if (State.FreeRegs) {
1383 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001384 if (!IsMCUABI)
1385 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001386 }
John McCall7f416cc2015-09-08 08:05:57 +00001387 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001388 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001389
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001390 // Compute the byval alignment.
1391 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1392 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1393 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001394 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001395
1396 // If the stack alignment is less than the type alignment, realign the
1397 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001398 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001399 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1400 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001401}
1402
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001403X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1404 const Type *T = isSingleElementStruct(Ty, getContext());
1405 if (!T)
1406 T = Ty.getTypePtr();
1407
1408 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1409 BuiltinType::Kind K = BT->getKind();
1410 if (K == BuiltinType::Float || K == BuiltinType::Double)
1411 return Float;
1412 }
1413 return Integer;
1414}
1415
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001416bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001417 if (!IsSoftFloatABI) {
1418 Class C = classify(Ty);
1419 if (C == Float)
1420 return false;
1421 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001422
Rafael Espindola077dd592012-10-24 01:58:58 +00001423 unsigned Size = getContext().getTypeSize(Ty);
1424 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001425
1426 if (SizeInRegs == 0)
1427 return false;
1428
Michael Kuperstein68901882015-10-25 08:18:20 +00001429 if (!IsMCUABI) {
1430 if (SizeInRegs > State.FreeRegs) {
1431 State.FreeRegs = 0;
1432 return false;
1433 }
1434 } else {
1435 // The MCU psABI allows passing parameters in-reg even if there are
1436 // earlier parameters that are passed on the stack. Also,
1437 // it does not allow passing >8-byte structs in-register,
1438 // even if there are 3 free registers available.
1439 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1440 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001441 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001442
Reid Kleckner661f35b2014-01-18 01:12:41 +00001443 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001444 return true;
1445}
1446
1447bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1448 bool &InReg,
1449 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001450 // On Windows, aggregates other than HFAs are never passed in registers, and
1451 // they do not consume register slots. Homogenous floating-point aggregates
1452 // (HFAs) have already been dealt with at this point.
1453 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1454 return false;
1455
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001456 NeedsPadding = false;
1457 InReg = !IsMCUABI;
1458
1459 if (!updateFreeRegs(Ty, State))
1460 return false;
1461
1462 if (IsMCUABI)
1463 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001464
Reid Kleckner80944df2014-10-31 22:00:51 +00001465 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001466 State.CC == llvm::CallingConv::X86_VectorCall ||
1467 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001468 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001469 NeedsPadding = true;
1470
Rafael Espindola077dd592012-10-24 01:58:58 +00001471 return false;
1472 }
1473
Rafael Espindola703c47f2012-10-19 05:04:37 +00001474 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001475}
1476
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001477bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1478 if (!updateFreeRegs(Ty, State))
1479 return false;
1480
1481 if (IsMCUABI)
1482 return false;
1483
1484 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001485 State.CC == llvm::CallingConv::X86_VectorCall ||
1486 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001487 if (getContext().getTypeSize(Ty) > 32)
1488 return false;
1489
1490 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1491 Ty->isReferenceType());
1492 }
1493
1494 return true;
1495}
1496
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001497ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1498 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001499 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001500
Reid Klecknerb1be6832014-11-15 01:41:41 +00001501 Ty = useFirstFieldIfTransparentUnion(Ty);
1502
Reid Kleckner80944df2014-10-31 22:00:51 +00001503 // Check with the C++ ABI first.
1504 const RecordType *RT = Ty->getAs<RecordType>();
1505 if (RT) {
1506 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1507 if (RAA == CGCXXABI::RAA_Indirect) {
1508 return getIndirectResult(Ty, false, State);
1509 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1510 // The field index doesn't matter, we'll fix it up later.
1511 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1512 }
1513 }
1514
1515 // vectorcall adds the concept of a homogenous vector aggregate, similar
1516 // to other targets.
1517 const Type *Base = nullptr;
1518 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001519 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1520 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001521 isHomogeneousAggregate(Ty, Base, NumElts)) {
1522 if (State.FreeSSERegs >= NumElts) {
1523 State.FreeSSERegs -= NumElts;
1524 if (Ty->isBuiltinType() || Ty->isVectorType())
1525 return ABIArgInfo::getDirect();
1526 return ABIArgInfo::getExpand();
1527 }
1528 return getIndirectResult(Ty, /*ByVal=*/false, State);
1529 }
1530
1531 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001532 // Structures with flexible arrays are always indirect.
1533 // FIXME: This should not be byval!
1534 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1535 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001536
Reid Kleckner04046052016-05-02 17:41:07 +00001537 // Ignore empty structs/unions on non-Windows.
1538 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001539 return ABIArgInfo::getIgnore();
1540
Rafael Espindolafad28de2012-10-24 01:59:00 +00001541 llvm::LLVMContext &LLVMContext = getVMContext();
1542 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001543 bool NeedsPadding = false;
1544 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001545 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001546 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001547 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001548 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001549 if (InReg)
1550 return ABIArgInfo::getDirectInReg(Result);
1551 else
1552 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001553 }
Craig Topper8a13c412014-05-21 05:09:00 +00001554 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001555
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001556 // Expand small (<= 128-bit) record types when we know that the stack layout
1557 // of those arguments will match the struct. This is important because the
1558 // LLVM backend isn't smart enough to remove byval, which inhibits many
1559 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001560 // Don't do this for the MCU if there are still free integer registers
1561 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001562 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1563 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001564 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001565 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001566 State.CC == llvm::CallingConv::X86_VectorCall ||
1567 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001568 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001569
Reid Kleckner661f35b2014-01-18 01:12:41 +00001570 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001571 }
1572
Chris Lattnerd774ae92010-08-26 20:05:13 +00001573 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001574 // On Darwin, some vectors are passed in memory, we handle this by passing
1575 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001576 if (IsDarwinVectorABI) {
1577 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001578 if ((Size == 8 || Size == 16 || Size == 32) ||
1579 (Size == 64 && VT->getNumElements() == 1))
1580 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1581 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001582 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001583
Chad Rosier651c1832013-03-25 21:00:27 +00001584 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1585 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001586
Chris Lattnerd774ae92010-08-26 20:05:13 +00001587 return ABIArgInfo::getDirect();
1588 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001589
1590
Chris Lattner458b2aa2010-07-29 02:16:43 +00001591 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1592 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001593
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001594 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001595
1596 if (Ty->isPromotableIntegerType()) {
1597 if (InReg)
1598 return ABIArgInfo::getExtendInReg();
1599 return ABIArgInfo::getExtend();
1600 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001601
Rafael Espindola703c47f2012-10-19 05:04:37 +00001602 if (InReg)
1603 return ABIArgInfo::getDirectInReg();
1604 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001605}
1606
Rafael Espindolaa6472962012-07-24 00:01:07 +00001607void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001608 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001609 if (IsMCUABI)
1610 State.FreeRegs = 3;
1611 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001612 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001613 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1614 State.FreeRegs = 2;
1615 State.FreeSSERegs = 6;
1616 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001617 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001618 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1619 State.FreeRegs = 5;
1620 State.FreeSSERegs = 8;
1621 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001622 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001623
Reid Kleckner677539d2014-07-10 01:58:55 +00001624 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001625 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001626 } else if (FI.getReturnInfo().isIndirect()) {
1627 // The C++ ABI is not aware of register usage, so we have to check if the
1628 // return value was sret and put it in a register ourselves if appropriate.
1629 if (State.FreeRegs) {
1630 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001631 if (!IsMCUABI)
1632 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001633 }
1634 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001635
Peter Collingbournef7706832014-12-12 23:41:25 +00001636 // The chain argument effectively gives us another free register.
1637 if (FI.isChainCall())
1638 ++State.FreeRegs;
1639
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001640 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001641 for (auto &I : FI.arguments()) {
1642 I.info = classifyArgumentType(I.type, State);
1643 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001644 }
1645
1646 // If we needed to use inalloca for any argument, do a second pass and rewrite
1647 // all the memory arguments to use inalloca.
1648 if (UsedInAlloca)
1649 rewriteWithInAlloca(FI);
1650}
1651
1652void
1653X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001654 CharUnits &StackOffset, ABIArgInfo &Info,
1655 QualType Type) const {
1656 // Arguments are always 4-byte-aligned.
1657 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1658
1659 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001660 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1661 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001662 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001663
John McCall7f416cc2015-09-08 08:05:57 +00001664 // Insert padding bytes to respect alignment.
1665 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001666 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001667 if (StackOffset != FieldEnd) {
1668 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001669 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001670 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001671 FrameFields.push_back(Ty);
1672 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001673}
1674
Reid Kleckner852361d2014-07-26 00:12:26 +00001675static bool isArgInAlloca(const ABIArgInfo &Info) {
1676 // Leave ignored and inreg arguments alone.
1677 switch (Info.getKind()) {
1678 case ABIArgInfo::InAlloca:
1679 return true;
1680 case ABIArgInfo::Indirect:
1681 assert(Info.getIndirectByVal());
1682 return true;
1683 case ABIArgInfo::Ignore:
1684 return false;
1685 case ABIArgInfo::Direct:
1686 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001687 if (Info.getInReg())
1688 return false;
1689 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001690 case ABIArgInfo::Expand:
1691 case ABIArgInfo::CoerceAndExpand:
1692 // These are aggregate types which are never passed in registers when
1693 // inalloca is involved.
1694 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001695 }
1696 llvm_unreachable("invalid enum");
1697}
1698
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001699void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1700 assert(IsWin32StructABI && "inalloca only supported on win32");
1701
1702 // Build a packed struct type for all of the arguments in memory.
1703 SmallVector<llvm::Type *, 6> FrameFields;
1704
John McCall7f416cc2015-09-08 08:05:57 +00001705 // The stack alignment is always 4.
1706 CharUnits StackAlign = CharUnits::fromQuantity(4);
1707
1708 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001709 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1710
1711 // Put 'this' into the struct before 'sret', if necessary.
1712 bool IsThisCall =
1713 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1714 ABIArgInfo &Ret = FI.getReturnInfo();
1715 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1716 isArgInAlloca(I->info)) {
1717 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1718 ++I;
1719 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001720
1721 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001722 if (Ret.isIndirect() && !Ret.getInReg()) {
1723 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1724 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001725 // On Windows, the hidden sret parameter is always returned in eax.
1726 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001727 }
1728
1729 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001730 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001731 ++I;
1732
1733 // Put arguments passed in memory into the struct.
1734 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001735 if (isArgInAlloca(I->info))
1736 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001737 }
1738
1739 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001740 /*isPacked=*/true),
1741 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001742}
1743
John McCall7f416cc2015-09-08 08:05:57 +00001744Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1745 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001746
John McCall7f416cc2015-09-08 08:05:57 +00001747 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001748
John McCall7f416cc2015-09-08 08:05:57 +00001749 // x86-32 changes the alignment of certain arguments on the stack.
1750 //
1751 // Just messing with TypeInfo like this works because we never pass
1752 // anything indirectly.
1753 TypeInfo.second = CharUnits::fromQuantity(
1754 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001755
John McCall7f416cc2015-09-08 08:05:57 +00001756 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1757 TypeInfo, CharUnits::fromQuantity(4),
1758 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001759}
1760
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001761bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1762 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1763 assert(Triple.getArch() == llvm::Triple::x86);
1764
1765 switch (Opts.getStructReturnConvention()) {
1766 case CodeGenOptions::SRCK_Default:
1767 break;
1768 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1769 return false;
1770 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1771 return true;
1772 }
1773
Michael Kupersteind749f232015-10-27 07:46:22 +00001774 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001775 return true;
1776
1777 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001778 case llvm::Triple::DragonFly:
1779 case llvm::Triple::FreeBSD:
1780 case llvm::Triple::OpenBSD:
1781 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001782 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001783 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001784 default:
1785 return false;
1786 }
1787}
1788
Eric Christopher162c91c2015-06-05 22:03:00 +00001789void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001790 llvm::GlobalValue *GV,
1791 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001792 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001793 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1794 // Get the LLVM function.
1795 llvm::Function *Fn = cast<llvm::Function>(GV);
1796
1797 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001798 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001799 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001800 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1801 llvm::AttributeSet::get(CGM.getLLVMContext(),
1802 llvm::AttributeSet::FunctionIndex,
1803 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001804 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001805 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1806 llvm::Function *Fn = cast<llvm::Function>(GV);
1807 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1808 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001809 }
1810}
1811
John McCallbeec5a02010-03-06 00:35:14 +00001812bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1813 CodeGen::CodeGenFunction &CGF,
1814 llvm::Value *Address) const {
1815 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001816
Chris Lattnerece04092012-02-07 00:39:47 +00001817 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001818
John McCallbeec5a02010-03-06 00:35:14 +00001819 // 0-7 are the eight integer registers; the order is different
1820 // on Darwin (for EH), but the range is the same.
1821 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001822 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001823
John McCallc8e01702013-04-16 22:48:15 +00001824 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001825 // 12-16 are st(0..4). Not sure why we stop at 4.
1826 // These have size 16, which is sizeof(long double) on
1827 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001828 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001829 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001830
John McCallbeec5a02010-03-06 00:35:14 +00001831 } else {
1832 // 9 is %eflags, which doesn't get a size on Darwin for some
1833 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001834 Builder.CreateAlignedStore(
1835 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1836 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001837
1838 // 11-16 are st(0..5). Not sure why we stop at 5.
1839 // These have size 12, which is sizeof(long double) on
1840 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001841 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001842 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1843 }
John McCallbeec5a02010-03-06 00:35:14 +00001844
1845 return false;
1846}
1847
Chris Lattner0cf24192010-06-28 20:05:43 +00001848//===----------------------------------------------------------------------===//
1849// X86-64 ABI Implementation
1850//===----------------------------------------------------------------------===//
1851
1852
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001853namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001854/// The AVX ABI level for X86 targets.
1855enum class X86AVXABILevel {
1856 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001857 AVX,
1858 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001859};
1860
1861/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1862static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1863 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001864 case X86AVXABILevel::AVX512:
1865 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001866 case X86AVXABILevel::AVX:
1867 return 256;
1868 case X86AVXABILevel::None:
1869 return 128;
1870 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001871 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001872}
1873
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001874/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001875class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001876 enum Class {
1877 Integer = 0,
1878 SSE,
1879 SSEUp,
1880 X87,
1881 X87Up,
1882 ComplexX87,
1883 NoClass,
1884 Memory
1885 };
1886
1887 /// merge - Implement the X86_64 ABI merging algorithm.
1888 ///
1889 /// Merge an accumulating classification \arg Accum with a field
1890 /// classification \arg Field.
1891 ///
1892 /// \param Accum - The accumulating classification. This should
1893 /// always be either NoClass or the result of a previous merge
1894 /// call. In addition, this should never be Memory (the caller
1895 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001896 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001897
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001898 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1899 ///
1900 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1901 /// final MEMORY or SSE classes when necessary.
1902 ///
1903 /// \param AggregateSize - The size of the current aggregate in
1904 /// the classification process.
1905 ///
1906 /// \param Lo - The classification for the parts of the type
1907 /// residing in the low word of the containing object.
1908 ///
1909 /// \param Hi - The classification for the parts of the type
1910 /// residing in the higher words of the containing object.
1911 ///
1912 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1913
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001914 /// classify - Determine the x86_64 register classes in which the
1915 /// given type T should be passed.
1916 ///
1917 /// \param Lo - The classification for the parts of the type
1918 /// residing in the low word of the containing object.
1919 ///
1920 /// \param Hi - The classification for the parts of the type
1921 /// residing in the high word of the containing object.
1922 ///
1923 /// \param OffsetBase - The bit offset of this type in the
1924 /// containing object. Some parameters are classified different
1925 /// depending on whether they straddle an eightbyte boundary.
1926 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001927 /// \param isNamedArg - Whether the argument in question is a "named"
1928 /// argument, as used in AMD64-ABI 3.5.7.
1929 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001930 /// If a word is unused its result will be NoClass; if a type should
1931 /// be passed in Memory then at least the classification of \arg Lo
1932 /// will be Memory.
1933 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001934 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001935 ///
1936 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1937 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001938 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1939 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001940
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001941 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001942 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1943 unsigned IROffset, QualType SourceTy,
1944 unsigned SourceOffset) const;
1945 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1946 unsigned IROffset, QualType SourceTy,
1947 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001948
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001949 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001950 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001951 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001952
1953 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001954 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001955 ///
1956 /// \param freeIntRegs - The number of free integer registers remaining
1957 /// available.
1958 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001959
Chris Lattner458b2aa2010-07-29 02:16:43 +00001960 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001961
Erich Keane757d3172016-11-02 18:29:35 +00001962 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
1963 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00001964 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001965
Erich Keane757d3172016-11-02 18:29:35 +00001966 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
1967 unsigned &NeededSSE) const;
1968
1969 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
1970 unsigned &NeededSSE) const;
1971
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001972 bool IsIllegalVectorType(QualType Ty) const;
1973
John McCalle0fda732011-04-21 01:20:55 +00001974 /// The 0.98 ABI revision clarified a lot of ambiguities,
1975 /// unfortunately in ways that were not always consistent with
1976 /// certain previous compilers. In particular, platforms which
1977 /// required strict binary compatibility with older versions of GCC
1978 /// may need to exempt themselves.
1979 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001980 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001981 }
1982
David Majnemere2ae2282016-03-04 05:26:16 +00001983 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
1984 // compilers require us to classify it as INTEGER.
1985 bool classifyIntegerMMXAsSSE() const {
1986 const llvm::Triple &Triple = getTarget().getTriple();
1987 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
1988 return false;
1989 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
1990 return false;
1991 return true;
1992 }
1993
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001994 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001995 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1996 // 64-bit hardware.
1997 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001998
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001999public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002000 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002001 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002002 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002003 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002004
John McCalla729c622012-02-17 03:33:10 +00002005 bool isPassedUsingAVXType(QualType type) const {
2006 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002007 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002008 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2009 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002010 if (info.isDirect()) {
2011 llvm::Type *ty = info.getCoerceToType();
2012 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2013 return (vectorTy->getBitWidth() > 128);
2014 }
2015 return false;
2016 }
2017
Craig Topper4f12f102014-03-12 06:41:41 +00002018 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002019
John McCall7f416cc2015-09-08 08:05:57 +00002020 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2021 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002022 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2023 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002024
2025 bool has64BitPointers() const {
2026 return Has64BitPointers;
2027 }
John McCall12f23522016-04-04 18:33:08 +00002028
2029 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2030 ArrayRef<llvm::Type*> scalars,
2031 bool asReturnValue) const override {
2032 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2033 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002034 bool isSwiftErrorInRegister() const override {
2035 return true;
2036 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002037};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002038
Chris Lattner04dc9572010-08-31 16:44:54 +00002039/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002040class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002041public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002042 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002043 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002044 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002045
Craig Topper4f12f102014-03-12 06:41:41 +00002046 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002047
John McCall7f416cc2015-09-08 08:05:57 +00002048 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2049 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002050
2051 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2052 // FIXME: Assumes vectorcall is in use.
2053 return isX86VectorTypeForVectorCall(getContext(), Ty);
2054 }
2055
2056 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2057 uint64_t NumMembers) const override {
2058 // FIXME: Assumes vectorcall is in use.
2059 return isX86VectorCallAggregateSmallEnough(NumMembers);
2060 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002061
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002062 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2063 ArrayRef<llvm::Type *> scalars,
2064 bool asReturnValue) const override {
2065 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2066 }
2067
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002068 bool isSwiftErrorInRegister() const override {
2069 return true;
2070 }
2071
Reid Kleckner11a17192015-10-28 22:29:52 +00002072private:
2073 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
2074 bool IsReturnType) const;
2075
2076 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002077};
2078
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002079class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2080public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002081 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002082 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002083
John McCalla729c622012-02-17 03:33:10 +00002084 const X86_64ABIInfo &getABIInfo() const {
2085 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2086 }
2087
Craig Topper4f12f102014-03-12 06:41:41 +00002088 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002089 return 7;
2090 }
2091
2092 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002093 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002094 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002095
John McCall943fae92010-05-27 06:19:26 +00002096 // 0-15 are the 16 integer registers.
2097 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002098 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002099 return false;
2100 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002101
Jay Foad7c57be32011-07-11 09:56:20 +00002102 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002103 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002104 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002105 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2106 }
2107
John McCalla729c622012-02-17 03:33:10 +00002108 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002109 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002110 // The default CC on x86-64 sets %al to the number of SSA
2111 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002112 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002113 // that when AVX types are involved: the ABI explicitly states it is
2114 // undefined, and it doesn't work in practice because of how the ABI
2115 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002116 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002117 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002118 for (CallArgList::const_iterator
2119 it = args.begin(), ie = args.end(); it != ie; ++it) {
2120 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2121 HasAVXType = true;
2122 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002123 }
2124 }
John McCalla729c622012-02-17 03:33:10 +00002125
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002126 if (!HasAVXType)
2127 return true;
2128 }
John McCallcbc038a2011-09-21 08:08:30 +00002129
John McCalla729c622012-02-17 03:33:10 +00002130 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002131 }
2132
Craig Topper4f12f102014-03-12 06:41:41 +00002133 llvm::Constant *
2134 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002135 unsigned Sig;
2136 if (getABIInfo().has64BitPointers())
2137 Sig = (0xeb << 0) | // jmp rel8
2138 (0x0a << 8) | // .+0x0c
2139 ('F' << 16) |
2140 ('T' << 24);
2141 else
2142 Sig = (0xeb << 0) | // jmp rel8
2143 (0x06 << 8) | // .+0x08
2144 ('F' << 16) |
2145 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002146 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2147 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002148
2149 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2150 CodeGen::CodeGenModule &CGM) const override {
2151 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2152 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2153 llvm::Function *Fn = cast<llvm::Function>(GV);
2154 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2155 }
2156 }
2157 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002158};
2159
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002160class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2161public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002162 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2163 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002164
2165 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002166 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002167 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002168 // If the argument contains a space, enclose it in quotes.
2169 if (Lib.find(" ") != StringRef::npos)
2170 Opt += "\"" + Lib.str() + "\"";
2171 else
2172 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002173 }
2174};
2175
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002176static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002177 // If the argument does not end in .lib, automatically add the suffix.
2178 // If the argument contains a space, enclose it in quotes.
2179 // This matches the behavior of MSVC.
2180 bool Quote = (Lib.find(" ") != StringRef::npos);
2181 std::string ArgStr = Quote ? "\"" : "";
2182 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002183 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002184 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002185 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002186 return ArgStr;
2187}
2188
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002189class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2190public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002191 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002192 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2193 unsigned NumRegisterParameters)
2194 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002195 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002196
Eric Christopher162c91c2015-06-05 22:03:00 +00002197 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002198 CodeGen::CodeGenModule &CGM) const override;
2199
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002200 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002201 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002202 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002203 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002204 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002205
2206 void getDetectMismatchOption(llvm::StringRef Name,
2207 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002208 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002209 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002210 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002211};
2212
Hans Wennborg77dc2362015-01-20 19:45:50 +00002213static void addStackProbeSizeTargetAttribute(const Decl *D,
2214 llvm::GlobalValue *GV,
2215 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002216 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002217 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2218 llvm::Function *Fn = cast<llvm::Function>(GV);
2219
Eric Christopher7565e0d2015-05-29 23:09:49 +00002220 Fn->addFnAttr("stack-probe-size",
2221 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002222 }
2223 }
2224}
2225
Eric Christopher162c91c2015-06-05 22:03:00 +00002226void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002227 llvm::GlobalValue *GV,
2228 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002229 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002230
2231 addStackProbeSizeTargetAttribute(D, GV, CGM);
2232}
2233
Chris Lattner04dc9572010-08-31 16:44:54 +00002234class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2235public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002236 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2237 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002238 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002239
Eric Christopher162c91c2015-06-05 22:03:00 +00002240 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002241 CodeGen::CodeGenModule &CGM) const override;
2242
Craig Topper4f12f102014-03-12 06:41:41 +00002243 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002244 return 7;
2245 }
2246
2247 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002248 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002249 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002250
Chris Lattner04dc9572010-08-31 16:44:54 +00002251 // 0-15 are the 16 integer registers.
2252 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002253 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002254 return false;
2255 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002256
2257 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002258 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002259 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002260 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002261 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002262
2263 void getDetectMismatchOption(llvm::StringRef Name,
2264 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002265 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002266 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002267 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002268};
2269
Eric Christopher162c91c2015-06-05 22:03:00 +00002270void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002271 llvm::GlobalValue *GV,
2272 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002273 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002274
Alexey Bataevd51e9932016-01-15 04:06:31 +00002275 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2276 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2277 llvm::Function *Fn = cast<llvm::Function>(GV);
2278 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2279 }
2280 }
2281
Hans Wennborg77dc2362015-01-20 19:45:50 +00002282 addStackProbeSizeTargetAttribute(D, GV, CGM);
2283}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002284}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002285
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002286void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2287 Class &Hi) const {
2288 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2289 //
2290 // (a) If one of the classes is Memory, the whole argument is passed in
2291 // memory.
2292 //
2293 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2294 // memory.
2295 //
2296 // (c) If the size of the aggregate exceeds two eightbytes and the first
2297 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2298 // argument is passed in memory. NOTE: This is necessary to keep the
2299 // ABI working for processors that don't support the __m256 type.
2300 //
2301 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2302 //
2303 // Some of these are enforced by the merging logic. Others can arise
2304 // only with unions; for example:
2305 // union { _Complex double; unsigned; }
2306 //
2307 // Note that clauses (b) and (c) were added in 0.98.
2308 //
2309 if (Hi == Memory)
2310 Lo = Memory;
2311 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2312 Lo = Memory;
2313 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2314 Lo = Memory;
2315 if (Hi == SSEUp && Lo != SSE)
2316 Hi = SSE;
2317}
2318
Chris Lattnerd776fb12010-06-28 21:43:59 +00002319X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002320 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2321 // classified recursively so that always two fields are
2322 // considered. The resulting class is calculated according to
2323 // the classes of the fields in the eightbyte:
2324 //
2325 // (a) If both classes are equal, this is the resulting class.
2326 //
2327 // (b) If one of the classes is NO_CLASS, the resulting class is
2328 // the other class.
2329 //
2330 // (c) If one of the classes is MEMORY, the result is the MEMORY
2331 // class.
2332 //
2333 // (d) If one of the classes is INTEGER, the result is the
2334 // INTEGER.
2335 //
2336 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2337 // MEMORY is used as class.
2338 //
2339 // (f) Otherwise class SSE is used.
2340
2341 // Accum should never be memory (we should have returned) or
2342 // ComplexX87 (because this cannot be passed in a structure).
2343 assert((Accum != Memory && Accum != ComplexX87) &&
2344 "Invalid accumulated classification during merge.");
2345 if (Accum == Field || Field == NoClass)
2346 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002347 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002348 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002349 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002350 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002351 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002352 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002353 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2354 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002355 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002356 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002357}
2358
Chris Lattner5c740f12010-06-30 19:14:05 +00002359void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002360 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002361 // FIXME: This code can be simplified by introducing a simple value class for
2362 // Class pairs with appropriate constructor methods for the various
2363 // situations.
2364
2365 // FIXME: Some of the split computations are wrong; unaligned vectors
2366 // shouldn't be passed in registers for example, so there is no chance they
2367 // can straddle an eightbyte. Verify & simplify.
2368
2369 Lo = Hi = NoClass;
2370
2371 Class &Current = OffsetBase < 64 ? Lo : Hi;
2372 Current = Memory;
2373
John McCall9dd450b2009-09-21 23:43:11 +00002374 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002375 BuiltinType::Kind k = BT->getKind();
2376
2377 if (k == BuiltinType::Void) {
2378 Current = NoClass;
2379 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2380 Lo = Integer;
2381 Hi = Integer;
2382 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2383 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002384 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002385 Current = SSE;
2386 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002387 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002388 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002389 Lo = SSE;
2390 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002391 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002392 Lo = X87;
2393 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002394 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002395 Current = SSE;
2396 } else
2397 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002398 }
2399 // FIXME: _Decimal32 and _Decimal64 are SSE.
2400 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002401 return;
2402 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002403
Chris Lattnerd776fb12010-06-28 21:43:59 +00002404 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002405 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002406 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002407 return;
2408 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002409
Chris Lattnerd776fb12010-06-28 21:43:59 +00002410 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002411 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002412 return;
2413 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002414
Chris Lattnerd776fb12010-06-28 21:43:59 +00002415 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002416 if (Ty->isMemberFunctionPointerType()) {
2417 if (Has64BitPointers) {
2418 // If Has64BitPointers, this is an {i64, i64}, so classify both
2419 // Lo and Hi now.
2420 Lo = Hi = Integer;
2421 } else {
2422 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2423 // straddles an eightbyte boundary, Hi should be classified as well.
2424 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2425 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2426 if (EB_FuncPtr != EB_ThisAdj) {
2427 Lo = Hi = Integer;
2428 } else {
2429 Current = Integer;
2430 }
2431 }
2432 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002433 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002434 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002435 return;
2436 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002437
Chris Lattnerd776fb12010-06-28 21:43:59 +00002438 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002439 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002440 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2441 // gcc passes the following as integer:
2442 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2443 // 2 bytes - <2 x char>, <1 x short>
2444 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002445 Current = Integer;
2446
2447 // If this type crosses an eightbyte boundary, it should be
2448 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002449 uint64_t EB_Lo = (OffsetBase) / 64;
2450 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2451 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002452 Hi = Lo;
2453 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002454 QualType ElementType = VT->getElementType();
2455
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002456 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002457 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002458 return;
2459
David Majnemere2ae2282016-03-04 05:26:16 +00002460 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2461 // pass them as integer. For platforms where clang is the de facto
2462 // platform compiler, we must continue to use integer.
2463 if (!classifyIntegerMMXAsSSE() &&
2464 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2465 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2466 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2467 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002468 Current = Integer;
2469 else
2470 Current = SSE;
2471
2472 // If this type crosses an eightbyte boundary, it should be
2473 // split.
2474 if (OffsetBase && OffsetBase != 64)
2475 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002476 } else if (Size == 128 ||
2477 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002478 // Arguments of 256-bits are split into four eightbyte chunks. The
2479 // least significant one belongs to class SSE and all the others to class
2480 // SSEUP. The original Lo and Hi design considers that types can't be
2481 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2482 // This design isn't correct for 256-bits, but since there're no cases
2483 // where the upper parts would need to be inspected, avoid adding
2484 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002485 //
2486 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2487 // registers if they are "named", i.e. not part of the "..." of a
2488 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002489 //
2490 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2491 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002492 Lo = SSE;
2493 Hi = SSEUp;
2494 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002495 return;
2496 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002497
Chris Lattnerd776fb12010-06-28 21:43:59 +00002498 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002499 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002500
Chris Lattner2b037972010-07-29 02:01:43 +00002501 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002502 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002503 if (Size <= 64)
2504 Current = Integer;
2505 else if (Size <= 128)
2506 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002507 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002508 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002509 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002510 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002511 } else if (ET == getContext().LongDoubleTy) {
2512 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002513 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002514 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002515 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002516 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002517 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002518 Lo = Hi = SSE;
2519 else
2520 llvm_unreachable("unexpected long double representation!");
2521 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002522
2523 // If this complex type crosses an eightbyte boundary then it
2524 // should be split.
2525 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002526 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002527 if (Hi == NoClass && EB_Real != EB_Imag)
2528 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002529
Chris Lattnerd776fb12010-06-28 21:43:59 +00002530 return;
2531 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002532
Chris Lattner2b037972010-07-29 02:01:43 +00002533 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002534 // Arrays are treated like structures.
2535
Chris Lattner2b037972010-07-29 02:01:43 +00002536 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002537
2538 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002539 // than eight eightbytes, ..., it has class MEMORY.
2540 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002541 return;
2542
2543 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2544 // fields, it has class MEMORY.
2545 //
2546 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002547 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002548 return;
2549
2550 // Otherwise implement simplified merge. We could be smarter about
2551 // this, but it isn't worth it and would be harder to verify.
2552 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002553 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002554 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002555
2556 // The only case a 256-bit wide vector could be used is when the array
2557 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2558 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002559 //
2560 if (Size > 128 &&
2561 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002562 return;
2563
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002564 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2565 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002566 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002567 Lo = merge(Lo, FieldLo);
2568 Hi = merge(Hi, FieldHi);
2569 if (Lo == Memory || Hi == Memory)
2570 break;
2571 }
2572
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002573 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002574 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002575 return;
2576 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002577
Chris Lattnerd776fb12010-06-28 21:43:59 +00002578 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002579 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002580
2581 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002582 // than eight eightbytes, ..., it has class MEMORY.
2583 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002584 return;
2585
Anders Carlsson20759ad2009-09-16 15:53:40 +00002586 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2587 // copy constructor or a non-trivial destructor, it is passed by invisible
2588 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002589 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002590 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002591
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002592 const RecordDecl *RD = RT->getDecl();
2593
2594 // Assume variable sized types are passed in memory.
2595 if (RD->hasFlexibleArrayMember())
2596 return;
2597
Chris Lattner2b037972010-07-29 02:01:43 +00002598 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002599
2600 // Reset Lo class, this will be recomputed.
2601 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002602
2603 // If this is a C++ record, classify the bases first.
2604 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002605 for (const auto &I : CXXRD->bases()) {
2606 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002607 "Unexpected base class!");
2608 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002609 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002610
2611 // Classify this field.
2612 //
2613 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2614 // single eightbyte, each is classified separately. Each eightbyte gets
2615 // initialized to class NO_CLASS.
2616 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002617 uint64_t Offset =
2618 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002619 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002620 Lo = merge(Lo, FieldLo);
2621 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002622 if (Lo == Memory || Hi == Memory) {
2623 postMerge(Size, Lo, Hi);
2624 return;
2625 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002626 }
2627 }
2628
2629 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002630 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002631 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002632 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002633 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2634 bool BitField = i->isBitField();
2635
David Majnemerb439dfe2016-08-15 07:20:40 +00002636 // Ignore padding bit-fields.
2637 if (BitField && i->isUnnamedBitfield())
2638 continue;
2639
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002640 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2641 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002643 // The only case a 256-bit wide vector could be used is when the struct
2644 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2645 // to work for sizes wider than 128, early check and fallback to memory.
2646 //
David Majnemerb229cb02016-08-15 06:39:18 +00002647 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2648 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002649 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002650 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002651 return;
2652 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002653 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002654 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002655 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002656 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002657 return;
2658 }
2659
2660 // Classify this field.
2661 //
2662 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2663 // exceeds a single eightbyte, each is classified
2664 // separately. Each eightbyte gets initialized to class
2665 // NO_CLASS.
2666 Class FieldLo, FieldHi;
2667
2668 // Bit-fields require special handling, they do not force the
2669 // structure to be passed in memory even if unaligned, and
2670 // therefore they can straddle an eightbyte.
2671 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002672 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002673 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002674 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002675
2676 uint64_t EB_Lo = Offset / 64;
2677 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002678
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002679 if (EB_Lo) {
2680 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2681 FieldLo = NoClass;
2682 FieldHi = Integer;
2683 } else {
2684 FieldLo = Integer;
2685 FieldHi = EB_Hi ? Integer : NoClass;
2686 }
2687 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002688 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002689 Lo = merge(Lo, FieldLo);
2690 Hi = merge(Hi, FieldHi);
2691 if (Lo == Memory || Hi == Memory)
2692 break;
2693 }
2694
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002695 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002696 }
2697}
2698
Chris Lattner22a931e2010-06-29 06:01:59 +00002699ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002700 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2701 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002702 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002703 // Treat an enum type as its underlying type.
2704 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2705 Ty = EnumTy->getDecl()->getIntegerType();
2706
2707 return (Ty->isPromotableIntegerType() ?
2708 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2709 }
2710
John McCall7f416cc2015-09-08 08:05:57 +00002711 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002712}
2713
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002714bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2715 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2716 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002717 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002718 if (Size <= 64 || Size > LargestVector)
2719 return true;
2720 }
2721
2722 return false;
2723}
2724
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002725ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2726 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002727 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2728 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002729 //
2730 // This assumption is optimistic, as there could be free registers available
2731 // when we need to pass this argument in memory, and LLVM could try to pass
2732 // the argument in the free register. This does not seem to happen currently,
2733 // but this code would be much safer if we could mark the argument with
2734 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002735 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002736 // Treat an enum type as its underlying type.
2737 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2738 Ty = EnumTy->getDecl()->getIntegerType();
2739
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002740 return (Ty->isPromotableIntegerType() ?
2741 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002742 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002743
Mark Lacey3825e832013-10-06 01:33:34 +00002744 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002745 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002746
Chris Lattner44c2b902011-05-22 23:21:23 +00002747 // Compute the byval alignment. We specify the alignment of the byval in all
2748 // cases so that the mid-level optimizer knows the alignment of the byval.
2749 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002750
2751 // Attempt to avoid passing indirect results using byval when possible. This
2752 // is important for good codegen.
2753 //
2754 // We do this by coercing the value into a scalar type which the backend can
2755 // handle naturally (i.e., without using byval).
2756 //
2757 // For simplicity, we currently only do this when we have exhausted all of the
2758 // free integer registers. Doing this when there are free integer registers
2759 // would require more care, as we would have to ensure that the coerced value
2760 // did not claim the unused register. That would require either reording the
2761 // arguments to the function (so that any subsequent inreg values came first),
2762 // or only doing this optimization when there were no following arguments that
2763 // might be inreg.
2764 //
2765 // We currently expect it to be rare (particularly in well written code) for
2766 // arguments to be passed on the stack when there are still free integer
2767 // registers available (this would typically imply large structs being passed
2768 // by value), so this seems like a fair tradeoff for now.
2769 //
2770 // We can revisit this if the backend grows support for 'onstack' parameter
2771 // attributes. See PR12193.
2772 if (freeIntRegs == 0) {
2773 uint64_t Size = getContext().getTypeSize(Ty);
2774
2775 // If this type fits in an eightbyte, coerce it into the matching integral
2776 // type, which will end up on the stack (with alignment 8).
2777 if (Align == 8 && Size <= 64)
2778 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2779 Size));
2780 }
2781
John McCall7f416cc2015-09-08 08:05:57 +00002782 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002783}
2784
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002785/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2786/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002787llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002788 // Wrapper structs/arrays that only contain vectors are passed just like
2789 // vectors; strip them off if present.
2790 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2791 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002792
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002793 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002794 if (isa<llvm::VectorType>(IRType) ||
2795 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002796 return IRType;
2797
2798 // We couldn't find the preferred IR vector type for 'Ty'.
2799 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002800 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002801
2802 // Return a LLVM IR vector type based on the size of 'Ty'.
2803 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2804 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002805}
2806
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002807/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2808/// is known to either be off the end of the specified type or being in
2809/// alignment padding. The user type specified is known to be at most 128 bits
2810/// in size, and have passed through X86_64ABIInfo::classify with a successful
2811/// classification that put one of the two halves in the INTEGER class.
2812///
2813/// It is conservatively correct to return false.
2814static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2815 unsigned EndBit, ASTContext &Context) {
2816 // If the bytes being queried are off the end of the type, there is no user
2817 // data hiding here. This handles analysis of builtins, vectors and other
2818 // types that don't contain interesting padding.
2819 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2820 if (TySize <= StartBit)
2821 return true;
2822
Chris Lattner98076a22010-07-29 07:43:55 +00002823 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2824 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2825 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2826
2827 // Check each element to see if the element overlaps with the queried range.
2828 for (unsigned i = 0; i != NumElts; ++i) {
2829 // If the element is after the span we care about, then we're done..
2830 unsigned EltOffset = i*EltSize;
2831 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002832
Chris Lattner98076a22010-07-29 07:43:55 +00002833 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2834 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2835 EndBit-EltOffset, Context))
2836 return false;
2837 }
2838 // If it overlaps no elements, then it is safe to process as padding.
2839 return true;
2840 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002841
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002842 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2843 const RecordDecl *RD = RT->getDecl();
2844 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002845
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002846 // If this is a C++ record, check the bases first.
2847 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002848 for (const auto &I : CXXRD->bases()) {
2849 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002850 "Unexpected base class!");
2851 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002852 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002853
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002854 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002855 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002856 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002857
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002858 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002859 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002860 EndBit-BaseOffset, Context))
2861 return false;
2862 }
2863 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002864
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002865 // Verify that no field has data that overlaps the region of interest. Yes
2866 // this could be sped up a lot by being smarter about queried fields,
2867 // however we're only looking at structs up to 16 bytes, so we don't care
2868 // much.
2869 unsigned idx = 0;
2870 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2871 i != e; ++i, ++idx) {
2872 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002873
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002874 // If we found a field after the region we care about, then we're done.
2875 if (FieldOffset >= EndBit) break;
2876
2877 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2878 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2879 Context))
2880 return false;
2881 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002882
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002883 // If nothing in this record overlapped the area of interest, then we're
2884 // clean.
2885 return true;
2886 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002887
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002888 return false;
2889}
2890
Chris Lattnere556a712010-07-29 18:39:32 +00002891/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2892/// float member at the specified offset. For example, {int,{float}} has a
2893/// float at offset 4. It is conservatively correct for this routine to return
2894/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002895static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002896 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002897 // Base case if we find a float.
2898 if (IROffset == 0 && IRType->isFloatTy())
2899 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002900
Chris Lattnere556a712010-07-29 18:39:32 +00002901 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002902 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002903 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2904 unsigned Elt = SL->getElementContainingOffset(IROffset);
2905 IROffset -= SL->getElementOffset(Elt);
2906 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2907 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002908
Chris Lattnere556a712010-07-29 18:39:32 +00002909 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002910 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2911 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002912 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2913 IROffset -= IROffset/EltSize*EltSize;
2914 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2915 }
2916
2917 return false;
2918}
2919
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002920
2921/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2922/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002923llvm::Type *X86_64ABIInfo::
2924GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002925 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002926 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002927 // pass as float if the last 4 bytes is just padding. This happens for
2928 // structs that contain 3 floats.
2929 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2930 SourceOffset*8+64, getContext()))
2931 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002932
Chris Lattnere556a712010-07-29 18:39:32 +00002933 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2934 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2935 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002936 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2937 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002938 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002939
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002940 return llvm::Type::getDoubleTy(getVMContext());
2941}
2942
2943
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002944/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2945/// an 8-byte GPR. This means that we either have a scalar or we are talking
2946/// about the high or low part of an up-to-16-byte struct. This routine picks
2947/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002948/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2949/// etc).
2950///
2951/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2952/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2953/// the 8-byte value references. PrefType may be null.
2954///
Alp Toker9907f082014-07-09 14:06:35 +00002955/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002956/// an offset into this that we're processing (which is always either 0 or 8).
2957///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002958llvm::Type *X86_64ABIInfo::
2959GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002960 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002961 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2962 // returning an 8-byte unit starting with it. See if we can safely use it.
2963 if (IROffset == 0) {
2964 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002965 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2966 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002967 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002968
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002969 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2970 // goodness in the source type is just tail padding. This is allowed to
2971 // kick in for struct {double,int} on the int, but not on
2972 // struct{double,int,int} because we wouldn't return the second int. We
2973 // have to do this analysis on the source type because we can't depend on
2974 // unions being lowered a specific way etc.
2975 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002976 IRType->isIntegerTy(32) ||
2977 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2978 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2979 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002980
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002981 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2982 SourceOffset*8+64, getContext()))
2983 return IRType;
2984 }
2985 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002986
Chris Lattner2192fe52011-07-18 04:24:23 +00002987 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002988 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002989 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002990 if (IROffset < SL->getSizeInBytes()) {
2991 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2992 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002993
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002994 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2995 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002996 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002997 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002998
Chris Lattner2192fe52011-07-18 04:24:23 +00002999 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003000 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003001 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003002 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003003 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3004 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003005 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003006
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003007 // Okay, we don't have any better idea of what to pass, so we pass this in an
3008 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003009 unsigned TySizeInBytes =
3010 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003011
Chris Lattner3f763422010-07-29 17:34:39 +00003012 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003013
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003014 // It is always safe to classify this as an integer type up to i64 that
3015 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003016 return llvm::IntegerType::get(getVMContext(),
3017 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003018}
3019
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003020
3021/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3022/// be used as elements of a two register pair to pass or return, return a
3023/// first class aggregate to represent them. For example, if the low part of
3024/// a by-value argument should be passed as i32* and the high part as float,
3025/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003026static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003027GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003028 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003029 // In order to correctly satisfy the ABI, we need to the high part to start
3030 // at offset 8. If the high and low parts we inferred are both 4-byte types
3031 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3032 // the second element at offset 8. Check for this:
3033 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3034 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003035 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003036 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003037
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003038 // To handle this, we have to increase the size of the low part so that the
3039 // second element will start at an 8 byte offset. We can't increase the size
3040 // of the second element because it might make us access off the end of the
3041 // struct.
3042 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003043 // There are usually two sorts of types the ABI generation code can produce
3044 // for the low part of a pair that aren't 8 bytes in size: float or
3045 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3046 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003047 // Promote these to a larger type.
3048 if (Lo->isFloatTy())
3049 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3050 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003051 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3052 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003053 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3054 }
3055 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003056
Reid Kleckneree7cf842014-12-01 22:02:27 +00003057 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003058
3059
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003060 // Verify that the second element is at an 8-byte offset.
3061 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3062 "Invalid x86-64 argument pair!");
3063 return Result;
3064}
3065
Chris Lattner31faff52010-07-28 23:06:14 +00003066ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003067classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003068 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3069 // classification algorithm.
3070 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003071 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003072
3073 // Check some invariants.
3074 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003075 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3076
Craig Topper8a13c412014-05-21 05:09:00 +00003077 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003078 switch (Lo) {
3079 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003080 if (Hi == NoClass)
3081 return ABIArgInfo::getIgnore();
3082 // If the low part is just padding, it takes no register, leave ResType
3083 // null.
3084 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3085 "Unknown missing lo part");
3086 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003087
3088 case SSEUp:
3089 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003090 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003091
3092 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3093 // hidden argument.
3094 case Memory:
3095 return getIndirectReturnResult(RetTy);
3096
3097 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3098 // available register of the sequence %rax, %rdx is used.
3099 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003100 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003101
Chris Lattner1f3a0632010-07-29 21:42:50 +00003102 // If we have a sign or zero extended integer, make sure to return Extend
3103 // so that the parameter gets the right LLVM IR attributes.
3104 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3105 // Treat an enum type as its underlying type.
3106 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3107 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003108
Chris Lattner1f3a0632010-07-29 21:42:50 +00003109 if (RetTy->isIntegralOrEnumerationType() &&
3110 RetTy->isPromotableIntegerType())
3111 return ABIArgInfo::getExtend();
3112 }
Chris Lattner31faff52010-07-28 23:06:14 +00003113 break;
3114
3115 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3116 // available SSE register of the sequence %xmm0, %xmm1 is used.
3117 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003118 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003119 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003120
3121 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3122 // returned on the X87 stack in %st0 as 80-bit x87 number.
3123 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003124 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003125 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003126
3127 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3128 // part of the value is returned in %st0 and the imaginary part in
3129 // %st1.
3130 case ComplexX87:
3131 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003132 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003133 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003134 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003135 break;
3136 }
3137
Craig Topper8a13c412014-05-21 05:09:00 +00003138 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003139 switch (Hi) {
3140 // Memory was handled previously and X87 should
3141 // never occur as a hi class.
3142 case Memory:
3143 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003144 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003145
3146 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003147 case NoClass:
3148 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003149
Chris Lattner52b3c132010-09-01 00:20:33 +00003150 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003151 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003152 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3153 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003154 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003155 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003156 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003157 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3158 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003159 break;
3160
3161 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003162 // is passed in the next available eightbyte chunk if the last used
3163 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003164 //
Chris Lattner57540c52011-04-15 05:22:18 +00003165 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003166 case SSEUp:
3167 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003168 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003169 break;
3170
3171 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3172 // returned together with the previous X87 value in %st0.
3173 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003174 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003175 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003176 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003177 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003178 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003179 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003180 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3181 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003182 }
Chris Lattner31faff52010-07-28 23:06:14 +00003183 break;
3184 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003185
Chris Lattner52b3c132010-09-01 00:20:33 +00003186 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003187 // known to pass in the high eightbyte of the result. We do this by forming a
3188 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003189 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003190 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003191
Chris Lattner1f3a0632010-07-29 21:42:50 +00003192 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003193}
3194
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003195ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003196 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3197 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003198 const
3199{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003200 Ty = useFirstFieldIfTransparentUnion(Ty);
3201
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003202 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003203 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003204
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003205 // Check some invariants.
3206 // FIXME: Enforce these by construction.
3207 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3209
3210 neededInt = 0;
3211 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003212 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003213 switch (Lo) {
3214 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003215 if (Hi == NoClass)
3216 return ABIArgInfo::getIgnore();
3217 // If the low part is just padding, it takes no register, leave ResType
3218 // null.
3219 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3220 "Unknown missing lo part");
3221 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003222
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003223 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3224 // on the stack.
3225 case Memory:
3226
3227 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3228 // COMPLEX_X87, it is passed in memory.
3229 case X87:
3230 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003231 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003232 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003233 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003234
3235 case SSEUp:
3236 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003237 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003238
3239 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3240 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3241 // and %r9 is used.
3242 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003243 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003244
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003245 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003246 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003247
3248 // If we have a sign or zero extended integer, make sure to return Extend
3249 // so that the parameter gets the right LLVM IR attributes.
3250 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3251 // Treat an enum type as its underlying type.
3252 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3253 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003254
Chris Lattner1f3a0632010-07-29 21:42:50 +00003255 if (Ty->isIntegralOrEnumerationType() &&
3256 Ty->isPromotableIntegerType())
3257 return ABIArgInfo::getExtend();
3258 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003259
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003260 break;
3261
3262 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3263 // available SSE register is used, the registers are taken in the
3264 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003265 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003266 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003267 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003268 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003269 break;
3270 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003271 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003272
Craig Topper8a13c412014-05-21 05:09:00 +00003273 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003274 switch (Hi) {
3275 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003276 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003277 // which is passed in memory.
3278 case Memory:
3279 case X87:
3280 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003281 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003282
3283 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003284
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003285 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003286 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003287 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003288 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003289
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003290 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3291 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003292 break;
3293
3294 // X87Up generally doesn't occur here (long double is passed in
3295 // memory), except in situations involving unions.
3296 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003297 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003298 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003299
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003300 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3301 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003302
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003303 ++neededSSE;
3304 break;
3305
3306 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3307 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003308 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003309 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003310 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003311 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003312 break;
3313 }
3314
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003315 // If a high part was specified, merge it together with the low part. It is
3316 // known to pass in the high eightbyte of the result. We do this by forming a
3317 // first class struct aggregate with the high and low part: {low, high}
3318 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003319 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003320
Chris Lattner1f3a0632010-07-29 21:42:50 +00003321 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003322}
3323
Erich Keane757d3172016-11-02 18:29:35 +00003324ABIArgInfo
3325X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3326 unsigned &NeededSSE) const {
3327 auto RT = Ty->getAs<RecordType>();
3328 assert(RT && "classifyRegCallStructType only valid with struct types");
3329
3330 if (RT->getDecl()->hasFlexibleArrayMember())
3331 return getIndirectReturnResult(Ty);
3332
3333 // Sum up bases
3334 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3335 if (CXXRD->isDynamicClass()) {
3336 NeededInt = NeededSSE = 0;
3337 return getIndirectReturnResult(Ty);
3338 }
3339
3340 for (const auto &I : CXXRD->bases())
3341 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3342 .isIndirect()) {
3343 NeededInt = NeededSSE = 0;
3344 return getIndirectReturnResult(Ty);
3345 }
3346 }
3347
3348 // Sum up members
3349 for (const auto *FD : RT->getDecl()->fields()) {
3350 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3351 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3352 .isIndirect()) {
3353 NeededInt = NeededSSE = 0;
3354 return getIndirectReturnResult(Ty);
3355 }
3356 } else {
3357 unsigned LocalNeededInt, LocalNeededSSE;
3358 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3359 LocalNeededSSE, true)
3360 .isIndirect()) {
3361 NeededInt = NeededSSE = 0;
3362 return getIndirectReturnResult(Ty);
3363 }
3364 NeededInt += LocalNeededInt;
3365 NeededSSE += LocalNeededSSE;
3366 }
3367 }
3368
3369 return ABIArgInfo::getDirect();
3370}
3371
3372ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3373 unsigned &NeededInt,
3374 unsigned &NeededSSE) const {
3375
3376 NeededInt = 0;
3377 NeededSSE = 0;
3378
3379 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3380}
3381
Chris Lattner22326a12010-07-29 02:31:05 +00003382void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003383
Erich Keane757d3172016-11-02 18:29:35 +00003384 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003385
3386 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003387 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3388 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3389 unsigned NeededInt, NeededSSE;
3390
3391 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3392 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3393 FI.getReturnInfo() =
3394 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3395 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3396 FreeIntRegs -= NeededInt;
3397 FreeSSERegs -= NeededSSE;
3398 } else {
3399 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3400 }
3401 } else if (!getCXXABI().classifyReturnType(FI))
3402 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003403
3404 // If the return value is indirect, then the hidden argument is consuming one
3405 // integer register.
3406 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003407 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003408
Peter Collingbournef7706832014-12-12 23:41:25 +00003409 // The chain argument effectively gives us another free register.
3410 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003411 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003412
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003413 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003414 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3415 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003416 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003417 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003418 it != ie; ++it, ++ArgNo) {
3419 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003420
Erich Keane757d3172016-11-02 18:29:35 +00003421 if (IsRegCall && it->type->isStructureOrClassType())
3422 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3423 else
3424 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3425 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003426
3427 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3428 // eightbyte of an argument, the whole argument is passed on the
3429 // stack. If registers have already been assigned for some
3430 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003431 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3432 FreeIntRegs -= NeededInt;
3433 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003434 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003435 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003436 }
3437 }
3438}
3439
John McCall7f416cc2015-09-08 08:05:57 +00003440static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3441 Address VAListAddr, QualType Ty) {
3442 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3443 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003444 llvm::Value *overflow_arg_area =
3445 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3446
3447 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3448 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003449 // It isn't stated explicitly in the standard, but in practice we use
3450 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003451 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3452 if (Align > CharUnits::fromQuantity(8)) {
3453 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3454 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003455 }
3456
3457 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003458 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003459 llvm::Value *Res =
3460 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003461 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003462
3463 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3464 // l->overflow_arg_area + sizeof(type).
3465 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3466 // an 8 byte boundary.
3467
3468 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003469 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003470 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003471 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3472 "overflow_arg_area.next");
3473 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3474
3475 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003476 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003477}
3478
John McCall7f416cc2015-09-08 08:05:57 +00003479Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3480 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003481 // Assume that va_list type is correct; should be pointer to LLVM type:
3482 // struct {
3483 // i32 gp_offset;
3484 // i32 fp_offset;
3485 // i8* overflow_arg_area;
3486 // i8* reg_save_area;
3487 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003488 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003489
John McCall7f416cc2015-09-08 08:05:57 +00003490 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003491 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003492 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003493
3494 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3495 // in the registers. If not go to step 7.
3496 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003497 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003498
3499 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3500 // general purpose registers needed to pass type and num_fp to hold
3501 // the number of floating point registers needed.
3502
3503 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3504 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3505 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3506 //
3507 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3508 // register save space).
3509
Craig Topper8a13c412014-05-21 05:09:00 +00003510 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003511 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3512 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003513 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003514 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003515 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3516 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003517 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003518 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3519 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003520 }
3521
3522 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003523 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003524 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3525 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003526 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3527 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003528 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3529 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003530 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3531 }
3532
3533 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3534 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3535 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3536 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3537
3538 // Emit code to load the value if it was passed in registers.
3539
3540 CGF.EmitBlock(InRegBlock);
3541
3542 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3543 // an offset of l->gp_offset and/or l->fp_offset. This may require
3544 // copying to a temporary location in case the parameter is passed
3545 // in different register classes or requires an alignment greater
3546 // than 8 for general purpose registers and 16 for XMM registers.
3547 //
3548 // FIXME: This really results in shameful code when we end up needing to
3549 // collect arguments from different places; often what should result in a
3550 // simple assembling of a structure from scattered addresses has many more
3551 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003552 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003553 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3554 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3555 "reg_save_area");
3556
3557 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003558 if (neededInt && neededSSE) {
3559 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003560 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003561 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003562 Address Tmp = CGF.CreateMemTemp(Ty);
3563 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003564 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003565 llvm::Type *TyLo = ST->getElementType(0);
3566 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003567 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003568 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003569 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3570 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003571 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3572 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003573 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3574 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003575
John McCall7f416cc2015-09-08 08:05:57 +00003576 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003577 // FIXME: Our choice of alignment here and below is probably pessimistic.
3578 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3579 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3580 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003581 CGF.Builder.CreateStore(V,
3582 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3583
3584 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003585 V = CGF.Builder.CreateAlignedLoad(
3586 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3587 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003588 CharUnits Offset = CharUnits::fromQuantity(
3589 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3590 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3591
3592 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003593 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003594 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3595 CharUnits::fromQuantity(8));
3596 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003597
3598 // Copy to a temporary if necessary to ensure the appropriate alignment.
3599 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003600 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003601 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003602 CharUnits TyAlign = SizeAlign.second;
3603
3604 // Copy into a temporary if the type is more aligned than the
3605 // register save area.
3606 if (TyAlign.getQuantity() > 8) {
3607 Address Tmp = CGF.CreateMemTemp(Ty);
3608 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003609 RegAddr = Tmp;
3610 }
John McCall7f416cc2015-09-08 08:05:57 +00003611
Chris Lattner0cf24192010-06-28 20:05:43 +00003612 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003613 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3614 CharUnits::fromQuantity(16));
3615 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003616 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003617 assert(neededSSE == 2 && "Invalid number of needed registers!");
3618 // SSE registers are spaced 16 bytes apart in the register save
3619 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003620 // The ABI isn't explicit about this, but it seems reasonable
3621 // to assume that the slots are 16-byte aligned, since the stack is
3622 // naturally 16-byte aligned and the prologue is expected to store
3623 // all the SSE registers to the RSA.
3624 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3625 CharUnits::fromQuantity(16));
3626 Address RegAddrHi =
3627 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3628 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003629 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003630 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003631 llvm::Value *V;
3632 Address Tmp = CGF.CreateMemTemp(Ty);
3633 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3634 V = CGF.Builder.CreateLoad(
3635 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3636 CGF.Builder.CreateStore(V,
3637 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3638 V = CGF.Builder.CreateLoad(
3639 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3640 CGF.Builder.CreateStore(V,
3641 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3642
3643 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003644 }
3645
3646 // AMD64-ABI 3.5.7p5: Step 5. Set:
3647 // l->gp_offset = l->gp_offset + num_gp * 8
3648 // l->fp_offset = l->fp_offset + num_fp * 16.
3649 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003650 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003651 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3652 gp_offset_p);
3653 }
3654 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003655 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003656 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3657 fp_offset_p);
3658 }
3659 CGF.EmitBranch(ContBlock);
3660
3661 // Emit code to load the value if it was passed in memory.
3662
3663 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003664 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003665
3666 // Return the appropriate result.
3667
3668 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003669 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3670 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003671 return ResAddr;
3672}
3673
Charles Davisc7d5c942015-09-17 20:55:33 +00003674Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3675 QualType Ty) const {
3676 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3677 CGF.getContext().getTypeInfoInChars(Ty),
3678 CharUnits::fromQuantity(8),
3679 /*allowHigherAlign*/ false);
3680}
3681
Reid Kleckner80944df2014-10-31 22:00:51 +00003682ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3683 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003684
3685 if (Ty->isVoidType())
3686 return ABIArgInfo::getIgnore();
3687
3688 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3689 Ty = EnumTy->getDecl()->getIntegerType();
3690
Reid Kleckner80944df2014-10-31 22:00:51 +00003691 TypeInfo Info = getContext().getTypeInfo(Ty);
3692 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003693 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003694
Reid Kleckner9005f412014-05-02 00:51:20 +00003695 const RecordType *RT = Ty->getAs<RecordType>();
3696 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003697 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003698 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003699 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003700 }
3701
3702 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003703 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003704
Reid Kleckner9005f412014-05-02 00:51:20 +00003705 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003706
Reid Kleckner80944df2014-10-31 22:00:51 +00003707 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3708 // other targets.
3709 const Type *Base = nullptr;
3710 uint64_t NumElts = 0;
3711 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3712 if (FreeSSERegs >= NumElts) {
3713 FreeSSERegs -= NumElts;
3714 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3715 return ABIArgInfo::getDirect();
3716 return ABIArgInfo::getExpand();
3717 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003718 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003719 }
3720
3721
Reid Klecknerec87fec2014-05-02 01:17:12 +00003722 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003723 // If the member pointer is represented by an LLVM int or ptr, pass it
3724 // directly.
3725 llvm::Type *LLTy = CGT.ConvertType(Ty);
3726 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3727 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003728 }
3729
Michael Kuperstein4f818702015-02-24 09:35:58 +00003730 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003731 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3732 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003733 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003734 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003735
Reid Kleckner9005f412014-05-02 00:51:20 +00003736 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003737 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003738 }
3739
Julien Lerouge10dcff82014-08-27 00:36:55 +00003740 // Bool type is always extended to the ABI, other builtin types are not
3741 // extended.
3742 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3743 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003744 return ABIArgInfo::getExtend();
3745
Reid Kleckner11a17192015-10-28 22:29:52 +00003746 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3747 // passes them indirectly through memory.
3748 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3749 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003750 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003751 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3752 }
3753
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003754 return ABIArgInfo::getDirect();
3755}
3756
3757void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003758 bool IsVectorCall =
3759 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003760 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003761
Erich Keane757d3172016-11-02 18:29:35 +00003762 unsigned FreeSSERegs = 0;
3763 if (IsVectorCall) {
3764 // We can use up to 4 SSE return registers with vectorcall.
3765 FreeSSERegs = 4;
3766 } else if (IsRegCall) {
3767 // RegCall gives us 16 SSE registers.
3768 FreeSSERegs = 16;
3769 }
3770
Reid Kleckner80944df2014-10-31 22:00:51 +00003771 if (!getCXXABI().classifyReturnType(FI))
3772 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3773
Erich Keane757d3172016-11-02 18:29:35 +00003774 if (IsVectorCall) {
3775 // We can use up to 6 SSE register parameters with vectorcall.
3776 FreeSSERegs = 6;
3777 } else if (IsRegCall) {
3778 FreeSSERegs = 16;
3779 }
3780
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003781 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003782 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003783}
3784
John McCall7f416cc2015-09-08 08:05:57 +00003785Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3786 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003787
3788 bool IsIndirect = false;
3789
3790 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3791 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3792 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3793 uint64_t Width = getContext().getTypeSize(Ty);
3794 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3795 }
3796
3797 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00003798 CGF.getContext().getTypeInfoInChars(Ty),
3799 CharUnits::fromQuantity(8),
3800 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003801}
Chris Lattner0cf24192010-06-28 20:05:43 +00003802
John McCallea8d8bb2010-03-11 00:10:12 +00003803// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003804namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003805/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3806class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003807bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003808public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003809 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3810 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003811
John McCall7f416cc2015-09-08 08:05:57 +00003812 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3813 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003814};
3815
3816class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3817public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003818 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3819 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003820
Craig Topper4f12f102014-03-12 06:41:41 +00003821 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003822 // This is recovered from gcc output.
3823 return 1; // r1 is the dedicated stack pointer
3824 }
3825
3826 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003827 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003828};
3829
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003830}
John McCallea8d8bb2010-03-11 00:10:12 +00003831
James Y Knight29b5f082016-02-24 02:59:33 +00003832// TODO: this implementation is now likely redundant with
3833// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00003834Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3835 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003836 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003837 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3838 // TODO: Implement this. For now ignore.
3839 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00003840 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00003841 }
3842
John McCall7f416cc2015-09-08 08:05:57 +00003843 // struct __va_list_tag {
3844 // unsigned char gpr;
3845 // unsigned char fpr;
3846 // unsigned short reserved;
3847 // void *overflow_arg_area;
3848 // void *reg_save_area;
3849 // };
3850
Roman Divacky8a12d842014-11-03 18:32:54 +00003851 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003852 bool isInt =
3853 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003854 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003855
3856 // All aggregates are passed indirectly? That doesn't seem consistent
3857 // with the argument-lowering code.
3858 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003859
3860 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003861
3862 // The calling convention either uses 1-2 GPRs or 1 FPR.
3863 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003864 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003865 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3866 } else {
3867 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003868 }
John McCall7f416cc2015-09-08 08:05:57 +00003869
3870 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3871
3872 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003873 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003874 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3875 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3876 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003877
Eric Christopher7565e0d2015-05-29 23:09:49 +00003878 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003879 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003880
3881 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3882 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3883 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3884
3885 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3886
John McCall7f416cc2015-09-08 08:05:57 +00003887 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3888 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003889
John McCall7f416cc2015-09-08 08:05:57 +00003890 // Case 1: consume registers.
3891 Address RegAddr = Address::invalid();
3892 {
3893 CGF.EmitBlock(UsingRegs);
3894
3895 Address RegSaveAreaPtr =
3896 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3897 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3898 CharUnits::fromQuantity(8));
3899 assert(RegAddr.getElementType() == CGF.Int8Ty);
3900
3901 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003902 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003903 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3904 CharUnits::fromQuantity(32));
3905 }
3906
3907 // Get the address of the saved value by scaling the number of
3908 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003909 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003910 llvm::Value *RegOffset =
3911 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3912 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3913 RegAddr.getPointer(), RegOffset),
3914 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3915 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3916
3917 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003918 NumRegs =
3919 Builder.CreateAdd(NumRegs,
3920 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003921 Builder.CreateStore(NumRegs, NumRegsAddr);
3922
3923 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003924 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003925
John McCall7f416cc2015-09-08 08:05:57 +00003926 // Case 2: consume space in the overflow area.
3927 Address MemAddr = Address::invalid();
3928 {
3929 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003930
Roman Divacky039b9702016-02-20 08:31:24 +00003931 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3932
John McCall7f416cc2015-09-08 08:05:57 +00003933 // Everything in the overflow area is rounded up to a size of at least 4.
3934 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3935
3936 CharUnits Size;
3937 if (!isIndirect) {
3938 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003939 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003940 } else {
3941 Size = CGF.getPointerSize();
3942 }
3943
3944 Address OverflowAreaAddr =
3945 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003946 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003947 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003948 // Round up address of argument to alignment
3949 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3950 if (Align > OverflowAreaAlign) {
3951 llvm::Value *Ptr = OverflowArea.getPointer();
3952 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3953 Align);
3954 }
3955
John McCall7f416cc2015-09-08 08:05:57 +00003956 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3957
3958 // Increase the overflow area.
3959 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3960 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3961 CGF.EmitBranch(Cont);
3962 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003963
3964 CGF.EmitBlock(Cont);
3965
John McCall7f416cc2015-09-08 08:05:57 +00003966 // Merge the cases with a phi.
3967 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3968 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003969
John McCall7f416cc2015-09-08 08:05:57 +00003970 // Load the pointer if the argument was passed indirectly.
3971 if (isIndirect) {
3972 Result = Address(Builder.CreateLoad(Result, "aggr"),
3973 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003974 }
3975
3976 return Result;
3977}
3978
John McCallea8d8bb2010-03-11 00:10:12 +00003979bool
3980PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3981 llvm::Value *Address) const {
3982 // This is calculated from the LLVM and GCC tables and verified
3983 // against gcc output. AFAIK all ABIs use the same encoding.
3984
3985 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003986
Chris Lattnerece04092012-02-07 00:39:47 +00003987 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003988 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3989 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3990 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3991
3992 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003993 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003994
3995 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003996 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003997
3998 // 64-76 are various 4-byte special-purpose registers:
3999 // 64: mq
4000 // 65: lr
4001 // 66: ctr
4002 // 67: ap
4003 // 68-75 cr0-7
4004 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004005 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004006
4007 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004008 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004009
4010 // 109: vrsave
4011 // 110: vscr
4012 // 111: spe_acc
4013 // 112: spefscr
4014 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004015 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004016
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004017 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004018}
4019
Roman Divackyd966e722012-05-09 18:22:46 +00004020// PowerPC-64
4021
4022namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004023/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004024class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004025public:
4026 enum ABIKind {
4027 ELFv1 = 0,
4028 ELFv2
4029 };
4030
4031private:
4032 static const unsigned GPRBits = 64;
4033 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004034 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004035 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004036
4037 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4038 // will be passed in a QPX register.
4039 bool IsQPXVectorTy(const Type *Ty) const {
4040 if (!HasQPX)
4041 return false;
4042
4043 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4044 unsigned NumElements = VT->getNumElements();
4045 if (NumElements == 1)
4046 return false;
4047
4048 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4049 if (getContext().getTypeSize(Ty) <= 256)
4050 return true;
4051 } else if (VT->getElementType()->
4052 isSpecificBuiltinType(BuiltinType::Float)) {
4053 if (getContext().getTypeSize(Ty) <= 128)
4054 return true;
4055 }
4056 }
4057
4058 return false;
4059 }
4060
4061 bool IsQPXVectorTy(QualType Ty) const {
4062 return IsQPXVectorTy(Ty.getTypePtr());
4063 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004064
4065public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004066 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4067 bool SoftFloatABI)
4068 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4069 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004070
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004071 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004072 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004073
4074 ABIArgInfo classifyReturnType(QualType RetTy) const;
4075 ABIArgInfo classifyArgumentType(QualType Ty) const;
4076
Reid Klecknere9f6a712014-10-31 17:10:41 +00004077 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4078 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4079 uint64_t Members) const override;
4080
Bill Schmidt84d37792012-10-12 19:26:17 +00004081 // TODO: We can add more logic to computeInfo to improve performance.
4082 // Example: For aggregate arguments that fit in a register, we could
4083 // use getDirectInReg (as is done below for structs containing a single
4084 // floating-point value) to avoid pushing them to memory on function
4085 // entry. This would require changing the logic in PPCISelLowering
4086 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004087 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004088 if (!getCXXABI().classifyReturnType(FI))
4089 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004090 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004091 // We rely on the default argument classification for the most part.
4092 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004093 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004094 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004095 if (T) {
4096 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004097 if (IsQPXVectorTy(T) ||
4098 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004099 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004100 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004101 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004102 continue;
4103 }
4104 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004105 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004106 }
4107 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004108
John McCall7f416cc2015-09-08 08:05:57 +00004109 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4110 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004111};
4112
4113class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004114
Bill Schmidt25cb3492012-10-03 19:18:57 +00004115public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004116 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004117 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4118 bool SoftFloatABI)
4119 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4120 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004121
Craig Topper4f12f102014-03-12 06:41:41 +00004122 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004123 // This is recovered from gcc output.
4124 return 1; // r1 is the dedicated stack pointer
4125 }
4126
4127 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004128 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004129};
4130
Roman Divackyd966e722012-05-09 18:22:46 +00004131class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4132public:
4133 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4134
Craig Topper4f12f102014-03-12 06:41:41 +00004135 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004136 // This is recovered from gcc output.
4137 return 1; // r1 is the dedicated stack pointer
4138 }
4139
4140 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004141 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004142};
4143
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004144}
Roman Divackyd966e722012-05-09 18:22:46 +00004145
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004146// Return true if the ABI requires Ty to be passed sign- or zero-
4147// extended to 64 bits.
4148bool
4149PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4150 // Treat an enum type as its underlying type.
4151 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4152 Ty = EnumTy->getDecl()->getIntegerType();
4153
4154 // Promotable integer types are required to be promoted by the ABI.
4155 if (Ty->isPromotableIntegerType())
4156 return true;
4157
4158 // In addition to the usual promotable integer types, we also need to
4159 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4160 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4161 switch (BT->getKind()) {
4162 case BuiltinType::Int:
4163 case BuiltinType::UInt:
4164 return true;
4165 default:
4166 break;
4167 }
4168
4169 return false;
4170}
4171
John McCall7f416cc2015-09-08 08:05:57 +00004172/// isAlignedParamType - Determine whether a type requires 16-byte or
4173/// higher alignment in the parameter area. Always returns at least 8.
4174CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004175 // Complex types are passed just like their elements.
4176 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4177 Ty = CTy->getElementType();
4178
4179 // Only vector types of size 16 bytes need alignment (larger types are
4180 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004181 if (IsQPXVectorTy(Ty)) {
4182 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004183 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004184
John McCall7f416cc2015-09-08 08:05:57 +00004185 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004186 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004187 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004188 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004189
4190 // For single-element float/vector structs, we consider the whole type
4191 // to have the same alignment requirements as its single element.
4192 const Type *AlignAsType = nullptr;
4193 const Type *EltType = isSingleElementStruct(Ty, getContext());
4194 if (EltType) {
4195 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004196 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004197 getContext().getTypeSize(EltType) == 128) ||
4198 (BT && BT->isFloatingPoint()))
4199 AlignAsType = EltType;
4200 }
4201
Ulrich Weigandb7122372014-07-21 00:48:09 +00004202 // Likewise for ELFv2 homogeneous aggregates.
4203 const Type *Base = nullptr;
4204 uint64_t Members = 0;
4205 if (!AlignAsType && Kind == ELFv2 &&
4206 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4207 AlignAsType = Base;
4208
Ulrich Weigand581badc2014-07-10 17:20:07 +00004209 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004210 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4211 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004212 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004213
John McCall7f416cc2015-09-08 08:05:57 +00004214 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004215 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004216 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004217 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004218
4219 // Otherwise, we only need alignment for any aggregate type that
4220 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004221 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4222 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004223 return CharUnits::fromQuantity(32);
4224 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004225 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004226
John McCall7f416cc2015-09-08 08:05:57 +00004227 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004228}
4229
Ulrich Weigandb7122372014-07-21 00:48:09 +00004230/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4231/// aggregate. Base is set to the base element type, and Members is set
4232/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004233bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4234 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004235 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4236 uint64_t NElements = AT->getSize().getZExtValue();
4237 if (NElements == 0)
4238 return false;
4239 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4240 return false;
4241 Members *= NElements;
4242 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4243 const RecordDecl *RD = RT->getDecl();
4244 if (RD->hasFlexibleArrayMember())
4245 return false;
4246
4247 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004248
4249 // If this is a C++ record, check the bases first.
4250 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4251 for (const auto &I : CXXRD->bases()) {
4252 // Ignore empty records.
4253 if (isEmptyRecord(getContext(), I.getType(), true))
4254 continue;
4255
4256 uint64_t FldMembers;
4257 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4258 return false;
4259
4260 Members += FldMembers;
4261 }
4262 }
4263
Ulrich Weigandb7122372014-07-21 00:48:09 +00004264 for (const auto *FD : RD->fields()) {
4265 // Ignore (non-zero arrays of) empty records.
4266 QualType FT = FD->getType();
4267 while (const ConstantArrayType *AT =
4268 getContext().getAsConstantArrayType(FT)) {
4269 if (AT->getSize().getZExtValue() == 0)
4270 return false;
4271 FT = AT->getElementType();
4272 }
4273 if (isEmptyRecord(getContext(), FT, true))
4274 continue;
4275
4276 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4277 if (getContext().getLangOpts().CPlusPlus &&
4278 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4279 continue;
4280
4281 uint64_t FldMembers;
4282 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4283 return false;
4284
4285 Members = (RD->isUnion() ?
4286 std::max(Members, FldMembers) : Members + FldMembers);
4287 }
4288
4289 if (!Base)
4290 return false;
4291
4292 // Ensure there is no padding.
4293 if (getContext().getTypeSize(Base) * Members !=
4294 getContext().getTypeSize(Ty))
4295 return false;
4296 } else {
4297 Members = 1;
4298 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4299 Members = 2;
4300 Ty = CT->getElementType();
4301 }
4302
Reid Klecknere9f6a712014-10-31 17:10:41 +00004303 // Most ABIs only support float, double, and some vector type widths.
4304 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004305 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004306
4307 // The base type must be the same for all members. Types that
4308 // agree in both total size and mode (float vs. vector) are
4309 // treated as being equivalent here.
4310 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004311 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004312 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004313 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4314 // so make sure to widen it explicitly.
4315 if (const VectorType *VT = Base->getAs<VectorType>()) {
4316 QualType EltTy = VT->getElementType();
4317 unsigned NumElements =
4318 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4319 Base = getContext()
4320 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4321 .getTypePtr();
4322 }
4323 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004324
4325 if (Base->isVectorType() != TyPtr->isVectorType() ||
4326 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4327 return false;
4328 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004329 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4330}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004331
Reid Klecknere9f6a712014-10-31 17:10:41 +00004332bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4333 // Homogeneous aggregates for ELFv2 must have base types of float,
4334 // double, long double, or 128-bit vectors.
4335 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4336 if (BT->getKind() == BuiltinType::Float ||
4337 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004338 BT->getKind() == BuiltinType::LongDouble) {
4339 if (IsSoftFloatABI)
4340 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004341 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004342 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004343 }
4344 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004345 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004346 return true;
4347 }
4348 return false;
4349}
4350
4351bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4352 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004353 // Vector types require one register, floating point types require one
4354 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004355 uint32_t NumRegs =
4356 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004357
4358 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004359 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004360}
4361
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004362ABIArgInfo
4363PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004364 Ty = useFirstFieldIfTransparentUnion(Ty);
4365
Bill Schmidt90b22c92012-11-27 02:46:43 +00004366 if (Ty->isAnyComplexType())
4367 return ABIArgInfo::getDirect();
4368
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004369 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4370 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004371 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004372 uint64_t Size = getContext().getTypeSize(Ty);
4373 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004374 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004375 else if (Size < 128) {
4376 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4377 return ABIArgInfo::getDirect(CoerceTy);
4378 }
4379 }
4380
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004381 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004382 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004383 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004384
John McCall7f416cc2015-09-08 08:05:57 +00004385 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4386 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004387
4388 // ELFv2 homogeneous aggregates are passed as array types.
4389 const Type *Base = nullptr;
4390 uint64_t Members = 0;
4391 if (Kind == ELFv2 &&
4392 isHomogeneousAggregate(Ty, Base, Members)) {
4393 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4394 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4395 return ABIArgInfo::getDirect(CoerceTy);
4396 }
4397
Ulrich Weigand601957f2014-07-21 00:56:36 +00004398 // If an aggregate may end up fully in registers, we do not
4399 // use the ByVal method, but pass the aggregate as array.
4400 // This is usually beneficial since we avoid forcing the
4401 // back-end to store the argument to memory.
4402 uint64_t Bits = getContext().getTypeSize(Ty);
4403 if (Bits > 0 && Bits <= 8 * GPRBits) {
4404 llvm::Type *CoerceTy;
4405
4406 // Types up to 8 bytes are passed as integer type (which will be
4407 // properly aligned in the argument save area doubleword).
4408 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004409 CoerceTy =
4410 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004411 // Larger types are passed as arrays, with the base type selected
4412 // according to the required alignment in the save area.
4413 else {
4414 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004415 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004416 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4417 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4418 }
4419
4420 return ABIArgInfo::getDirect(CoerceTy);
4421 }
4422
Ulrich Weigandb7122372014-07-21 00:48:09 +00004423 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004424 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4425 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004426 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004427 }
4428
4429 return (isPromotableTypeForABI(Ty) ?
4430 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4431}
4432
4433ABIArgInfo
4434PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4435 if (RetTy->isVoidType())
4436 return ABIArgInfo::getIgnore();
4437
Bill Schmidta3d121c2012-12-17 04:20:17 +00004438 if (RetTy->isAnyComplexType())
4439 return ABIArgInfo::getDirect();
4440
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004441 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4442 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004443 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004444 uint64_t Size = getContext().getTypeSize(RetTy);
4445 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004446 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004447 else if (Size < 128) {
4448 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4449 return ABIArgInfo::getDirect(CoerceTy);
4450 }
4451 }
4452
Ulrich Weigandb7122372014-07-21 00:48:09 +00004453 if (isAggregateTypeForABI(RetTy)) {
4454 // ELFv2 homogeneous aggregates are returned as array types.
4455 const Type *Base = nullptr;
4456 uint64_t Members = 0;
4457 if (Kind == ELFv2 &&
4458 isHomogeneousAggregate(RetTy, Base, Members)) {
4459 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4460 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4461 return ABIArgInfo::getDirect(CoerceTy);
4462 }
4463
4464 // ELFv2 small aggregates are returned in up to two registers.
4465 uint64_t Bits = getContext().getTypeSize(RetTy);
4466 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4467 if (Bits == 0)
4468 return ABIArgInfo::getIgnore();
4469
4470 llvm::Type *CoerceTy;
4471 if (Bits > GPRBits) {
4472 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004473 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004474 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004475 CoerceTy =
4476 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004477 return ABIArgInfo::getDirect(CoerceTy);
4478 }
4479
4480 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004481 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004482 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004483
4484 return (isPromotableTypeForABI(RetTy) ?
4485 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4486}
4487
Bill Schmidt25cb3492012-10-03 19:18:57 +00004488// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004489Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4490 QualType Ty) const {
4491 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4492 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004493
John McCall7f416cc2015-09-08 08:05:57 +00004494 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004495
Bill Schmidt924c4782013-01-14 17:45:36 +00004496 // If we have a complex type and the base type is smaller than 8 bytes,
4497 // the ABI calls for the real and imaginary parts to be right-adjusted
4498 // in separate doublewords. However, Clang expects us to produce a
4499 // pointer to a structure with the two parts packed tightly. So generate
4500 // loads of the real and imaginary parts relative to the va_list pointer,
4501 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004502 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4503 CharUnits EltSize = TypeInfo.first / 2;
4504 if (EltSize < SlotSize) {
4505 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4506 SlotSize * 2, SlotSize,
4507 SlotSize, /*AllowHigher*/ true);
4508
4509 Address RealAddr = Addr;
4510 Address ImagAddr = RealAddr;
4511 if (CGF.CGM.getDataLayout().isBigEndian()) {
4512 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4513 SlotSize - EltSize);
4514 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4515 2 * SlotSize - EltSize);
4516 } else {
4517 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4518 }
4519
4520 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4521 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4522 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4523 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4524 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4525
4526 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4527 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4528 /*init*/ true);
4529 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004530 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004531 }
4532
John McCall7f416cc2015-09-08 08:05:57 +00004533 // Otherwise, just use the general rule.
4534 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4535 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004536}
4537
4538static bool
4539PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4540 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004541 // This is calculated from the LLVM and GCC tables and verified
4542 // against gcc output. AFAIK all ABIs use the same encoding.
4543
4544 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4545
4546 llvm::IntegerType *i8 = CGF.Int8Ty;
4547 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4548 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4549 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4550
4551 // 0-31: r0-31, the 8-byte general-purpose registers
4552 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4553
4554 // 32-63: fp0-31, the 8-byte floating-point registers
4555 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4556
Hal Finkel84832a72016-08-30 02:38:34 +00004557 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004558 // 64: mq
4559 // 65: lr
4560 // 66: ctr
4561 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004562 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4563
4564 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004565 // 68-75 cr0-7
4566 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004567 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004568
4569 // 77-108: v0-31, the 16-byte vector registers
4570 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4571
4572 // 109: vrsave
4573 // 110: vscr
4574 // 111: spe_acc
4575 // 112: spefscr
4576 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004577 // 114: tfhar
4578 // 115: tfiar
4579 // 116: texasr
4580 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004581
4582 return false;
4583}
John McCallea8d8bb2010-03-11 00:10:12 +00004584
Bill Schmidt25cb3492012-10-03 19:18:57 +00004585bool
4586PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4587 CodeGen::CodeGenFunction &CGF,
4588 llvm::Value *Address) const {
4589
4590 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4591}
4592
4593bool
4594PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4595 llvm::Value *Address) const {
4596
4597 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4598}
4599
Chris Lattner0cf24192010-06-28 20:05:43 +00004600//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004601// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004602//===----------------------------------------------------------------------===//
4603
4604namespace {
4605
John McCall12f23522016-04-04 18:33:08 +00004606class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004607public:
4608 enum ABIKind {
4609 AAPCS = 0,
4610 DarwinPCS
4611 };
4612
4613private:
4614 ABIKind Kind;
4615
4616public:
John McCall12f23522016-04-04 18:33:08 +00004617 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4618 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004619
4620private:
4621 ABIKind getABIKind() const { return Kind; }
4622 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4623
4624 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004625 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004626 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4627 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4628 uint64_t Members) const override;
4629
Tim Northovera2ee4332014-03-29 15:09:45 +00004630 bool isIllegalVectorType(QualType Ty) const;
4631
David Blaikie1cbb9712014-11-14 19:09:44 +00004632 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004633 if (!getCXXABI().classifyReturnType(FI))
4634 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004635
Tim Northoverb047bfa2014-11-27 21:02:49 +00004636 for (auto &it : FI.arguments())
4637 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004638 }
4639
John McCall7f416cc2015-09-08 08:05:57 +00004640 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4641 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004642
John McCall7f416cc2015-09-08 08:05:57 +00004643 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4644 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004645
John McCall7f416cc2015-09-08 08:05:57 +00004646 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4647 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004648 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4649 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4650 }
John McCall12f23522016-04-04 18:33:08 +00004651
4652 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4653 ArrayRef<llvm::Type*> scalars,
4654 bool asReturnValue) const override {
4655 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4656 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004657 bool isSwiftErrorInRegister() const override {
4658 return true;
4659 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004660};
4661
Tim Northover573cbee2014-05-24 12:52:07 +00004662class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004663public:
Tim Northover573cbee2014-05-24 12:52:07 +00004664 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4665 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004666
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004667 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004668 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4669 }
4670
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004671 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4672 return 31;
4673 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004674
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004675 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004676};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004677}
Tim Northovera2ee4332014-03-29 15:09:45 +00004678
Tim Northoverb047bfa2014-11-27 21:02:49 +00004679ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004680 Ty = useFirstFieldIfTransparentUnion(Ty);
4681
Tim Northovera2ee4332014-03-29 15:09:45 +00004682 // Handle illegal vector types here.
4683 if (isIllegalVectorType(Ty)) {
4684 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004685 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004686 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004687 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4688 return ABIArgInfo::getDirect(ResType);
4689 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004690 if (Size <= 32) {
4691 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004692 return ABIArgInfo::getDirect(ResType);
4693 }
4694 if (Size == 64) {
4695 llvm::Type *ResType =
4696 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004697 return ABIArgInfo::getDirect(ResType);
4698 }
4699 if (Size == 128) {
4700 llvm::Type *ResType =
4701 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004702 return ABIArgInfo::getDirect(ResType);
4703 }
John McCall7f416cc2015-09-08 08:05:57 +00004704 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004705 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004706
4707 if (!isAggregateTypeForABI(Ty)) {
4708 // Treat an enum type as its underlying type.
4709 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4710 Ty = EnumTy->getDecl()->getIntegerType();
4711
Tim Northovera2ee4332014-03-29 15:09:45 +00004712 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4713 ? ABIArgInfo::getExtend()
4714 : ABIArgInfo::getDirect());
4715 }
4716
4717 // Structures with either a non-trivial destructor or a non-trivial
4718 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004719 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004720 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4721 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004722 }
4723
4724 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4725 // elsewhere for GNU compatibility.
4726 if (isEmptyRecord(getContext(), Ty, true)) {
4727 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4728 return ABIArgInfo::getIgnore();
4729
Tim Northovera2ee4332014-03-29 15:09:45 +00004730 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4731 }
4732
4733 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004734 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004735 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004736 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004737 return ABIArgInfo::getDirect(
4738 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004739 }
4740
4741 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4742 uint64_t Size = getContext().getTypeSize(Ty);
4743 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004744 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4745 // same size and alignment.
4746 if (getTarget().isRenderScriptTarget()) {
4747 return coerceToIntArray(Ty, getContext(), getVMContext());
4748 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004749 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004750 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004751
Tim Northovera2ee4332014-03-29 15:09:45 +00004752 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4753 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004754 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004755 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4756 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4757 }
4758 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4759 }
4760
John McCall7f416cc2015-09-08 08:05:57 +00004761 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004762}
4763
Tim Northover573cbee2014-05-24 12:52:07 +00004764ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004765 if (RetTy->isVoidType())
4766 return ABIArgInfo::getIgnore();
4767
4768 // Large vector types should be returned via memory.
4769 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004770 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004771
4772 if (!isAggregateTypeForABI(RetTy)) {
4773 // Treat an enum type as its underlying type.
4774 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4775 RetTy = EnumTy->getDecl()->getIntegerType();
4776
Tim Northover4dab6982014-04-18 13:46:08 +00004777 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4778 ? ABIArgInfo::getExtend()
4779 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004780 }
4781
Tim Northovera2ee4332014-03-29 15:09:45 +00004782 if (isEmptyRecord(getContext(), RetTy, true))
4783 return ABIArgInfo::getIgnore();
4784
Craig Topper8a13c412014-05-21 05:09:00 +00004785 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004786 uint64_t Members = 0;
4787 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004788 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4789 return ABIArgInfo::getDirect();
4790
4791 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4792 uint64_t Size = getContext().getTypeSize(RetTy);
4793 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004794 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4795 // same size and alignment.
4796 if (getTarget().isRenderScriptTarget()) {
4797 return coerceToIntArray(RetTy, getContext(), getVMContext());
4798 }
Pete Cooper635b5092015-04-17 22:16:24 +00004799 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004800 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004801
4802 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4803 // For aggregates with 16-byte alignment, we use i128.
4804 if (Alignment < 128 && Size == 128) {
4805 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4806 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4807 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004808 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4809 }
4810
John McCall7f416cc2015-09-08 08:05:57 +00004811 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004812}
4813
Tim Northover573cbee2014-05-24 12:52:07 +00004814/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4815bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004816 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4817 // Check whether VT is legal.
4818 unsigned NumElements = VT->getNumElements();
4819 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004820 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004821 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004822 return true;
4823 return Size != 64 && (Size != 128 || NumElements == 1);
4824 }
4825 return false;
4826}
4827
Reid Klecknere9f6a712014-10-31 17:10:41 +00004828bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4829 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4830 // point type or a short-vector type. This is the same as the 32-bit ABI,
4831 // but with the difference that any floating-point type is allowed,
4832 // including __fp16.
4833 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4834 if (BT->isFloatingPoint())
4835 return true;
4836 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4837 unsigned VecSize = getContext().getTypeSize(VT);
4838 if (VecSize == 64 || VecSize == 128)
4839 return true;
4840 }
4841 return false;
4842}
4843
4844bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4845 uint64_t Members) const {
4846 return Members <= 4;
4847}
4848
John McCall7f416cc2015-09-08 08:05:57 +00004849Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004850 QualType Ty,
4851 CodeGenFunction &CGF) const {
4852 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004853 bool IsIndirect = AI.isIndirect();
4854
Tim Northoverb047bfa2014-11-27 21:02:49 +00004855 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4856 if (IsIndirect)
4857 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4858 else if (AI.getCoerceToType())
4859 BaseTy = AI.getCoerceToType();
4860
4861 unsigned NumRegs = 1;
4862 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4863 BaseTy = ArrTy->getElementType();
4864 NumRegs = ArrTy->getNumElements();
4865 }
4866 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4867
Tim Northovera2ee4332014-03-29 15:09:45 +00004868 // The AArch64 va_list type and handling is specified in the Procedure Call
4869 // Standard, section B.4:
4870 //
4871 // struct {
4872 // void *__stack;
4873 // void *__gr_top;
4874 // void *__vr_top;
4875 // int __gr_offs;
4876 // int __vr_offs;
4877 // };
4878
4879 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4880 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4881 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4882 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004883
John McCall7f416cc2015-09-08 08:05:57 +00004884 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4885 CharUnits TyAlign = TyInfo.second;
4886
4887 Address reg_offs_p = Address::invalid();
4888 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004889 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004890 CharUnits reg_top_offset;
4891 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004892 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004893 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004894 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004895 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4896 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004897 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4898 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004899 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004900 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004901 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004902 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004903 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004904 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4905 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004906 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4907 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004908 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004909 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004910 }
4911
4912 //=======================================
4913 // Find out where argument was passed
4914 //=======================================
4915
4916 // If reg_offs >= 0 we're already using the stack for this type of
4917 // argument. We don't want to keep updating reg_offs (in case it overflows,
4918 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4919 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004920 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004921 UsingStack = CGF.Builder.CreateICmpSGE(
4922 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4923
4924 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4925
4926 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004927 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004928 CGF.EmitBlock(MaybeRegBlock);
4929
4930 // Integer arguments may need to correct register alignment (for example a
4931 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4932 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004933 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4934 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004935
4936 reg_offs = CGF.Builder.CreateAdd(
4937 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4938 "align_regoffs");
4939 reg_offs = CGF.Builder.CreateAnd(
4940 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4941 "aligned_regoffs");
4942 }
4943
4944 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004945 // The fact that this is done unconditionally reflects the fact that
4946 // allocating an argument to the stack also uses up all the remaining
4947 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004948 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004949 NewOffset = CGF.Builder.CreateAdd(
4950 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4951 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4952
4953 // Now we're in a position to decide whether this argument really was in
4954 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004955 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004956 InRegs = CGF.Builder.CreateICmpSLE(
4957 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4958
4959 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4960
4961 //=======================================
4962 // Argument was in registers
4963 //=======================================
4964
4965 // Now we emit the code for if the argument was originally passed in
4966 // registers. First start the appropriate block:
4967 CGF.EmitBlock(InRegBlock);
4968
John McCall7f416cc2015-09-08 08:05:57 +00004969 llvm::Value *reg_top = nullptr;
4970 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4971 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004972 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004973 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4974 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4975 Address RegAddr = Address::invalid();
4976 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004977
4978 if (IsIndirect) {
4979 // If it's been passed indirectly (actually a struct), whatever we find from
4980 // stored registers or on the stack will actually be a struct **.
4981 MemTy = llvm::PointerType::getUnqual(MemTy);
4982 }
4983
Craig Topper8a13c412014-05-21 05:09:00 +00004984 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004985 uint64_t NumMembers = 0;
4986 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004987 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004988 // Homogeneous aggregates passed in registers will have their elements split
4989 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4990 // qN+1, ...). We reload and store into a temporary local variable
4991 // contiguously.
4992 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004993 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004994 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4995 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004996 Address Tmp = CGF.CreateTempAlloca(HFATy,
4997 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004998
John McCall7f416cc2015-09-08 08:05:57 +00004999 // On big-endian platforms, the value will be right-aligned in its slot.
5000 int Offset = 0;
5001 if (CGF.CGM.getDataLayout().isBigEndian() &&
5002 BaseTyInfo.first.getQuantity() < 16)
5003 Offset = 16 - BaseTyInfo.first.getQuantity();
5004
Tim Northovera2ee4332014-03-29 15:09:45 +00005005 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005006 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5007 Address LoadAddr =
5008 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5009 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5010
5011 Address StoreAddr =
5012 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005013
5014 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5015 CGF.Builder.CreateStore(Elem, StoreAddr);
5016 }
5017
John McCall7f416cc2015-09-08 08:05:57 +00005018 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005019 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005020 // Otherwise the object is contiguous in memory.
5021
5022 // It might be right-aligned in its slot.
5023 CharUnits SlotSize = BaseAddr.getAlignment();
5024 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005025 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005026 TyInfo.first < SlotSize) {
5027 CharUnits Offset = SlotSize - TyInfo.first;
5028 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005029 }
5030
John McCall7f416cc2015-09-08 08:05:57 +00005031 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005032 }
5033
5034 CGF.EmitBranch(ContBlock);
5035
5036 //=======================================
5037 // Argument was on the stack
5038 //=======================================
5039 CGF.EmitBlock(OnStackBlock);
5040
John McCall7f416cc2015-09-08 08:05:57 +00005041 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5042 CharUnits::Zero(), "stack_p");
5043 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005044
John McCall7f416cc2015-09-08 08:05:57 +00005045 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005046 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005047 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5048 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005049
John McCall7f416cc2015-09-08 08:05:57 +00005050 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005051
John McCall7f416cc2015-09-08 08:05:57 +00005052 OnStackPtr = CGF.Builder.CreateAdd(
5053 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005054 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005055 OnStackPtr = CGF.Builder.CreateAnd(
5056 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005057 "align_stack");
5058
John McCall7f416cc2015-09-08 08:05:57 +00005059 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005060 }
John McCall7f416cc2015-09-08 08:05:57 +00005061 Address OnStackAddr(OnStackPtr,
5062 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005063
John McCall7f416cc2015-09-08 08:05:57 +00005064 // All stack slots are multiples of 8 bytes.
5065 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5066 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005067 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005068 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005069 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005070 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005071
John McCall7f416cc2015-09-08 08:05:57 +00005072 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005073 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005074 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005075
5076 // Write the new value of __stack for the next call to va_arg
5077 CGF.Builder.CreateStore(NewStack, stack_p);
5078
5079 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005080 TyInfo.first < StackSlotSize) {
5081 CharUnits Offset = StackSlotSize - TyInfo.first;
5082 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005083 }
5084
John McCall7f416cc2015-09-08 08:05:57 +00005085 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005086
5087 CGF.EmitBranch(ContBlock);
5088
5089 //=======================================
5090 // Tidy up
5091 //=======================================
5092 CGF.EmitBlock(ContBlock);
5093
John McCall7f416cc2015-09-08 08:05:57 +00005094 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5095 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005096
5097 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005098 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5099 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005100
5101 return ResAddr;
5102}
5103
John McCall7f416cc2015-09-08 08:05:57 +00005104Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5105 CodeGenFunction &CGF) const {
5106 // The backend's lowering doesn't support va_arg for aggregates or
5107 // illegal vector types. Lower VAArg here for these cases and use
5108 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005109 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005110 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005111
John McCall7f416cc2015-09-08 08:05:57 +00005112 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005113
John McCall7f416cc2015-09-08 08:05:57 +00005114 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005115 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005116 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5117 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5118 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005119 }
5120
John McCall7f416cc2015-09-08 08:05:57 +00005121 // The size of the actual thing passed, which might end up just
5122 // being a pointer for indirect types.
5123 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5124
5125 // Arguments bigger than 16 bytes which aren't homogeneous
5126 // aggregates should be passed indirectly.
5127 bool IsIndirect = false;
5128 if (TyInfo.first.getQuantity() > 16) {
5129 const Type *Base = nullptr;
5130 uint64_t Members = 0;
5131 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005132 }
5133
John McCall7f416cc2015-09-08 08:05:57 +00005134 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5135 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005136}
5137
5138//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005139// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005140//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005141
5142namespace {
5143
John McCall12f23522016-04-04 18:33:08 +00005144class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005145public:
5146 enum ABIKind {
5147 APCS = 0,
5148 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005149 AAPCS_VFP = 2,
5150 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005151 };
5152
5153private:
5154 ABIKind Kind;
5155
5156public:
John McCall12f23522016-04-04 18:33:08 +00005157 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5158 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005159 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005160 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005161
John McCall3480ef22011-08-30 01:42:09 +00005162 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005163 switch (getTarget().getTriple().getEnvironment()) {
5164 case llvm::Triple::Android:
5165 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005166 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005167 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005168 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005169 case llvm::Triple::MuslEABI:
5170 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005171 return true;
5172 default:
5173 return false;
5174 }
John McCall3480ef22011-08-30 01:42:09 +00005175 }
5176
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005177 bool isEABIHF() const {
5178 switch (getTarget().getTriple().getEnvironment()) {
5179 case llvm::Triple::EABIHF:
5180 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005181 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005182 return true;
5183 default:
5184 return false;
5185 }
5186 }
5187
Daniel Dunbar020daa92009-09-12 01:00:39 +00005188 ABIKind getABIKind() const { return Kind; }
5189
Tim Northovera484bc02013-10-01 14:34:25 +00005190private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005191 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005192 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005193 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005194
Reid Klecknere9f6a712014-10-31 17:10:41 +00005195 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5196 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5197 uint64_t Members) const override;
5198
Craig Topper4f12f102014-03-12 06:41:41 +00005199 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005200
John McCall7f416cc2015-09-08 08:05:57 +00005201 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5202 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005203
5204 llvm::CallingConv::ID getLLVMDefaultCC() const;
5205 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005206 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005207
5208 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5209 ArrayRef<llvm::Type*> scalars,
5210 bool asReturnValue) const override {
5211 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5212 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005213 bool isSwiftErrorInRegister() const override {
5214 return true;
5215 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005216};
5217
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005218class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5219public:
Chris Lattner2b037972010-07-29 02:01:43 +00005220 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5221 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005222
John McCall3480ef22011-08-30 01:42:09 +00005223 const ARMABIInfo &getABIInfo() const {
5224 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5225 }
5226
Craig Topper4f12f102014-03-12 06:41:41 +00005227 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005228 return 13;
5229 }
Roman Divackyc1617352011-05-18 19:36:54 +00005230
Craig Topper4f12f102014-03-12 06:41:41 +00005231 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005232 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5233 }
5234
Roman Divackyc1617352011-05-18 19:36:54 +00005235 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005236 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005237 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005238
5239 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005240 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005241 return false;
5242 }
John McCall3480ef22011-08-30 01:42:09 +00005243
Craig Topper4f12f102014-03-12 06:41:41 +00005244 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005245 if (getABIInfo().isEABI()) return 88;
5246 return TargetCodeGenInfo::getSizeOfUnwindException();
5247 }
Tim Northovera484bc02013-10-01 14:34:25 +00005248
Eric Christopher162c91c2015-06-05 22:03:00 +00005249 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005250 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005251 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005252 if (!FD)
5253 return;
5254
5255 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5256 if (!Attr)
5257 return;
5258
5259 const char *Kind;
5260 switch (Attr->getInterrupt()) {
5261 case ARMInterruptAttr::Generic: Kind = ""; break;
5262 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5263 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5264 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5265 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5266 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5267 }
5268
5269 llvm::Function *Fn = cast<llvm::Function>(GV);
5270
5271 Fn->addFnAttr("interrupt", Kind);
5272
Tim Northover5627d392015-10-30 16:30:45 +00005273 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5274 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005275 return;
5276
5277 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5278 // however this is not necessarily true on taking any interrupt. Instruct
5279 // the backend to perform a realignment as part of the function prologue.
5280 llvm::AttrBuilder B;
5281 B.addStackAlignmentAttr(8);
5282 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5283 llvm::AttributeSet::get(CGM.getLLVMContext(),
5284 llvm::AttributeSet::FunctionIndex,
5285 B));
5286 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005287};
5288
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005289class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005290public:
5291 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5292 : ARMTargetCodeGenInfo(CGT, K) {}
5293
Eric Christopher162c91c2015-06-05 22:03:00 +00005294 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005295 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005296
5297 void getDependentLibraryOption(llvm::StringRef Lib,
5298 llvm::SmallString<24> &Opt) const override {
5299 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5300 }
5301
5302 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5303 llvm::SmallString<32> &Opt) const override {
5304 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5305 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005306};
5307
Eric Christopher162c91c2015-06-05 22:03:00 +00005308void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005309 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005310 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005311 addStackProbeSizeTargetAttribute(D, GV, CGM);
5312}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005313}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005314
Chris Lattner22326a12010-07-29 02:31:05 +00005315void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005316 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005317 FI.getReturnInfo() =
5318 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005319
Tim Northoverbc784d12015-02-24 17:22:40 +00005320 for (auto &I : FI.arguments())
5321 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005322
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005323 // Always honor user-specified calling convention.
5324 if (FI.getCallingConvention() != llvm::CallingConv::C)
5325 return;
5326
John McCall882987f2013-02-28 19:01:20 +00005327 llvm::CallingConv::ID cc = getRuntimeCC();
5328 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005329 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005330}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005331
John McCall882987f2013-02-28 19:01:20 +00005332/// Return the default calling convention that LLVM will use.
5333llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5334 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005335 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005336 return llvm::CallingConv::ARM_AAPCS_VFP;
5337 else if (isEABI())
5338 return llvm::CallingConv::ARM_AAPCS;
5339 else
5340 return llvm::CallingConv::ARM_APCS;
5341}
5342
5343/// Return the calling convention that our ABI would like us to use
5344/// as the C calling convention.
5345llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005346 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005347 case APCS: return llvm::CallingConv::ARM_APCS;
5348 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5349 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005350 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005351 }
John McCall882987f2013-02-28 19:01:20 +00005352 llvm_unreachable("bad ABI kind");
5353}
5354
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005355void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005356 assert(getRuntimeCC() == llvm::CallingConv::C);
5357
5358 // Don't muddy up the IR with a ton of explicit annotations if
5359 // they'd just match what LLVM will infer from the triple.
5360 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5361 if (abiCC != getLLVMDefaultCC())
5362 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005363
Tim Northover5627d392015-10-30 16:30:45 +00005364 // AAPCS apparently requires runtime support functions to be soft-float, but
5365 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5366 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5367 switch (getABIKind()) {
5368 case APCS:
5369 case AAPCS16_VFP:
5370 if (abiCC != getLLVMDefaultCC())
5371 BuiltinCC = abiCC;
5372 break;
5373 case AAPCS:
5374 case AAPCS_VFP:
5375 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5376 break;
5377 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005378}
5379
Tim Northoverbc784d12015-02-24 17:22:40 +00005380ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5381 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005382 // 6.1.2.1 The following argument types are VFP CPRCs:
5383 // A single-precision floating-point type (including promoted
5384 // half-precision types); A double-precision floating-point type;
5385 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5386 // with a Base Type of a single- or double-precision floating-point type,
5387 // 64-bit containerized vectors or 128-bit containerized vectors with one
5388 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005389 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005390
Reid Klecknerb1be6832014-11-15 01:41:41 +00005391 Ty = useFirstFieldIfTransparentUnion(Ty);
5392
Manman Renfef9e312012-10-16 19:18:39 +00005393 // Handle illegal vector types here.
5394 if (isIllegalVectorType(Ty)) {
5395 uint64_t Size = getContext().getTypeSize(Ty);
5396 if (Size <= 32) {
5397 llvm::Type *ResType =
5398 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005399 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005400 }
5401 if (Size == 64) {
5402 llvm::Type *ResType = llvm::VectorType::get(
5403 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005404 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005405 }
5406 if (Size == 128) {
5407 llvm::Type *ResType = llvm::VectorType::get(
5408 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005409 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005410 }
John McCall7f416cc2015-09-08 08:05:57 +00005411 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005412 }
5413
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005414 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5415 // unspecified. This is not done for OpenCL as it handles the half type
5416 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005417 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005418 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5419 llvm::Type::getFloatTy(getVMContext()) :
5420 llvm::Type::getInt32Ty(getVMContext());
5421 return ABIArgInfo::getDirect(ResType);
5422 }
5423
John McCalla1dee5302010-08-22 10:59:02 +00005424 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005425 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005426 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005427 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005428 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005429
Tim Northover5a1558e2014-11-07 22:30:50 +00005430 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5431 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005432 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005433
Oliver Stannard405bded2014-02-11 09:25:50 +00005434 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005435 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005436 }
Tim Northover1060eae2013-06-21 22:49:34 +00005437
Daniel Dunbar09d33622009-09-14 21:54:03 +00005438 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005439 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005440 return ABIArgInfo::getIgnore();
5441
Tim Northover5a1558e2014-11-07 22:30:50 +00005442 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005443 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5444 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005445 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005446 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005447 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005448 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005449 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005450 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005451 }
Tim Northover5627d392015-10-30 16:30:45 +00005452 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5453 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5454 // this convention even for a variadic function: the backend will use GPRs
5455 // if needed.
5456 const Type *Base = nullptr;
5457 uint64_t Members = 0;
5458 if (isHomogeneousAggregate(Ty, Base, Members)) {
5459 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5460 llvm::Type *Ty =
5461 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5462 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5463 }
5464 }
5465
5466 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5467 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5468 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5469 // bigger than 128-bits, they get placed in space allocated by the caller,
5470 // and a pointer is passed.
5471 return ABIArgInfo::getIndirect(
5472 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005473 }
5474
Manman Ren6c30e132012-08-13 21:23:55 +00005475 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005476 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5477 // most 8-byte. We realign the indirect argument if type alignment is bigger
5478 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005479 uint64_t ABIAlign = 4;
5480 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5481 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005482 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005483 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005484
Manman Ren8cd99812012-11-06 04:58:01 +00005485 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005486 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005487 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5488 /*ByVal=*/true,
5489 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005490 }
5491
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005492 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5493 // same size and alignment.
5494 if (getTarget().isRenderScriptTarget()) {
5495 return coerceToIntArray(Ty, getContext(), getVMContext());
5496 }
5497
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005498 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005499 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005500 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005501 // FIXME: Try to match the types of the arguments more accurately where
5502 // we can.
5503 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005504 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5505 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005506 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005507 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5508 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005509 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005510
Tim Northover5a1558e2014-11-07 22:30:50 +00005511 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005512}
5513
Chris Lattner458b2aa2010-07-29 02:16:43 +00005514static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005515 llvm::LLVMContext &VMContext) {
5516 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5517 // is called integer-like if its size is less than or equal to one word, and
5518 // the offset of each of its addressable sub-fields is zero.
5519
5520 uint64_t Size = Context.getTypeSize(Ty);
5521
5522 // Check that the type fits in a word.
5523 if (Size > 32)
5524 return false;
5525
5526 // FIXME: Handle vector types!
5527 if (Ty->isVectorType())
5528 return false;
5529
Daniel Dunbard53bac72009-09-14 02:20:34 +00005530 // Float types are never treated as "integer like".
5531 if (Ty->isRealFloatingType())
5532 return false;
5533
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005534 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005535 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005536 return true;
5537
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005538 // Small complex integer types are "integer like".
5539 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5540 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005541
5542 // Single element and zero sized arrays should be allowed, by the definition
5543 // above, but they are not.
5544
5545 // Otherwise, it must be a record type.
5546 const RecordType *RT = Ty->getAs<RecordType>();
5547 if (!RT) return false;
5548
5549 // Ignore records with flexible arrays.
5550 const RecordDecl *RD = RT->getDecl();
5551 if (RD->hasFlexibleArrayMember())
5552 return false;
5553
5554 // Check that all sub-fields are at offset 0, and are themselves "integer
5555 // like".
5556 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5557
5558 bool HadField = false;
5559 unsigned idx = 0;
5560 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5561 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005562 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005563
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005564 // Bit-fields are not addressable, we only need to verify they are "integer
5565 // like". We still have to disallow a subsequent non-bitfield, for example:
5566 // struct { int : 0; int x }
5567 // is non-integer like according to gcc.
5568 if (FD->isBitField()) {
5569 if (!RD->isUnion())
5570 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005571
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005572 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5573 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005574
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005575 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005576 }
5577
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005578 // Check if this field is at offset 0.
5579 if (Layout.getFieldOffset(idx) != 0)
5580 return false;
5581
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005582 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5583 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005584
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005585 // Only allow at most one field in a structure. This doesn't match the
5586 // wording above, but follows gcc in situations with a field following an
5587 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005588 if (!RD->isUnion()) {
5589 if (HadField)
5590 return false;
5591
5592 HadField = true;
5593 }
5594 }
5595
5596 return true;
5597}
5598
Oliver Stannard405bded2014-02-11 09:25:50 +00005599ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5600 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005601 bool IsEffectivelyAAPCS_VFP =
5602 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005603
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005604 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005605 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005606
Daniel Dunbar19964db2010-09-23 01:54:32 +00005607 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005608 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005609 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005610 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005611
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005612 // __fp16 gets returned as if it were an int or float, but with the top 16
5613 // bits unspecified. This is not done for OpenCL as it handles the half type
5614 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005615 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005616 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5617 llvm::Type::getFloatTy(getVMContext()) :
5618 llvm::Type::getInt32Ty(getVMContext());
5619 return ABIArgInfo::getDirect(ResType);
5620 }
5621
John McCalla1dee5302010-08-22 10:59:02 +00005622 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005623 // Treat an enum type as its underlying type.
5624 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5625 RetTy = EnumTy->getDecl()->getIntegerType();
5626
Tim Northover5a1558e2014-11-07 22:30:50 +00005627 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5628 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005629 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005630
5631 // Are we following APCS?
5632 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005633 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005634 return ABIArgInfo::getIgnore();
5635
Daniel Dunbareedf1512010-02-01 23:31:19 +00005636 // Complex types are all returned as packed integers.
5637 //
5638 // FIXME: Consider using 2 x vector types if the back end handles them
5639 // correctly.
5640 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005641 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5642 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005643
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005644 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005645 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005646 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005647 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005648 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005649 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005650 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005651 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5652 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005653 }
5654
5655 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005656 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005657 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005658
5659 // Otherwise this is an AAPCS variant.
5660
Chris Lattner458b2aa2010-07-29 02:16:43 +00005661 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005662 return ABIArgInfo::getIgnore();
5663
Bob Wilson1d9269a2011-11-02 04:51:36 +00005664 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005665 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005666 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005667 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005668 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005669 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005670 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005671 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005672 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005673 }
5674
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005675 // Aggregates <= 4 bytes are returned in r0; other aggregates
5676 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005677 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005678 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005679 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5680 // same size and alignment.
5681 if (getTarget().isRenderScriptTarget()) {
5682 return coerceToIntArray(RetTy, getContext(), getVMContext());
5683 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005684 if (getDataLayout().isBigEndian())
5685 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005686 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005687
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005688 // Return in the smallest viable integer type.
5689 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005690 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005691 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005692 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5693 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005694 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5695 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5696 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005697 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005698 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005699 }
5700
John McCall7f416cc2015-09-08 08:05:57 +00005701 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005702}
5703
Manman Renfef9e312012-10-16 19:18:39 +00005704/// isIllegalVector - check whether Ty is an illegal vector type.
5705bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005706 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5707 if (isAndroid()) {
5708 // Android shipped using Clang 3.1, which supported a slightly different
5709 // vector ABI. The primary differences were that 3-element vector types
5710 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5711 // accepts that legacy behavior for Android only.
5712 // Check whether VT is legal.
5713 unsigned NumElements = VT->getNumElements();
5714 // NumElements should be power of 2 or equal to 3.
5715 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5716 return true;
5717 } else {
5718 // Check whether VT is legal.
5719 unsigned NumElements = VT->getNumElements();
5720 uint64_t Size = getContext().getTypeSize(VT);
5721 // NumElements should be power of 2.
5722 if (!llvm::isPowerOf2_32(NumElements))
5723 return true;
5724 // Size should be greater than 32 bits.
5725 return Size <= 32;
5726 }
Manman Renfef9e312012-10-16 19:18:39 +00005727 }
5728 return false;
5729}
5730
Reid Klecknere9f6a712014-10-31 17:10:41 +00005731bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5732 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5733 // double, or 64-bit or 128-bit vectors.
5734 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5735 if (BT->getKind() == BuiltinType::Float ||
5736 BT->getKind() == BuiltinType::Double ||
5737 BT->getKind() == BuiltinType::LongDouble)
5738 return true;
5739 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5740 unsigned VecSize = getContext().getTypeSize(VT);
5741 if (VecSize == 64 || VecSize == 128)
5742 return true;
5743 }
5744 return false;
5745}
5746
5747bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5748 uint64_t Members) const {
5749 return Members <= 4;
5750}
5751
John McCall7f416cc2015-09-08 08:05:57 +00005752Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5753 QualType Ty) const {
5754 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005755
John McCall7f416cc2015-09-08 08:05:57 +00005756 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005757 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005758 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5759 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5760 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005761 }
5762
John McCall7f416cc2015-09-08 08:05:57 +00005763 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5764 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005765
John McCall7f416cc2015-09-08 08:05:57 +00005766 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5767 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005768 const Type *Base = nullptr;
5769 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005770 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5771 IsIndirect = true;
5772
Tim Northover5627d392015-10-30 16:30:45 +00005773 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5774 // allocated by the caller.
5775 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5776 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5777 !isHomogeneousAggregate(Ty, Base, Members)) {
5778 IsIndirect = true;
5779
John McCall7f416cc2015-09-08 08:05:57 +00005780 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005781 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5782 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005783 // Our callers should be prepared to handle an under-aligned address.
5784 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5785 getABIKind() == ARMABIInfo::AAPCS) {
5786 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5787 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005788 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5789 // ARMv7k allows type alignment up to 16 bytes.
5790 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5791 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005792 } else {
5793 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005794 }
John McCall7f416cc2015-09-08 08:05:57 +00005795 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005796
John McCall7f416cc2015-09-08 08:05:57 +00005797 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5798 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005799}
5800
Chris Lattner0cf24192010-06-28 20:05:43 +00005801//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005802// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005803//===----------------------------------------------------------------------===//
5804
5805namespace {
5806
Justin Holewinski83e96682012-05-24 17:43:12 +00005807class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005808public:
Justin Holewinski36837432013-03-30 14:38:24 +00005809 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005810
5811 ABIArgInfo classifyReturnType(QualType RetTy) const;
5812 ABIArgInfo classifyArgumentType(QualType Ty) const;
5813
Craig Topper4f12f102014-03-12 06:41:41 +00005814 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005815 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5816 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005817};
5818
Justin Holewinski83e96682012-05-24 17:43:12 +00005819class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005820public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005821 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5822 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005823
Eric Christopher162c91c2015-06-05 22:03:00 +00005824 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005825 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005826private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005827 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5828 // resulting MDNode to the nvvm.annotations MDNode.
5829 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005830};
5831
Justin Holewinski83e96682012-05-24 17:43:12 +00005832ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005833 if (RetTy->isVoidType())
5834 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005835
5836 // note: this is different from default ABI
5837 if (!RetTy->isScalarType())
5838 return ABIArgInfo::getDirect();
5839
5840 // Treat an enum type as its underlying type.
5841 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5842 RetTy = EnumTy->getDecl()->getIntegerType();
5843
5844 return (RetTy->isPromotableIntegerType() ?
5845 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005846}
5847
Justin Holewinski83e96682012-05-24 17:43:12 +00005848ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005849 // Treat an enum type as its underlying type.
5850 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5851 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005852
Eli Bendersky95338a02014-10-29 13:43:21 +00005853 // Return aggregates type as indirect by value
5854 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005855 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005856
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005857 return (Ty->isPromotableIntegerType() ?
5858 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005859}
5860
Justin Holewinski83e96682012-05-24 17:43:12 +00005861void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005862 if (!getCXXABI().classifyReturnType(FI))
5863 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005864 for (auto &I : FI.arguments())
5865 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005866
5867 // Always honor user-specified calling convention.
5868 if (FI.getCallingConvention() != llvm::CallingConv::C)
5869 return;
5870
John McCall882987f2013-02-28 19:01:20 +00005871 FI.setEffectiveCallingConvention(getRuntimeCC());
5872}
5873
John McCall7f416cc2015-09-08 08:05:57 +00005874Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5875 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005876 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005877}
5878
Justin Holewinski83e96682012-05-24 17:43:12 +00005879void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005880setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005881 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005882 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005883 if (!FD) return;
5884
5885 llvm::Function *F = cast<llvm::Function>(GV);
5886
5887 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005888 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005889 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005890 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005891 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005892 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005893 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5894 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005895 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005896 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005897 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005898 }
Justin Holewinski38031972011-10-05 17:58:44 +00005899
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005900 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005901 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005902 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005903 // __global__ functions cannot be called from the device, we do not
5904 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005905 if (FD->hasAttr<CUDAGlobalAttr>()) {
5906 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5907 addNVVMMetadata(F, "kernel", 1);
5908 }
Artem Belevich7093e402015-04-21 22:55:54 +00005909 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005910 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005911 llvm::APSInt MaxThreads(32);
5912 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5913 if (MaxThreads > 0)
5914 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5915
5916 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5917 // not specified in __launch_bounds__ or if the user specified a 0 value,
5918 // we don't have to add a PTX directive.
5919 if (Attr->getMinBlocks()) {
5920 llvm::APSInt MinBlocks(32);
5921 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5922 if (MinBlocks > 0)
5923 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5924 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005925 }
5926 }
Justin Holewinski38031972011-10-05 17:58:44 +00005927 }
5928}
5929
Eli Benderskye06a2c42014-04-15 16:57:05 +00005930void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5931 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005932 llvm::Module *M = F->getParent();
5933 llvm::LLVMContext &Ctx = M->getContext();
5934
5935 // Get "nvvm.annotations" metadata node
5936 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5937
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005938 llvm::Metadata *MDVals[] = {
5939 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5940 llvm::ConstantAsMetadata::get(
5941 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005942 // Append metadata to nvvm.annotations
5943 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5944}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005945}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005946
5947//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005948// SystemZ ABI Implementation
5949//===----------------------------------------------------------------------===//
5950
5951namespace {
5952
Bryan Chane3f1ed52016-04-28 13:56:43 +00005953class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005954 bool HasVector;
5955
Ulrich Weigand47445072013-05-06 16:26:41 +00005956public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005957 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00005958 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005959
5960 bool isPromotableIntegerType(QualType Ty) const;
5961 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005962 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005963 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005964 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005965
5966 ABIArgInfo classifyReturnType(QualType RetTy) const;
5967 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5968
Craig Topper4f12f102014-03-12 06:41:41 +00005969 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005970 if (!getCXXABI().classifyReturnType(FI))
5971 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005972 for (auto &I : FI.arguments())
5973 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005974 }
5975
John McCall7f416cc2015-09-08 08:05:57 +00005976 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5977 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00005978
5979 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5980 ArrayRef<llvm::Type*> scalars,
5981 bool asReturnValue) const override {
5982 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5983 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005984 bool isSwiftErrorInRegister() const override {
5985 return true;
5986 }
Ulrich Weigand47445072013-05-06 16:26:41 +00005987};
5988
5989class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5990public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005991 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5992 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005993};
5994
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005995}
Ulrich Weigand47445072013-05-06 16:26:41 +00005996
5997bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5998 // Treat an enum type as its underlying type.
5999 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6000 Ty = EnumTy->getDecl()->getIntegerType();
6001
6002 // Promotable integer types are required to be promoted by the ABI.
6003 if (Ty->isPromotableIntegerType())
6004 return true;
6005
6006 // 32-bit values must also be promoted.
6007 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6008 switch (BT->getKind()) {
6009 case BuiltinType::Int:
6010 case BuiltinType::UInt:
6011 return true;
6012 default:
6013 return false;
6014 }
6015 return false;
6016}
6017
6018bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006019 return (Ty->isAnyComplexType() ||
6020 Ty->isVectorType() ||
6021 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006022}
6023
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006024bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6025 return (HasVector &&
6026 Ty->isVectorType() &&
6027 getContext().getTypeSize(Ty) <= 128);
6028}
6029
Ulrich Weigand47445072013-05-06 16:26:41 +00006030bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6031 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6032 switch (BT->getKind()) {
6033 case BuiltinType::Float:
6034 case BuiltinType::Double:
6035 return true;
6036 default:
6037 return false;
6038 }
6039
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006040 return false;
6041}
6042
6043QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006044 if (const RecordType *RT = Ty->getAsStructureType()) {
6045 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006046 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006047
6048 // If this is a C++ record, check the bases first.
6049 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006050 for (const auto &I : CXXRD->bases()) {
6051 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006052
6053 // Empty bases don't affect things either way.
6054 if (isEmptyRecord(getContext(), Base, true))
6055 continue;
6056
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006057 if (!Found.isNull())
6058 return Ty;
6059 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006060 }
6061
6062 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006063 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006064 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006065 // Unlike isSingleElementStruct(), empty structure and array fields
6066 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006067 if (getContext().getLangOpts().CPlusPlus &&
6068 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6069 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006070
6071 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006072 // Nested structures still do though.
6073 if (!Found.isNull())
6074 return Ty;
6075 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006076 }
6077
6078 // Unlike isSingleElementStruct(), trailing padding is allowed.
6079 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006080 if (!Found.isNull())
6081 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006082 }
6083
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006084 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006085}
6086
John McCall7f416cc2015-09-08 08:05:57 +00006087Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6088 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006089 // Assume that va_list type is correct; should be pointer to LLVM type:
6090 // struct {
6091 // i64 __gpr;
6092 // i64 __fpr;
6093 // i8 *__overflow_arg_area;
6094 // i8 *__reg_save_area;
6095 // };
6096
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006097 // Every non-vector argument occupies 8 bytes and is passed by preference
6098 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6099 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006100 Ty = getContext().getCanonicalType(Ty);
6101 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006102 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006103 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006104 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006105 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006106 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006107 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006108 CharUnits UnpaddedSize;
6109 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006110 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006111 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6112 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006113 } else {
6114 if (AI.getCoerceToType())
6115 ArgTy = AI.getCoerceToType();
6116 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006117 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006118 UnpaddedSize = TyInfo.first;
6119 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006120 }
John McCall7f416cc2015-09-08 08:05:57 +00006121 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6122 if (IsVector && UnpaddedSize > PaddedSize)
6123 PaddedSize = CharUnits::fromQuantity(16);
6124 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006125
John McCall7f416cc2015-09-08 08:05:57 +00006126 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006127
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006128 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006129 llvm::Value *PaddedSizeV =
6130 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006131
6132 if (IsVector) {
6133 // Work out the address of a vector argument on the stack.
6134 // Vector arguments are always passed in the high bits of a
6135 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006136 Address OverflowArgAreaPtr =
6137 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006138 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006139 Address OverflowArgArea =
6140 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6141 TyInfo.second);
6142 Address MemAddr =
6143 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006144
6145 // Update overflow_arg_area_ptr pointer
6146 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006147 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6148 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006149 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6150
6151 return MemAddr;
6152 }
6153
John McCall7f416cc2015-09-08 08:05:57 +00006154 assert(PaddedSize.getQuantity() == 8);
6155
6156 unsigned MaxRegs, RegCountField, RegSaveIndex;
6157 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006158 if (InFPRs) {
6159 MaxRegs = 4; // Maximum of 4 FPR arguments
6160 RegCountField = 1; // __fpr
6161 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006162 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006163 } else {
6164 MaxRegs = 5; // Maximum of 5 GPR arguments
6165 RegCountField = 0; // __gpr
6166 RegSaveIndex = 2; // save offset for r2
6167 RegPadding = Padding; // values are passed in the low bits of a GPR
6168 }
6169
John McCall7f416cc2015-09-08 08:05:57 +00006170 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6171 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6172 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006173 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006174 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6175 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006176 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006177
6178 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6179 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6180 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6181 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6182
6183 // Emit code to load the value if it was passed in registers.
6184 CGF.EmitBlock(InRegBlock);
6185
6186 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006187 llvm::Value *ScaledRegCount =
6188 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6189 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006190 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6191 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006192 llvm::Value *RegOffset =
6193 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006194 Address RegSaveAreaPtr =
6195 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6196 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006197 llvm::Value *RegSaveArea =
6198 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006199 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6200 "raw_reg_addr"),
6201 PaddedSize);
6202 Address RegAddr =
6203 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006204
6205 // Update the register count
6206 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6207 llvm::Value *NewRegCount =
6208 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6209 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6210 CGF.EmitBranch(ContBlock);
6211
6212 // Emit code to load the value if it was passed in memory.
6213 CGF.EmitBlock(InMemBlock);
6214
6215 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006216 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6217 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6218 Address OverflowArgArea =
6219 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6220 PaddedSize);
6221 Address RawMemAddr =
6222 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6223 Address MemAddr =
6224 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006225
6226 // Update overflow_arg_area_ptr pointer
6227 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006228 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6229 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006230 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6231 CGF.EmitBranch(ContBlock);
6232
6233 // Return the appropriate result.
6234 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006235 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6236 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006237
6238 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006239 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6240 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006241
6242 return ResAddr;
6243}
6244
Ulrich Weigand47445072013-05-06 16:26:41 +00006245ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6246 if (RetTy->isVoidType())
6247 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006248 if (isVectorArgumentType(RetTy))
6249 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006250 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006251 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006252 return (isPromotableIntegerType(RetTy) ?
6253 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6254}
6255
6256ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6257 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006258 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006259 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006260
6261 // Integers and enums are extended to full register width.
6262 if (isPromotableIntegerType(Ty))
6263 return ABIArgInfo::getExtend();
6264
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006265 // Handle vector types and vector-like structure types. Note that
6266 // as opposed to float-like structure types, we do not allow any
6267 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006268 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006269 QualType SingleElementTy = GetSingleElementType(Ty);
6270 if (isVectorArgumentType(SingleElementTy) &&
6271 getContext().getTypeSize(SingleElementTy) == Size)
6272 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6273
6274 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006275 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006276 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006277
6278 // Handle small structures.
6279 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6280 // Structures with flexible arrays have variable length, so really
6281 // fail the size test above.
6282 const RecordDecl *RD = RT->getDecl();
6283 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006284 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006285
6286 // The structure is passed as an unextended integer, a float, or a double.
6287 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006288 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006289 assert(Size == 32 || Size == 64);
6290 if (Size == 32)
6291 PassTy = llvm::Type::getFloatTy(getVMContext());
6292 else
6293 PassTy = llvm::Type::getDoubleTy(getVMContext());
6294 } else
6295 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6296 return ABIArgInfo::getDirect(PassTy);
6297 }
6298
6299 // Non-structure compounds are passed indirectly.
6300 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006301 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006302
Craig Topper8a13c412014-05-21 05:09:00 +00006303 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006304}
6305
6306//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006307// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006308//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006309
6310namespace {
6311
6312class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6313public:
Chris Lattner2b037972010-07-29 02:01:43 +00006314 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6315 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006316 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006317 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006318};
6319
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006320}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006321
Eric Christopher162c91c2015-06-05 22:03:00 +00006322void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006323 llvm::GlobalValue *GV,
6324 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006325 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006326 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6327 // Handle 'interrupt' attribute:
6328 llvm::Function *F = cast<llvm::Function>(GV);
6329
6330 // Step 1: Set ISR calling convention.
6331 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6332
6333 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006334 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006335
6336 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006337 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006338 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6339 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006340 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006341 }
6342}
6343
Chris Lattner0cf24192010-06-28 20:05:43 +00006344//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006345// MIPS ABI Implementation. This works for both little-endian and
6346// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006347//===----------------------------------------------------------------------===//
6348
John McCall943fae92010-05-27 06:19:26 +00006349namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006350class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006351 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006352 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6353 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006354 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006355 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006356 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006357 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006358public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006359 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006360 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006361 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006362
6363 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006364 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006365 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006366 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6367 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006368 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006369};
6370
John McCall943fae92010-05-27 06:19:26 +00006371class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006372 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006373public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006374 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6375 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006376 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006377
Craig Topper4f12f102014-03-12 06:41:41 +00006378 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006379 return 29;
6380 }
6381
Eric Christopher162c91c2015-06-05 22:03:00 +00006382 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006383 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006384 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006385 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006386 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006387 if (FD->hasAttr<Mips16Attr>()) {
6388 Fn->addFnAttr("mips16");
6389 }
6390 else if (FD->hasAttr<NoMips16Attr>()) {
6391 Fn->addFnAttr("nomips16");
6392 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006393
6394 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6395 if (!Attr)
6396 return;
6397
6398 const char *Kind;
6399 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006400 case MipsInterruptAttr::eic: Kind = "eic"; break;
6401 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6402 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6403 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6404 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6405 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6406 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6407 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6408 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6409 }
6410
6411 Fn->addFnAttr("interrupt", Kind);
6412
Reed Kotler373feca2013-01-16 17:10:28 +00006413 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006414
John McCall943fae92010-05-27 06:19:26 +00006415 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006416 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006417
Craig Topper4f12f102014-03-12 06:41:41 +00006418 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006419 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006420 }
John McCall943fae92010-05-27 06:19:26 +00006421};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006422}
John McCall943fae92010-05-27 06:19:26 +00006423
Eric Christopher7565e0d2015-05-29 23:09:49 +00006424void MipsABIInfo::CoerceToIntArgs(
6425 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006426 llvm::IntegerType *IntTy =
6427 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006428
6429 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6430 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6431 ArgList.push_back(IntTy);
6432
6433 // If necessary, add one more integer type to ArgList.
6434 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6435
6436 if (R)
6437 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006438}
6439
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006440// In N32/64, an aligned double precision floating point field is passed in
6441// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006442llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006443 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6444
6445 if (IsO32) {
6446 CoerceToIntArgs(TySize, ArgList);
6447 return llvm::StructType::get(getVMContext(), ArgList);
6448 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006449
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006450 if (Ty->isComplexType())
6451 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006452
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006453 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006454
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006455 // Unions/vectors are passed in integer registers.
6456 if (!RT || !RT->isStructureOrClassType()) {
6457 CoerceToIntArgs(TySize, ArgList);
6458 return llvm::StructType::get(getVMContext(), ArgList);
6459 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006460
6461 const RecordDecl *RD = RT->getDecl();
6462 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006463 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006464
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006465 uint64_t LastOffset = 0;
6466 unsigned idx = 0;
6467 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6468
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006469 // Iterate over fields in the struct/class and check if there are any aligned
6470 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006471 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6472 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006473 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006474 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6475
6476 if (!BT || BT->getKind() != BuiltinType::Double)
6477 continue;
6478
6479 uint64_t Offset = Layout.getFieldOffset(idx);
6480 if (Offset % 64) // Ignore doubles that are not aligned.
6481 continue;
6482
6483 // Add ((Offset - LastOffset) / 64) args of type i64.
6484 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6485 ArgList.push_back(I64);
6486
6487 // Add double type.
6488 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6489 LastOffset = Offset + 64;
6490 }
6491
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006492 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6493 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006494
6495 return llvm::StructType::get(getVMContext(), ArgList);
6496}
6497
Akira Hatanakaddd66342013-10-29 18:41:15 +00006498llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6499 uint64_t Offset) const {
6500 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006501 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006502
Akira Hatanakaddd66342013-10-29 18:41:15 +00006503 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006504}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006505
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006506ABIArgInfo
6507MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006508 Ty = useFirstFieldIfTransparentUnion(Ty);
6509
Akira Hatanaka1632af62012-01-09 19:31:25 +00006510 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006511 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006512 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006513
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006514 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6515 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006516 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6517 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006518
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006519 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006520 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006521 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006522 return ABIArgInfo::getIgnore();
6523
Mark Lacey3825e832013-10-06 01:33:34 +00006524 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006525 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006526 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006527 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006528
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006529 // If we have reached here, aggregates are passed directly by coercing to
6530 // another structure type. Padding is inserted if the offset of the
6531 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006532 ABIArgInfo ArgInfo =
6533 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6534 getPaddingType(OrigOffset, CurrOffset));
6535 ArgInfo.setInReg(true);
6536 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006537 }
6538
6539 // Treat an enum type as its underlying type.
6540 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6541 Ty = EnumTy->getDecl()->getIntegerType();
6542
Daniel Sanders5b445b32014-10-24 14:42:42 +00006543 // All integral types are promoted to the GPR width.
6544 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006545 return ABIArgInfo::getExtend();
6546
Akira Hatanakaddd66342013-10-29 18:41:15 +00006547 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006548 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006549}
6550
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006551llvm::Type*
6552MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006553 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006554 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006555
Akira Hatanakab6f74432012-02-09 18:49:26 +00006556 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006557 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006558 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6559 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006560
Akira Hatanakab6f74432012-02-09 18:49:26 +00006561 // N32/64 returns struct/classes in floating point registers if the
6562 // following conditions are met:
6563 // 1. The size of the struct/class is no larger than 128-bit.
6564 // 2. The struct/class has one or two fields all of which are floating
6565 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006566 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006567 //
6568 // Any other composite results are returned in integer registers.
6569 //
6570 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6571 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6572 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006573 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006574
Akira Hatanakab6f74432012-02-09 18:49:26 +00006575 if (!BT || !BT->isFloatingPoint())
6576 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006577
David Blaikie2d7c57e2012-04-30 02:36:29 +00006578 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006579 }
6580
6581 if (b == e)
6582 return llvm::StructType::get(getVMContext(), RTList,
6583 RD->hasAttr<PackedAttr>());
6584
6585 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006586 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006587 }
6588
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006589 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006590 return llvm::StructType::get(getVMContext(), RTList);
6591}
6592
Akira Hatanakab579fe52011-06-02 00:09:17 +00006593ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006594 uint64_t Size = getContext().getTypeSize(RetTy);
6595
Daniel Sandersed39f582014-09-04 13:28:14 +00006596 if (RetTy->isVoidType())
6597 return ABIArgInfo::getIgnore();
6598
6599 // O32 doesn't treat zero-sized structs differently from other structs.
6600 // However, N32/N64 ignores zero sized return values.
6601 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006602 return ABIArgInfo::getIgnore();
6603
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006604 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006605 if (Size <= 128) {
6606 if (RetTy->isAnyComplexType())
6607 return ABIArgInfo::getDirect();
6608
Daniel Sanderse5018b62014-09-04 15:05:39 +00006609 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006610 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006611 if (!IsO32 ||
6612 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6613 ABIArgInfo ArgInfo =
6614 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6615 ArgInfo.setInReg(true);
6616 return ArgInfo;
6617 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006618 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006619
John McCall7f416cc2015-09-08 08:05:57 +00006620 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006621 }
6622
6623 // Treat an enum type as its underlying type.
6624 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6625 RetTy = EnumTy->getDecl()->getIntegerType();
6626
6627 return (RetTy->isPromotableIntegerType() ?
6628 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6629}
6630
6631void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006632 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006633 if (!getCXXABI().classifyReturnType(FI))
6634 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006635
Eric Christopher7565e0d2015-05-29 23:09:49 +00006636 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006637 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006638
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006639 for (auto &I : FI.arguments())
6640 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006641}
6642
John McCall7f416cc2015-09-08 08:05:57 +00006643Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6644 QualType OrigTy) const {
6645 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006646
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006647 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6648 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006649 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006650 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006651 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006652 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006653 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006654 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006655 DidPromote = true;
6656 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6657 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006658 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006659
John McCall7f416cc2015-09-08 08:05:57 +00006660 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006661
John McCall7f416cc2015-09-08 08:05:57 +00006662 // The alignment of things in the argument area is never larger than
6663 // StackAlignInBytes.
6664 TyInfo.second =
6665 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6666
6667 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6668 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6669
6670 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6671 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6672
6673
6674 // If there was a promotion, "unpromote" into a temporary.
6675 // TODO: can we just use a pointer into a subset of the original slot?
6676 if (DidPromote) {
6677 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6678 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6679
6680 // Truncate down to the right width.
6681 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6682 : CGF.IntPtrTy);
6683 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6684 if (OrigTy->isPointerType())
6685 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6686
6687 CGF.Builder.CreateStore(V, Temp);
6688 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006689 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006690
John McCall7f416cc2015-09-08 08:05:57 +00006691 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006692}
6693
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006694bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6695 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006696
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006697 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6698 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6699 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006700
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006701 return false;
6702}
6703
John McCall943fae92010-05-27 06:19:26 +00006704bool
6705MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6706 llvm::Value *Address) const {
6707 // This information comes from gcc's implementation, which seems to
6708 // as canonical as it gets.
6709
John McCall943fae92010-05-27 06:19:26 +00006710 // Everything on MIPS is 4 bytes. Double-precision FP registers
6711 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006712 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006713
6714 // 0-31 are the general purpose registers, $0 - $31.
6715 // 32-63 are the floating-point registers, $f0 - $f31.
6716 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6717 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006718 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006719
6720 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6721 // They are one bit wide and ignored here.
6722
6723 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6724 // (coprocessor 1 is the FP unit)
6725 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6726 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6727 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006728 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006729 return false;
6730}
6731
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006732//===----------------------------------------------------------------------===//
6733// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006734// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006735// handling.
6736//===----------------------------------------------------------------------===//
6737
6738namespace {
6739
6740class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6741public:
6742 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6743 : DefaultTargetCodeGenInfo(CGT) {}
6744
Eric Christopher162c91c2015-06-05 22:03:00 +00006745 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006746 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006747};
6748
Eric Christopher162c91c2015-06-05 22:03:00 +00006749void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006750 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006751 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006752 if (!FD) return;
6753
6754 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006755
David Blaikiebbafb8a2012-03-11 07:00:24 +00006756 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006757 if (FD->hasAttr<OpenCLKernelAttr>()) {
6758 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006759 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006760 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6761 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006762 // Convert the reqd_work_group_size() attributes to metadata.
6763 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006764 llvm::NamedMDNode *OpenCLMetadata =
6765 M.getModule().getOrInsertNamedMetadata(
6766 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006767
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006768 SmallVector<llvm::Metadata *, 5> Operands;
6769 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006770
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006771 Operands.push_back(
6772 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6773 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6774 Operands.push_back(
6775 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6776 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6777 Operands.push_back(
6778 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6779 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006780
Eric Christopher7565e0d2015-05-29 23:09:49 +00006781 // Add a boolean constant operand for "required" (true) or "hint"
6782 // (false) for implementing the work_group_size_hint attr later.
6783 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006784 Operands.push_back(
6785 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006786 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6787 }
6788 }
6789 }
6790}
6791
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006792}
John McCall943fae92010-05-27 06:19:26 +00006793
Tony Linthicum76329bf2011-12-12 21:14:55 +00006794//===----------------------------------------------------------------------===//
6795// Hexagon ABI Implementation
6796//===----------------------------------------------------------------------===//
6797
6798namespace {
6799
6800class HexagonABIInfo : public ABIInfo {
6801
6802
6803public:
6804 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6805
6806private:
6807
6808 ABIArgInfo classifyReturnType(QualType RetTy) const;
6809 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6810
Craig Topper4f12f102014-03-12 06:41:41 +00006811 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006812
John McCall7f416cc2015-09-08 08:05:57 +00006813 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6814 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006815};
6816
6817class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6818public:
6819 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6820 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6821
Craig Topper4f12f102014-03-12 06:41:41 +00006822 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006823 return 29;
6824 }
6825};
6826
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006827}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006828
6829void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006830 if (!getCXXABI().classifyReturnType(FI))
6831 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006832 for (auto &I : FI.arguments())
6833 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006834}
6835
6836ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6837 if (!isAggregateTypeForABI(Ty)) {
6838 // Treat an enum type as its underlying type.
6839 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6840 Ty = EnumTy->getDecl()->getIntegerType();
6841
6842 return (Ty->isPromotableIntegerType() ?
6843 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6844 }
6845
6846 // Ignore empty records.
6847 if (isEmptyRecord(getContext(), Ty, true))
6848 return ABIArgInfo::getIgnore();
6849
Mark Lacey3825e832013-10-06 01:33:34 +00006850 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006851 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006852
6853 uint64_t Size = getContext().getTypeSize(Ty);
6854 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006855 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006856 // Pass in the smallest viable integer type.
6857 else if (Size > 32)
6858 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6859 else if (Size > 16)
6860 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6861 else if (Size > 8)
6862 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6863 else
6864 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6865}
6866
6867ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6868 if (RetTy->isVoidType())
6869 return ABIArgInfo::getIgnore();
6870
6871 // Large vector types should be returned via memory.
6872 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006873 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006874
6875 if (!isAggregateTypeForABI(RetTy)) {
6876 // Treat an enum type as its underlying type.
6877 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6878 RetTy = EnumTy->getDecl()->getIntegerType();
6879
6880 return (RetTy->isPromotableIntegerType() ?
6881 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6882 }
6883
Tony Linthicum76329bf2011-12-12 21:14:55 +00006884 if (isEmptyRecord(getContext(), RetTy, true))
6885 return ABIArgInfo::getIgnore();
6886
6887 // Aggregates <= 8 bytes are returned in r0; other aggregates
6888 // are returned indirectly.
6889 uint64_t Size = getContext().getTypeSize(RetTy);
6890 if (Size <= 64) {
6891 // Return in the smallest viable integer type.
6892 if (Size <= 8)
6893 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6894 if (Size <= 16)
6895 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6896 if (Size <= 32)
6897 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6898 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6899 }
6900
John McCall7f416cc2015-09-08 08:05:57 +00006901 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006902}
6903
John McCall7f416cc2015-09-08 08:05:57 +00006904Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6905 QualType Ty) const {
6906 // FIXME: Someone needs to audit that this handle alignment correctly.
6907 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6908 getContext().getTypeInfoInChars(Ty),
6909 CharUnits::fromQuantity(4),
6910 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006911}
6912
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006913//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00006914// Lanai ABI Implementation
6915//===----------------------------------------------------------------------===//
6916
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006917namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00006918class LanaiABIInfo : public DefaultABIInfo {
6919public:
6920 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
6921
6922 bool shouldUseInReg(QualType Ty, CCState &State) const;
6923
6924 void computeInfo(CGFunctionInfo &FI) const override {
6925 CCState State(FI.getCallingConvention());
6926 // Lanai uses 4 registers to pass arguments unless the function has the
6927 // regparm attribute set.
6928 if (FI.getHasRegParm()) {
6929 State.FreeRegs = FI.getRegParm();
6930 } else {
6931 State.FreeRegs = 4;
6932 }
6933
6934 if (!getCXXABI().classifyReturnType(FI))
6935 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6936 for (auto &I : FI.arguments())
6937 I.info = classifyArgumentType(I.type, State);
6938 }
6939
Jacques Pienaare74d9132016-04-26 00:09:29 +00006940 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00006941 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
6942};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00006943} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00006944
6945bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
6946 unsigned Size = getContext().getTypeSize(Ty);
6947 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
6948
6949 if (SizeInRegs == 0)
6950 return false;
6951
6952 if (SizeInRegs > State.FreeRegs) {
6953 State.FreeRegs = 0;
6954 return false;
6955 }
6956
6957 State.FreeRegs -= SizeInRegs;
6958
6959 return true;
6960}
6961
Jacques Pienaare74d9132016-04-26 00:09:29 +00006962ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
6963 CCState &State) const {
6964 if (!ByVal) {
6965 if (State.FreeRegs) {
6966 --State.FreeRegs; // Non-byval indirects just use one pointer.
6967 return getNaturalAlignIndirectInReg(Ty);
6968 }
6969 return getNaturalAlignIndirect(Ty, false);
6970 }
6971
6972 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00006973 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00006974 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
6975 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
6976 /*Realign=*/TypeAlign >
6977 MinABIStackAlignInBytes);
6978}
6979
Jacques Pienaard964cc22016-03-28 21:02:54 +00006980ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
6981 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00006982 // Check with the C++ ABI first.
6983 const RecordType *RT = Ty->getAs<RecordType>();
6984 if (RT) {
6985 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
6986 if (RAA == CGCXXABI::RAA_Indirect) {
6987 return getIndirectResult(Ty, /*ByVal=*/false, State);
6988 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
6989 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
6990 }
6991 }
6992
6993 if (isAggregateTypeForABI(Ty)) {
6994 // Structures with flexible arrays are always indirect.
6995 if (RT && RT->getDecl()->hasFlexibleArrayMember())
6996 return getIndirectResult(Ty, /*ByVal=*/true, State);
6997
6998 // Ignore empty structs/unions.
6999 if (isEmptyRecord(getContext(), Ty, true))
7000 return ABIArgInfo::getIgnore();
7001
7002 llvm::LLVMContext &LLVMContext = getVMContext();
7003 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7004 if (SizeInRegs <= State.FreeRegs) {
7005 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7006 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7007 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7008 State.FreeRegs -= SizeInRegs;
7009 return ABIArgInfo::getDirectInReg(Result);
7010 } else {
7011 State.FreeRegs = 0;
7012 }
7013 return getIndirectResult(Ty, true, State);
7014 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007015
7016 // Treat an enum type as its underlying type.
7017 if (const auto *EnumTy = Ty->getAs<EnumType>())
7018 Ty = EnumTy->getDecl()->getIntegerType();
7019
Jacques Pienaare74d9132016-04-26 00:09:29 +00007020 bool InReg = shouldUseInReg(Ty, State);
7021 if (Ty->isPromotableIntegerType()) {
7022 if (InReg)
7023 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007024 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007025 }
7026 if (InReg)
7027 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007028 return ABIArgInfo::getDirect();
7029}
7030
7031namespace {
7032class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7033public:
7034 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7035 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7036};
7037}
7038
7039//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007040// AMDGPU ABI Implementation
7041//===----------------------------------------------------------------------===//
7042
7043namespace {
7044
Matt Arsenault88d7da02016-08-22 19:25:59 +00007045class AMDGPUABIInfo final : public DefaultABIInfo {
7046public:
7047 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7048
7049private:
7050 ABIArgInfo classifyArgumentType(QualType Ty) const;
7051
7052 void computeInfo(CGFunctionInfo &FI) const override;
7053};
7054
7055void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7056 if (!getCXXABI().classifyReturnType(FI))
7057 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7058
7059 unsigned CC = FI.getCallingConvention();
7060 for (auto &Arg : FI.arguments())
7061 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7062 Arg.info = classifyArgumentType(Arg.type);
7063 else
7064 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7065}
7066
7067/// \brief Classify argument of given type \p Ty.
7068ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7069 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7070 if (!StrTy) {
7071 return DefaultABIInfo::classifyArgumentType(Ty);
7072 }
7073
7074 // Coerce single element structs to its element.
7075 if (StrTy->getNumElements() == 1) {
7076 return ABIArgInfo::getDirect();
7077 }
7078
7079 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7080 // individual elements, which confuses the Clover OpenCL backend; therefore we
7081 // have to set it to false here. Other args of getDirect() are just defaults.
7082 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7083}
7084
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007085class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7086public:
7087 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007088 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007089 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007090 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007091 unsigned getOpenCLKernelCallingConv() const override;
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007092
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00007093 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7094 llvm::PointerType *T, QualType QT) const override;
7095};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007096}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007097
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007098static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7099
Eric Christopher162c91c2015-06-05 22:03:00 +00007100void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007101 const Decl *D,
7102 llvm::GlobalValue *GV,
7103 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007104 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007105 if (!FD)
7106 return;
7107
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007108 llvm::Function *F = cast<llvm::Function>(GV);
7109
7110 if (const auto *Attr = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7111 unsigned Min = Attr->getMin();
7112 unsigned Max = Attr->getMax();
7113
7114 if (Min != 0) {
7115 assert(Min <= Max && "Min must be less than or equal Max");
7116
7117 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7118 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7119 } else
7120 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007121 }
7122
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007123 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7124 unsigned Min = Attr->getMin();
7125 unsigned Max = Attr->getMax();
7126
7127 if (Min != 0) {
7128 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7129
7130 std::string AttrVal = llvm::utostr(Min);
7131 if (Max != 0)
7132 AttrVal = AttrVal + "," + llvm::utostr(Max);
7133 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7134 } else
7135 assert(Max == 0 && "Max must be zero");
7136 }
7137
7138 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007139 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007140
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007141 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007142 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7143 }
7144
7145 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7146 uint32_t NumVGPR = Attr->getNumVGPR();
7147
7148 if (NumVGPR != 0)
7149 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007150 }
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007151
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007152 appendOpenCLVersionMD(M);
7153}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007154
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007155unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7156 return llvm::CallingConv::AMDGPU_KERNEL;
7157}
7158
Yaxun Liu8f66b4b2016-12-09 19:01:11 +00007159// Currently LLVM assumes null pointers always have value 0,
7160// which results in incorrectly transformed IR. Therefore, instead of
7161// emitting null pointers in private and local address spaces, a null
7162// pointer in generic address space is emitted which is casted to a
7163// pointer in local or private address space.
7164llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7165 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7166 QualType QT) const {
7167 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7168 return llvm::ConstantPointerNull::get(PT);
7169
7170 auto &Ctx = CGM.getContext();
7171 auto NPT = llvm::PointerType::get(PT->getElementType(),
7172 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7173 return llvm::ConstantExpr::getAddrSpaceCast(
7174 llvm::ConstantPointerNull::get(NPT), PT);
7175}
7176
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007177//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007178// SPARC v8 ABI Implementation.
7179// Based on the SPARC Compliance Definition version 2.4.1.
7180//
7181// Ensures that complex values are passed in registers.
7182//
7183namespace {
7184class SparcV8ABIInfo : public DefaultABIInfo {
7185public:
7186 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7187
7188private:
7189 ABIArgInfo classifyReturnType(QualType RetTy) const;
7190 void computeInfo(CGFunctionInfo &FI) const override;
7191};
7192} // end anonymous namespace
7193
7194
7195ABIArgInfo
7196SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7197 if (Ty->isAnyComplexType()) {
7198 return ABIArgInfo::getDirect();
7199 }
7200 else {
7201 return DefaultABIInfo::classifyReturnType(Ty);
7202 }
7203}
7204
7205void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7206
7207 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7208 for (auto &Arg : FI.arguments())
7209 Arg.info = classifyArgumentType(Arg.type);
7210}
7211
7212namespace {
7213class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7214public:
7215 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7216 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7217};
7218} // end anonymous namespace
7219
7220//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007221// SPARC v9 ABI Implementation.
7222// Based on the SPARC Compliance Definition version 2.4.1.
7223//
7224// Function arguments a mapped to a nominal "parameter array" and promoted to
7225// registers depending on their type. Each argument occupies 8 or 16 bytes in
7226// the array, structs larger than 16 bytes are passed indirectly.
7227//
7228// One case requires special care:
7229//
7230// struct mixed {
7231// int i;
7232// float f;
7233// };
7234//
7235// When a struct mixed is passed by value, it only occupies 8 bytes in the
7236// parameter array, but the int is passed in an integer register, and the float
7237// is passed in a floating point register. This is represented as two arguments
7238// with the LLVM IR inreg attribute:
7239//
7240// declare void f(i32 inreg %i, float inreg %f)
7241//
7242// The code generator will only allocate 4 bytes from the parameter array for
7243// the inreg arguments. All other arguments are allocated a multiple of 8
7244// bytes.
7245//
7246namespace {
7247class SparcV9ABIInfo : public ABIInfo {
7248public:
7249 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7250
7251private:
7252 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007253 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007254 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7255 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007256
7257 // Coercion type builder for structs passed in registers. The coercion type
7258 // serves two purposes:
7259 //
7260 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7261 // in registers.
7262 // 2. Expose aligned floating point elements as first-level elements, so the
7263 // code generator knows to pass them in floating point registers.
7264 //
7265 // We also compute the InReg flag which indicates that the struct contains
7266 // aligned 32-bit floats.
7267 //
7268 struct CoerceBuilder {
7269 llvm::LLVMContext &Context;
7270 const llvm::DataLayout &DL;
7271 SmallVector<llvm::Type*, 8> Elems;
7272 uint64_t Size;
7273 bool InReg;
7274
7275 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7276 : Context(c), DL(dl), Size(0), InReg(false) {}
7277
7278 // Pad Elems with integers until Size is ToSize.
7279 void pad(uint64_t ToSize) {
7280 assert(ToSize >= Size && "Cannot remove elements");
7281 if (ToSize == Size)
7282 return;
7283
7284 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007285 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007286 if (Aligned > Size && Aligned <= ToSize) {
7287 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7288 Size = Aligned;
7289 }
7290
7291 // Add whole 64-bit words.
7292 while (Size + 64 <= ToSize) {
7293 Elems.push_back(llvm::Type::getInt64Ty(Context));
7294 Size += 64;
7295 }
7296
7297 // Final in-word padding.
7298 if (Size < ToSize) {
7299 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7300 Size = ToSize;
7301 }
7302 }
7303
7304 // Add a floating point element at Offset.
7305 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7306 // Unaligned floats are treated as integers.
7307 if (Offset % Bits)
7308 return;
7309 // The InReg flag is only required if there are any floats < 64 bits.
7310 if (Bits < 64)
7311 InReg = true;
7312 pad(Offset);
7313 Elems.push_back(Ty);
7314 Size = Offset + Bits;
7315 }
7316
7317 // Add a struct type to the coercion type, starting at Offset (in bits).
7318 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7319 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7320 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7321 llvm::Type *ElemTy = StrTy->getElementType(i);
7322 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7323 switch (ElemTy->getTypeID()) {
7324 case llvm::Type::StructTyID:
7325 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7326 break;
7327 case llvm::Type::FloatTyID:
7328 addFloat(ElemOffset, ElemTy, 32);
7329 break;
7330 case llvm::Type::DoubleTyID:
7331 addFloat(ElemOffset, ElemTy, 64);
7332 break;
7333 case llvm::Type::FP128TyID:
7334 addFloat(ElemOffset, ElemTy, 128);
7335 break;
7336 case llvm::Type::PointerTyID:
7337 if (ElemOffset % 64 == 0) {
7338 pad(ElemOffset);
7339 Elems.push_back(ElemTy);
7340 Size += 64;
7341 }
7342 break;
7343 default:
7344 break;
7345 }
7346 }
7347 }
7348
7349 // Check if Ty is a usable substitute for the coercion type.
7350 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007351 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007352 }
7353
7354 // Get the coercion type as a literal struct type.
7355 llvm::Type *getType() const {
7356 if (Elems.size() == 1)
7357 return Elems.front();
7358 else
7359 return llvm::StructType::get(Context, Elems);
7360 }
7361 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007362};
7363} // end anonymous namespace
7364
7365ABIArgInfo
7366SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7367 if (Ty->isVoidType())
7368 return ABIArgInfo::getIgnore();
7369
7370 uint64_t Size = getContext().getTypeSize(Ty);
7371
7372 // Anything too big to fit in registers is passed with an explicit indirect
7373 // pointer / sret pointer.
7374 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007375 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007376
7377 // Treat an enum type as its underlying type.
7378 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7379 Ty = EnumTy->getDecl()->getIntegerType();
7380
7381 // Integer types smaller than a register are extended.
7382 if (Size < 64 && Ty->isIntegerType())
7383 return ABIArgInfo::getExtend();
7384
7385 // Other non-aggregates go in registers.
7386 if (!isAggregateTypeForABI(Ty))
7387 return ABIArgInfo::getDirect();
7388
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007389 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7390 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7391 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007392 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007393
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007394 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007395 // Build a coercion type from the LLVM struct type.
7396 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7397 if (!StrTy)
7398 return ABIArgInfo::getDirect();
7399
7400 CoerceBuilder CB(getVMContext(), getDataLayout());
7401 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007402 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007403
7404 // Try to use the original type for coercion.
7405 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7406
7407 if (CB.InReg)
7408 return ABIArgInfo::getDirectInReg(CoerceTy);
7409 else
7410 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007411}
7412
John McCall7f416cc2015-09-08 08:05:57 +00007413Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7414 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007415 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7416 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7417 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7418 AI.setCoerceToType(ArgTy);
7419
John McCall7f416cc2015-09-08 08:05:57 +00007420 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007421
John McCall7f416cc2015-09-08 08:05:57 +00007422 CGBuilderTy &Builder = CGF.Builder;
7423 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7424 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7425
7426 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7427
7428 Address ArgAddr = Address::invalid();
7429 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007430 switch (AI.getKind()) {
7431 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007432 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007433 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007434 llvm_unreachable("Unsupported ABI kind for va_arg");
7435
John McCall7f416cc2015-09-08 08:05:57 +00007436 case ABIArgInfo::Extend: {
7437 Stride = SlotSize;
7438 CharUnits Offset = SlotSize - TypeInfo.first;
7439 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007440 break;
John McCall7f416cc2015-09-08 08:05:57 +00007441 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007442
John McCall7f416cc2015-09-08 08:05:57 +00007443 case ABIArgInfo::Direct: {
7444 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007445 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007446 ArgAddr = Addr;
7447 break;
John McCall7f416cc2015-09-08 08:05:57 +00007448 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007449
7450 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007451 Stride = SlotSize;
7452 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7453 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7454 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007455 break;
7456
7457 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007458 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007459 }
7460
7461 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007462 llvm::Value *NextPtr =
7463 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7464 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007465
John McCall7f416cc2015-09-08 08:05:57 +00007466 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007467}
7468
7469void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7470 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007471 for (auto &I : FI.arguments())
7472 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007473}
7474
7475namespace {
7476class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7477public:
7478 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7479 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007480
Craig Topper4f12f102014-03-12 06:41:41 +00007481 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007482 return 14;
7483 }
7484
7485 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007486 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007487};
7488} // end anonymous namespace
7489
Roman Divackyf02c9942014-02-24 18:46:27 +00007490bool
7491SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7492 llvm::Value *Address) const {
7493 // This is calculated from the LLVM and GCC tables and verified
7494 // against gcc output. AFAIK all ABIs use the same encoding.
7495
7496 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7497
7498 llvm::IntegerType *i8 = CGF.Int8Ty;
7499 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7500 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7501
7502 // 0-31: the 8-byte general-purpose registers
7503 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7504
7505 // 32-63: f0-31, the 4-byte floating-point registers
7506 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7507
7508 // Y = 64
7509 // PSR = 65
7510 // WIM = 66
7511 // TBR = 67
7512 // PC = 68
7513 // NPC = 69
7514 // FSR = 70
7515 // CSR = 71
7516 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007517
Roman Divackyf02c9942014-02-24 18:46:27 +00007518 // 72-87: d0-15, the 8-byte floating-point registers
7519 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7520
7521 return false;
7522}
7523
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007524
Robert Lytton0e076492013-08-13 09:43:10 +00007525//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007526// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007527//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007528
Robert Lytton0e076492013-08-13 09:43:10 +00007529namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007530
7531/// A SmallStringEnc instance is used to build up the TypeString by passing
7532/// it by reference between functions that append to it.
7533typedef llvm::SmallString<128> SmallStringEnc;
7534
7535/// TypeStringCache caches the meta encodings of Types.
7536///
7537/// The reason for caching TypeStrings is two fold:
7538/// 1. To cache a type's encoding for later uses;
7539/// 2. As a means to break recursive member type inclusion.
7540///
7541/// A cache Entry can have a Status of:
7542/// NonRecursive: The type encoding is not recursive;
7543/// Recursive: The type encoding is recursive;
7544/// Incomplete: An incomplete TypeString;
7545/// IncompleteUsed: An incomplete TypeString that has been used in a
7546/// Recursive type encoding.
7547///
7548/// A NonRecursive entry will have all of its sub-members expanded as fully
7549/// as possible. Whilst it may contain types which are recursive, the type
7550/// itself is not recursive and thus its encoding may be safely used whenever
7551/// the type is encountered.
7552///
7553/// A Recursive entry will have all of its sub-members expanded as fully as
7554/// possible. The type itself is recursive and it may contain other types which
7555/// are recursive. The Recursive encoding must not be used during the expansion
7556/// of a recursive type's recursive branch. For simplicity the code uses
7557/// IncompleteCount to reject all usage of Recursive encodings for member types.
7558///
7559/// An Incomplete entry is always a RecordType and only encodes its
7560/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7561/// are placed into the cache during type expansion as a means to identify and
7562/// handle recursive inclusion of types as sub-members. If there is recursion
7563/// the entry becomes IncompleteUsed.
7564///
7565/// During the expansion of a RecordType's members:
7566///
7567/// If the cache contains a NonRecursive encoding for the member type, the
7568/// cached encoding is used;
7569///
7570/// If the cache contains a Recursive encoding for the member type, the
7571/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7572///
7573/// If the member is a RecordType, an Incomplete encoding is placed into the
7574/// cache to break potential recursive inclusion of itself as a sub-member;
7575///
7576/// Once a member RecordType has been expanded, its temporary incomplete
7577/// entry is removed from the cache. If a Recursive encoding was swapped out
7578/// it is swapped back in;
7579///
7580/// If an incomplete entry is used to expand a sub-member, the incomplete
7581/// entry is marked as IncompleteUsed. The cache keeps count of how many
7582/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7583///
7584/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7585/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7586/// Else the member is part of a recursive type and thus the recursion has
7587/// been exited too soon for the encoding to be correct for the member.
7588///
7589class TypeStringCache {
7590 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7591 struct Entry {
7592 std::string Str; // The encoded TypeString for the type.
7593 enum Status State; // Information about the encoding in 'Str'.
7594 std::string Swapped; // A temporary place holder for a Recursive encoding
7595 // during the expansion of RecordType's members.
7596 };
7597 std::map<const IdentifierInfo *, struct Entry> Map;
7598 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7599 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7600public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007601 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007602 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7603 bool removeIncomplete(const IdentifierInfo *ID);
7604 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7605 bool IsRecursive);
7606 StringRef lookupStr(const IdentifierInfo *ID);
7607};
7608
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007609/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007610/// FieldEncoding is a helper for this ordering process.
7611class FieldEncoding {
7612 bool HasName;
7613 std::string Enc;
7614public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007615 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007616 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007617 bool operator<(const FieldEncoding &rhs) const {
7618 if (HasName != rhs.HasName) return HasName;
7619 return Enc < rhs.Enc;
7620 }
7621};
7622
Robert Lytton7d1db152013-08-19 09:46:39 +00007623class XCoreABIInfo : public DefaultABIInfo {
7624public:
7625 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007626 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7627 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007628};
7629
Robert Lyttond21e2d72014-03-03 13:45:29 +00007630class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007631 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007632public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007633 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007634 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007635 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7636 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007637};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007638
Robert Lytton2d196952013-10-11 10:29:34 +00007639} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007640
James Y Knight29b5f082016-02-24 02:59:33 +00007641// TODO: this implementation is likely now redundant with the default
7642// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007643Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7644 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007645 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007646
Robert Lytton2d196952013-10-11 10:29:34 +00007647 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007648 CharUnits SlotSize = CharUnits::fromQuantity(4);
7649 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007650
Robert Lytton2d196952013-10-11 10:29:34 +00007651 // Handle the argument.
7652 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007653 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007654 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7655 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7656 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007657 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007658
7659 Address Val = Address::invalid();
7660 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007661 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007662 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007663 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007664 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007665 llvm_unreachable("Unsupported ABI kind for va_arg");
7666 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007667 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7668 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007669 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007670 case ABIArgInfo::Extend:
7671 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007672 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7673 ArgSize = CharUnits::fromQuantity(
7674 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007675 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007676 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007677 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007678 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7679 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7680 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007681 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007682 }
Robert Lytton2d196952013-10-11 10:29:34 +00007683
7684 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007685 if (!ArgSize.isZero()) {
7686 llvm::Value *APN =
7687 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7688 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007689 }
John McCall7f416cc2015-09-08 08:05:57 +00007690
Robert Lytton2d196952013-10-11 10:29:34 +00007691 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007692}
Robert Lytton0e076492013-08-13 09:43:10 +00007693
Robert Lytton844aeeb2014-05-02 09:33:20 +00007694/// During the expansion of a RecordType, an incomplete TypeString is placed
7695/// into the cache as a means to identify and break recursion.
7696/// If there is a Recursive encoding in the cache, it is swapped out and will
7697/// be reinserted by removeIncomplete().
7698/// All other types of encoding should have been used rather than arriving here.
7699void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7700 std::string StubEnc) {
7701 if (!ID)
7702 return;
7703 Entry &E = Map[ID];
7704 assert( (E.Str.empty() || E.State == Recursive) &&
7705 "Incorrectly use of addIncomplete");
7706 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7707 E.Swapped.swap(E.Str); // swap out the Recursive
7708 E.Str.swap(StubEnc);
7709 E.State = Incomplete;
7710 ++IncompleteCount;
7711}
7712
7713/// Once the RecordType has been expanded, the temporary incomplete TypeString
7714/// must be removed from the cache.
7715/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7716/// Returns true if the RecordType was defined recursively.
7717bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7718 if (!ID)
7719 return false;
7720 auto I = Map.find(ID);
7721 assert(I != Map.end() && "Entry not present");
7722 Entry &E = I->second;
7723 assert( (E.State == Incomplete ||
7724 E.State == IncompleteUsed) &&
7725 "Entry must be an incomplete type");
7726 bool IsRecursive = false;
7727 if (E.State == IncompleteUsed) {
7728 // We made use of our Incomplete encoding, thus we are recursive.
7729 IsRecursive = true;
7730 --IncompleteUsedCount;
7731 }
7732 if (E.Swapped.empty())
7733 Map.erase(I);
7734 else {
7735 // Swap the Recursive back.
7736 E.Swapped.swap(E.Str);
7737 E.Swapped.clear();
7738 E.State = Recursive;
7739 }
7740 --IncompleteCount;
7741 return IsRecursive;
7742}
7743
7744/// Add the encoded TypeString to the cache only if it is NonRecursive or
7745/// Recursive (viz: all sub-members were expanded as fully as possible).
7746void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7747 bool IsRecursive) {
7748 if (!ID || IncompleteUsedCount)
7749 return; // No key or it is is an incomplete sub-type so don't add.
7750 Entry &E = Map[ID];
7751 if (IsRecursive && !E.Str.empty()) {
7752 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7753 "This is not the same Recursive entry");
7754 // The parent container was not recursive after all, so we could have used
7755 // this Recursive sub-member entry after all, but we assumed the worse when
7756 // we started viz: IncompleteCount!=0.
7757 return;
7758 }
7759 assert(E.Str.empty() && "Entry already present");
7760 E.Str = Str.str();
7761 E.State = IsRecursive? Recursive : NonRecursive;
7762}
7763
7764/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7765/// are recursively expanding a type (IncompleteCount != 0) and the cached
7766/// encoding is Recursive, return an empty StringRef.
7767StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7768 if (!ID)
7769 return StringRef(); // We have no key.
7770 auto I = Map.find(ID);
7771 if (I == Map.end())
7772 return StringRef(); // We have no encoding.
7773 Entry &E = I->second;
7774 if (E.State == Recursive && IncompleteCount)
7775 return StringRef(); // We don't use Recursive encodings for member types.
7776
7777 if (E.State == Incomplete) {
7778 // The incomplete type is being used to break out of recursion.
7779 E.State = IncompleteUsed;
7780 ++IncompleteUsedCount;
7781 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007782 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007783}
7784
7785/// The XCore ABI includes a type information section that communicates symbol
7786/// type information to the linker. The linker uses this information to verify
7787/// safety/correctness of things such as array bound and pointers et al.
7788/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7789/// This type information (TypeString) is emitted into meta data for all global
7790/// symbols: definitions, declarations, functions & variables.
7791///
7792/// The TypeString carries type, qualifier, name, size & value details.
7793/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007794/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007795/// The output is tested by test/CodeGen/xcore-stringtype.c.
7796///
7797static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7798 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7799
7800/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7801void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7802 CodeGen::CodeGenModule &CGM) const {
7803 SmallStringEnc Enc;
7804 if (getTypeString(Enc, D, CGM, TSC)) {
7805 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00007806 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
7807 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007808 llvm::NamedMDNode *MD =
7809 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7810 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7811 }
7812}
7813
Xiuli Pan972bea82016-03-24 03:57:17 +00007814//===----------------------------------------------------------------------===//
7815// SPIR ABI Implementation
7816//===----------------------------------------------------------------------===//
7817
7818namespace {
7819class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
7820public:
7821 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7822 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
7823 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7824 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007825 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00007826};
7827} // End anonymous namespace.
7828
7829/// Emit SPIR specific metadata: OpenCL and SPIR version.
7830void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7831 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00007832 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7833 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7834 llvm::Module &M = CGM.getModule();
7835 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
7836 // opencl.spir.version named metadata.
7837 llvm::Metadata *SPIRVerElts[] = {
Alexey Baderb3190822016-12-07 08:38:24 +00007838 llvm::ConstantAsMetadata::get(
7839 llvm::ConstantInt::get(Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7840 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7841 Int32Ty, (CGM.getLangOpts().OpenCLVersion / 100 > 1) ? 0 : 2))};
Xiuli Pan972bea82016-03-24 03:57:17 +00007842 llvm::NamedMDNode *SPIRVerMD =
7843 M.getOrInsertNamedMetadata("opencl.spir.version");
7844 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007845 appendOpenCLVersionMD(CGM);
7846}
7847
Matt Arsenault8afb5cd2016-09-07 07:07:59 +00007848static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007849 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
7850 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
7851 llvm::Module &M = CGM.getModule();
Xiuli Pan972bea82016-03-24 03:57:17 +00007852 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
7853 // opencl.ocl.version named metadata node.
7854 llvm::Metadata *OCLVerElts[] = {
7855 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7856 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
7857 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
7858 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
7859 llvm::NamedMDNode *OCLVerMD =
7860 M.getOrInsertNamedMetadata("opencl.ocl.version");
7861 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
7862}
7863
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007864unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7865 return llvm::CallingConv::SPIR_KERNEL;
7866}
7867
Robert Lytton844aeeb2014-05-02 09:33:20 +00007868static bool appendType(SmallStringEnc &Enc, QualType QType,
7869 const CodeGen::CodeGenModule &CGM,
7870 TypeStringCache &TSC);
7871
7872/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007873/// Builds a SmallVector containing the encoded field types in declaration
7874/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007875static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7876 const RecordDecl *RD,
7877 const CodeGen::CodeGenModule &CGM,
7878 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007879 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007880 SmallStringEnc Enc;
7881 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007882 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007883 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007884 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007885 Enc += "b(";
7886 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007887 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007888 Enc += ':';
7889 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007890 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007891 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007892 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007893 Enc += ')';
7894 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007895 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007896 }
7897 return true;
7898}
7899
7900/// Appends structure and union types to Enc and adds encoding to cache.
7901/// Recursively calls appendType (via extractFieldType) for each field.
7902/// Union types have their fields ordered according to the ABI.
7903static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7904 const CodeGen::CodeGenModule &CGM,
7905 TypeStringCache &TSC, const IdentifierInfo *ID) {
7906 // Append the cached TypeString if we have one.
7907 StringRef TypeString = TSC.lookupStr(ID);
7908 if (!TypeString.empty()) {
7909 Enc += TypeString;
7910 return true;
7911 }
7912
7913 // Start to emit an incomplete TypeString.
7914 size_t Start = Enc.size();
7915 Enc += (RT->isUnionType()? 'u' : 's');
7916 Enc += '(';
7917 if (ID)
7918 Enc += ID->getName();
7919 Enc += "){";
7920
7921 // We collect all encoded fields and order as necessary.
7922 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007923 const RecordDecl *RD = RT->getDecl()->getDefinition();
7924 if (RD && !RD->field_empty()) {
7925 // An incomplete TypeString stub is placed in the cache for this RecordType
7926 // so that recursive calls to this RecordType will use it whilst building a
7927 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007928 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007929 std::string StubEnc(Enc.substr(Start).str());
7930 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7931 TSC.addIncomplete(ID, std::move(StubEnc));
7932 if (!extractFieldType(FE, RD, CGM, TSC)) {
7933 (void) TSC.removeIncomplete(ID);
7934 return false;
7935 }
7936 IsRecursive = TSC.removeIncomplete(ID);
7937 // The ABI requires unions to be sorted but not structures.
7938 // See FieldEncoding::operator< for sort algorithm.
7939 if (RT->isUnionType())
7940 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007941 // We can now complete the TypeString.
7942 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007943 for (unsigned I = 0; I != E; ++I) {
7944 if (I)
7945 Enc += ',';
7946 Enc += FE[I].str();
7947 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007948 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007949 Enc += '}';
7950 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7951 return true;
7952}
7953
7954/// Appends enum types to Enc and adds the encoding to the cache.
7955static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7956 TypeStringCache &TSC,
7957 const IdentifierInfo *ID) {
7958 // Append the cached TypeString if we have one.
7959 StringRef TypeString = TSC.lookupStr(ID);
7960 if (!TypeString.empty()) {
7961 Enc += TypeString;
7962 return true;
7963 }
7964
7965 size_t Start = Enc.size();
7966 Enc += "e(";
7967 if (ID)
7968 Enc += ID->getName();
7969 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007970
7971 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007972 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007973 SmallVector<FieldEncoding, 16> FE;
7974 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7975 ++I) {
7976 SmallStringEnc EnumEnc;
7977 EnumEnc += "m(";
7978 EnumEnc += I->getName();
7979 EnumEnc += "){";
7980 I->getInitVal().toString(EnumEnc);
7981 EnumEnc += '}';
7982 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7983 }
7984 std::sort(FE.begin(), FE.end());
7985 unsigned E = FE.size();
7986 for (unsigned I = 0; I != E; ++I) {
7987 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007988 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007989 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007990 }
7991 }
7992 Enc += '}';
7993 TSC.addIfComplete(ID, Enc.substr(Start), false);
7994 return true;
7995}
7996
7997/// Appends type's qualifier to Enc.
7998/// This is done prior to appending the type's encoding.
7999static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8000 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008001 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008002 int Lookup = 0;
8003 if (QT.isConstQualified())
8004 Lookup += 1<<0;
8005 if (QT.isRestrictQualified())
8006 Lookup += 1<<1;
8007 if (QT.isVolatileQualified())
8008 Lookup += 1<<2;
8009 Enc += Table[Lookup];
8010}
8011
8012/// Appends built-in types to Enc.
8013static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8014 const char *EncType;
8015 switch (BT->getKind()) {
8016 case BuiltinType::Void:
8017 EncType = "0";
8018 break;
8019 case BuiltinType::Bool:
8020 EncType = "b";
8021 break;
8022 case BuiltinType::Char_U:
8023 EncType = "uc";
8024 break;
8025 case BuiltinType::UChar:
8026 EncType = "uc";
8027 break;
8028 case BuiltinType::SChar:
8029 EncType = "sc";
8030 break;
8031 case BuiltinType::UShort:
8032 EncType = "us";
8033 break;
8034 case BuiltinType::Short:
8035 EncType = "ss";
8036 break;
8037 case BuiltinType::UInt:
8038 EncType = "ui";
8039 break;
8040 case BuiltinType::Int:
8041 EncType = "si";
8042 break;
8043 case BuiltinType::ULong:
8044 EncType = "ul";
8045 break;
8046 case BuiltinType::Long:
8047 EncType = "sl";
8048 break;
8049 case BuiltinType::ULongLong:
8050 EncType = "ull";
8051 break;
8052 case BuiltinType::LongLong:
8053 EncType = "sll";
8054 break;
8055 case BuiltinType::Float:
8056 EncType = "ft";
8057 break;
8058 case BuiltinType::Double:
8059 EncType = "d";
8060 break;
8061 case BuiltinType::LongDouble:
8062 EncType = "ld";
8063 break;
8064 default:
8065 return false;
8066 }
8067 Enc += EncType;
8068 return true;
8069}
8070
8071/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8072static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8073 const CodeGen::CodeGenModule &CGM,
8074 TypeStringCache &TSC) {
8075 Enc += "p(";
8076 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8077 return false;
8078 Enc += ')';
8079 return true;
8080}
8081
8082/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008083static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8084 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008085 const CodeGen::CodeGenModule &CGM,
8086 TypeStringCache &TSC, StringRef NoSizeEnc) {
8087 if (AT->getSizeModifier() != ArrayType::Normal)
8088 return false;
8089 Enc += "a(";
8090 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8091 CAT->getSize().toStringUnsigned(Enc);
8092 else
8093 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8094 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008095 // The Qualifiers should be attached to the type rather than the array.
8096 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008097 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8098 return false;
8099 Enc += ')';
8100 return true;
8101}
8102
8103/// Appends a function encoding to Enc, calling appendType for the return type
8104/// and the arguments.
8105static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8106 const CodeGen::CodeGenModule &CGM,
8107 TypeStringCache &TSC) {
8108 Enc += "f{";
8109 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8110 return false;
8111 Enc += "}(";
8112 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8113 // N.B. we are only interested in the adjusted param types.
8114 auto I = FPT->param_type_begin();
8115 auto E = FPT->param_type_end();
8116 if (I != E) {
8117 do {
8118 if (!appendType(Enc, *I, CGM, TSC))
8119 return false;
8120 ++I;
8121 if (I != E)
8122 Enc += ',';
8123 } while (I != E);
8124 if (FPT->isVariadic())
8125 Enc += ",va";
8126 } else {
8127 if (FPT->isVariadic())
8128 Enc += "va";
8129 else
8130 Enc += '0';
8131 }
8132 }
8133 Enc += ')';
8134 return true;
8135}
8136
8137/// Handles the type's qualifier before dispatching a call to handle specific
8138/// type encodings.
8139static bool appendType(SmallStringEnc &Enc, QualType QType,
8140 const CodeGen::CodeGenModule &CGM,
8141 TypeStringCache &TSC) {
8142
8143 QualType QT = QType.getCanonicalType();
8144
Robert Lytton6adb20f2014-06-05 09:06:21 +00008145 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8146 // The Qualifiers should be attached to the type rather than the array.
8147 // Thus we don't call appendQualifier() here.
8148 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8149
Robert Lytton844aeeb2014-05-02 09:33:20 +00008150 appendQualifier(Enc, QT);
8151
8152 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8153 return appendBuiltinType(Enc, BT);
8154
Robert Lytton844aeeb2014-05-02 09:33:20 +00008155 if (const PointerType *PT = QT->getAs<PointerType>())
8156 return appendPointerType(Enc, PT, CGM, TSC);
8157
8158 if (const EnumType *ET = QT->getAs<EnumType>())
8159 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8160
8161 if (const RecordType *RT = QT->getAsStructureType())
8162 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8163
8164 if (const RecordType *RT = QT->getAsUnionType())
8165 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8166
8167 if (const FunctionType *FT = QT->getAs<FunctionType>())
8168 return appendFunctionType(Enc, FT, CGM, TSC);
8169
8170 return false;
8171}
8172
8173static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8174 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8175 if (!D)
8176 return false;
8177
8178 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8179 if (FD->getLanguageLinkage() != CLanguageLinkage)
8180 return false;
8181 return appendType(Enc, FD->getType(), CGM, TSC);
8182 }
8183
8184 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8185 if (VD->getLanguageLinkage() != CLanguageLinkage)
8186 return false;
8187 QualType QT = VD->getType().getCanonicalType();
8188 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8189 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008190 // The Qualifiers should be attached to the type rather than the array.
8191 // Thus we don't call appendQualifier() here.
8192 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008193 }
8194 return appendType(Enc, QT, CGM, TSC);
8195 }
8196 return false;
8197}
8198
8199
Robert Lytton0e076492013-08-13 09:43:10 +00008200//===----------------------------------------------------------------------===//
8201// Driver code
8202//===----------------------------------------------------------------------===//
8203
Rafael Espindola9f834732014-09-19 01:54:22 +00008204bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008205 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008206}
8207
Chris Lattner2b037972010-07-29 02:01:43 +00008208const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008209 if (TheTargetCodeGenInfo)
8210 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008211
Reid Kleckner9305fd12016-04-13 23:37:17 +00008212 // Helper to set the unique_ptr while still keeping the return value.
8213 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8214 this->TheTargetCodeGenInfo.reset(P);
8215 return *P;
8216 };
8217
John McCallc8e01702013-04-16 22:48:15 +00008218 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008219 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008220 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008221 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008222
Derek Schuff09338a22012-09-06 17:37:28 +00008223 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008224 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008225 case llvm::Triple::mips:
8226 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008227 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008228 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8229 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008230
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008231 case llvm::Triple::mips64:
8232 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008233 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008234
Tim Northover25e8a672014-05-24 12:51:25 +00008235 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008236 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008237 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008238 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008239 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00008240
Reid Kleckner9305fd12016-04-13 23:37:17 +00008241 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008242 }
8243
Dan Gohmanc2853072015-09-03 22:51:53 +00008244 case llvm::Triple::wasm32:
8245 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008246 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008247
Daniel Dunbard59655c2009-09-12 00:59:49 +00008248 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008249 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008250 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008251 case llvm::Triple::thumbeb: {
8252 if (Triple.getOS() == llvm::Triple::Win32) {
8253 return SetCGInfo(
8254 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008255 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008256
Reid Kleckner9305fd12016-04-13 23:37:17 +00008257 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8258 StringRef ABIStr = getTarget().getABI();
8259 if (ABIStr == "apcs-gnu")
8260 Kind = ARMABIInfo::APCS;
8261 else if (ABIStr == "aapcs16")
8262 Kind = ARMABIInfo::AAPCS16_VFP;
8263 else if (CodeGenOpts.FloatABI == "hard" ||
8264 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008265 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008266 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008267 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008268 Kind = ARMABIInfo::AAPCS_VFP;
8269
8270 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8271 }
8272
John McCallea8d8bb2010-03-11 00:10:12 +00008273 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008274 return SetCGInfo(
8275 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008276 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008277 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008278 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008279 if (getTarget().getABI() == "elfv2")
8280 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008281 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008282 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008283
Hal Finkel415c2a32016-10-02 02:10:45 +00008284 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8285 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008286 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008287 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008288 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008289 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008290 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008291 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008292 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008293 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008294 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008295
Hal Finkel415c2a32016-10-02 02:10:45 +00008296 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8297 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008298 }
John McCallea8d8bb2010-03-11 00:10:12 +00008299
Peter Collingbournec947aae2012-05-20 23:28:41 +00008300 case llvm::Triple::nvptx:
8301 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008302 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008303
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008304 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008305 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008306
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008307 case llvm::Triple::systemz: {
8308 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008309 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008310 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008311
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008312 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008313 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008314 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008315
Eli Friedman33465822011-07-08 23:31:17 +00008316 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008317 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008318 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008319 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008320 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008321
John McCall1fe2a8c2013-06-18 02:46:29 +00008322 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008323 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8324 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8325 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008326 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008327 return SetCGInfo(new X86_32TargetCodeGenInfo(
8328 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8329 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8330 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008331 }
Eli Friedman33465822011-07-08 23:31:17 +00008332 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008333
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008334 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008335 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008336 X86AVXABILevel AVXLevel =
8337 (ABI == "avx512"
8338 ? X86AVXABILevel::AVX512
8339 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008340
Chris Lattner04dc9572010-08-31 16:44:54 +00008341 switch (Triple.getOS()) {
8342 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008343 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008344 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008345 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008346 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008347 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008348 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008349 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008350 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008351 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008352 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008353 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008354 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008355 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008356 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008357 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008358 case llvm::Triple::sparc:
8359 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008360 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008361 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008362 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008363 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008364 case llvm::Triple::spir:
8365 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008366 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008367 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008368}