blob: 19b63ce6213dc8d7af7334fd22af8c91772426c5 [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 Liu402804b2016-12-15 08:09:08 +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
Erich Keane521ed962017-01-05 00:20:51 +0000874/// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
875static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
876 auto AI = ABIArgInfo::getDirect(T);
877 AI.setInReg(true);
878 AI.setCanBeFlattened(false);
879 return AI;
880}
881
Chris Lattner0cf24192010-06-28 20:05:43 +0000882//===----------------------------------------------------------------------===//
883// X86-32 ABI Implementation
884//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000885
Reid Kleckner661f35b2014-01-18 01:12:41 +0000886/// \brief Similar to llvm::CCState, but for Clang.
887struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000888 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000889
890 unsigned CC;
891 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000892 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000893};
894
Erich Keane521ed962017-01-05 00:20:51 +0000895enum {
896 // Vectorcall only allows the first 6 parameters to be passed in registers.
897 VectorcallMaxParamNumAsReg = 6
898};
899
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000900/// X86_32ABIInfo - The X86-32 ABI information.
John McCall12f23522016-04-04 18:33:08 +0000901class X86_32ABIInfo : public SwiftABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000902 enum Class {
903 Integer,
904 Float
905 };
906
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000907 static const unsigned MinABIStackAlignInBytes = 4;
908
David Chisnallde3a0692009-08-17 23:08:21 +0000909 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000910 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000911 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000912 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000913 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000914 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000915
916 static bool isRegisterSize(unsigned Size) {
917 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
918 }
919
Reid Kleckner80944df2014-10-31 22:00:51 +0000920 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
921 // FIXME: Assumes vectorcall is in use.
922 return isX86VectorTypeForVectorCall(getContext(), Ty);
923 }
924
925 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
926 uint64_t NumMembers) const override {
927 // FIXME: Assumes vectorcall is in use.
928 return isX86VectorCallAggregateSmallEnough(NumMembers);
929 }
930
Reid Kleckner40ca9132014-05-13 22:05:45 +0000931 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000932
Daniel Dunbar557893d2010-04-21 19:10:51 +0000933 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
934 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000935 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
936
John McCall7f416cc2015-09-08 08:05:57 +0000937 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000938
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000939 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000940 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000941
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000942 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000943 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000944 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Erich Keane521ed962017-01-05 00:20:51 +0000945 ABIArgInfo reclassifyHvaArgType(QualType RetTy, CCState &State,
946 const ABIArgInfo& current) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000947 /// \brief Updates the number of available free registers, returns
948 /// true if any registers were allocated.
949 bool updateFreeRegs(QualType Ty, CCState &State) const;
950
951 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
952 bool &NeedsPadding) const;
953 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000954
Reid Kleckner04046052016-05-02 17:41:07 +0000955 bool canExpandIndirectArgument(QualType Ty) const;
956
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000957 /// \brief Rewrite the function info so that all memory arguments use
958 /// inalloca.
959 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
960
961 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000962 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000963 QualType Type) const;
Erich Keane521ed962017-01-05 00:20:51 +0000964 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
965 bool &UsedInAlloca) const;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000966
Rafael Espindola75419dc2012-07-23 23:30:29 +0000967public:
968
Craig Topper4f12f102014-03-12 06:41:41 +0000969 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000970 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
971 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000972
Michael Kupersteindc745202015-10-19 07:52:25 +0000973 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
974 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000975 unsigned NumRegisterParameters, bool SoftFloatABI)
John McCall12f23522016-04-04 18:33:08 +0000976 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
Michael Kupersteindc745202015-10-19 07:52:25 +0000977 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
978 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000979 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000980 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000981 DefaultNumRegisterParameters(NumRegisterParameters) {}
John McCall12f23522016-04-04 18:33:08 +0000982
983 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
984 ArrayRef<llvm::Type*> scalars,
985 bool asReturnValue) const override {
986 // LLVM's x86-32 lowering currently only assigns up to three
987 // integer registers and three fp registers. Oddly, it'll use up to
988 // four vector registers for vectors, but those can overlap with the
989 // scalar registers.
990 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
991 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +0000992
993 bool isSwiftErrorInRegister() const override {
994 // x86-32 lowering does not support passing swifterror in a register.
995 return false;
996 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000997};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000998
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000999class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1000public:
Michael Kupersteindc745202015-10-19 07:52:25 +00001001 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1002 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001003 unsigned NumRegisterParameters, bool SoftFloatABI)
1004 : TargetCodeGenInfo(new X86_32ABIInfo(
1005 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1006 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +00001007
John McCall1fe2a8c2013-06-18 02:46:29 +00001008 static bool isStructReturnInRegABI(
1009 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1010
Eric Christopher162c91c2015-06-05 22:03:00 +00001011 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00001012 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +00001013
Craig Topper4f12f102014-03-12 06:41:41 +00001014 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001015 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +00001016 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +00001017 return 4;
1018 }
1019
1020 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001021 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001022
Jay Foad7c57be32011-07-11 09:56:20 +00001023 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001024 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001025 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001026 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1027 }
1028
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001029 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1030 std::string &Constraints,
1031 std::vector<llvm::Type *> &ResultRegTypes,
1032 std::vector<llvm::Type *> &ResultTruncRegTypes,
1033 std::vector<LValue> &ResultRegDests,
1034 std::string &AsmString,
1035 unsigned NumOutputs) const override;
1036
Craig Topper4f12f102014-03-12 06:41:41 +00001037 llvm::Constant *
1038 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001039 unsigned Sig = (0xeb << 0) | // jmp rel8
1040 (0x06 << 8) | // .+0x08
1041 ('F' << 16) |
1042 ('T' << 24);
1043 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1044 }
John McCall01391782016-02-05 21:37:38 +00001045
1046 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1047 return "movl\t%ebp, %ebp"
1048 "\t\t## marker for objc_retainAutoreleaseReturnValue";
1049 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001050};
1051
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001052}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001053
Reid Kleckner9b3e3df2014-09-04 20:04:38 +00001054/// Rewrite input constraint references after adding some output constraints.
1055/// In the case where there is one output and one input and we add one output,
1056/// we need to replace all operand references greater than or equal to 1:
1057/// mov $0, $1
1058/// mov eax, $1
1059/// The result will be:
1060/// mov $0, $2
1061/// mov eax, $2
1062static void rewriteInputConstraintReferences(unsigned FirstIn,
1063 unsigned NumNewOuts,
1064 std::string &AsmString) {
1065 std::string Buf;
1066 llvm::raw_string_ostream OS(Buf);
1067 size_t Pos = 0;
1068 while (Pos < AsmString.size()) {
1069 size_t DollarStart = AsmString.find('$', Pos);
1070 if (DollarStart == std::string::npos)
1071 DollarStart = AsmString.size();
1072 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1073 if (DollarEnd == std::string::npos)
1074 DollarEnd = AsmString.size();
1075 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1076 Pos = DollarEnd;
1077 size_t NumDollars = DollarEnd - DollarStart;
1078 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1079 // We have an operand reference.
1080 size_t DigitStart = Pos;
1081 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1082 if (DigitEnd == std::string::npos)
1083 DigitEnd = AsmString.size();
1084 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1085 unsigned OperandIndex;
1086 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1087 if (OperandIndex >= FirstIn)
1088 OperandIndex += NumNewOuts;
1089 OS << OperandIndex;
1090 } else {
1091 OS << OperandStr;
1092 }
1093 Pos = DigitEnd;
1094 }
1095 }
1096 AsmString = std::move(OS.str());
1097}
1098
1099/// Add output constraints for EAX:EDX because they are return registers.
1100void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1101 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1102 std::vector<llvm::Type *> &ResultRegTypes,
1103 std::vector<llvm::Type *> &ResultTruncRegTypes,
1104 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1105 unsigned NumOutputs) const {
1106 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1107
1108 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1109 // larger.
1110 if (!Constraints.empty())
1111 Constraints += ',';
1112 if (RetWidth <= 32) {
1113 Constraints += "={eax}";
1114 ResultRegTypes.push_back(CGF.Int32Ty);
1115 } else {
1116 // Use the 'A' constraint for EAX:EDX.
1117 Constraints += "=A";
1118 ResultRegTypes.push_back(CGF.Int64Ty);
1119 }
1120
1121 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1122 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1123 ResultTruncRegTypes.push_back(CoerceTy);
1124
1125 // Coerce the integer by bitcasting the return slot pointer.
1126 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1127 CoerceTy->getPointerTo()));
1128 ResultRegDests.push_back(ReturnSlot);
1129
1130 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1131}
1132
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001133/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001134/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001135bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1136 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001137 uint64_t Size = Context.getTypeSize(Ty);
1138
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001139 // For i386, type must be register sized.
1140 // For the MCU ABI, it only needs to be <= 8-byte
1141 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1142 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001143
1144 if (Ty->isVectorType()) {
1145 // 64- and 128- bit vectors inside structures are not returned in
1146 // registers.
1147 if (Size == 64 || Size == 128)
1148 return false;
1149
1150 return true;
1151 }
1152
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001153 // If this is a builtin, pointer, enum, complex type, member pointer, or
1154 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001155 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001156 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001157 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001158 return true;
1159
1160 // Arrays are treated like records.
1161 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001162 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001163
1164 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001165 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001166 if (!RT) return false;
1167
Anders Carlsson40446e82010-01-27 03:25:19 +00001168 // FIXME: Traverse bases here too.
1169
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001170 // Structure types are passed in register if all fields would be
1171 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001172 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001173 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001174 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001175 continue;
1176
1177 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001178 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001179 return false;
1180 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001181 return true;
1182}
1183
Reid Kleckner04046052016-05-02 17:41:07 +00001184static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1185 // Treat complex types as the element type.
1186 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1187 Ty = CTy->getElementType();
1188
1189 // Check for a type which we know has a simple scalar argument-passing
1190 // convention without any padding. (We're specifically looking for 32
1191 // and 64-bit integer and integer-equivalents, float, and double.)
1192 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1193 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1194 return false;
1195
1196 uint64_t Size = Context.getTypeSize(Ty);
1197 return Size == 32 || Size == 64;
1198}
1199
Reid Kleckner791bbf62017-01-13 17:18:19 +00001200static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1201 uint64_t &Size) {
1202 for (const auto *FD : RD->fields()) {
1203 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1204 // argument is smaller than 32-bits, expanding the struct will create
1205 // alignment padding.
1206 if (!is32Or64BitBasicType(FD->getType(), Context))
1207 return false;
1208
1209 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1210 // how to expand them yet, and the predicate for telling if a bitfield still
1211 // counts as "basic" is more complicated than what we were doing previously.
1212 if (FD->isBitField())
1213 return false;
1214
1215 Size += Context.getTypeSize(FD->getType());
1216 }
1217 return true;
1218}
1219
1220static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1221 uint64_t &Size) {
1222 // Don't do this if there are any non-empty bases.
1223 for (const CXXBaseSpecifier &Base : RD->bases()) {
1224 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1225 Size))
1226 return false;
1227 }
1228 if (!addFieldSizes(Context, RD, Size))
1229 return false;
1230 return true;
1231}
1232
Reid Kleckner04046052016-05-02 17:41:07 +00001233/// Test whether an argument type which is to be passed indirectly (on the
1234/// stack) would have the equivalent layout if it was expanded into separate
1235/// arguments. If so, we prefer to do the latter to avoid inhibiting
1236/// optimizations.
1237bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1238 // We can only expand structure types.
1239 const RecordType *RT = Ty->getAs<RecordType>();
1240 if (!RT)
1241 return false;
1242 const RecordDecl *RD = RT->getDecl();
Reid Kleckner791bbf62017-01-13 17:18:19 +00001243 uint64_t Size = 0;
Reid Kleckner04046052016-05-02 17:41:07 +00001244 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Reid Kleckner791bbf62017-01-13 17:18:19 +00001245 if (!IsWin32StructABI) {
Reid Kleckner04046052016-05-02 17:41:07 +00001246 // On non-Windows, we have to conservatively match our old bitcode
1247 // prototypes in order to be ABI-compatible at the bitcode level.
1248 if (!CXXRD->isCLike())
1249 return false;
1250 } else {
1251 // Don't do this for dynamic classes.
1252 if (CXXRD->isDynamicClass())
1253 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001254 }
Reid Kleckner791bbf62017-01-13 17:18:19 +00001255 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001256 return false;
Reid Kleckner791bbf62017-01-13 17:18:19 +00001257 } else {
1258 if (!addFieldSizes(getContext(), RD, Size))
Reid Kleckner04046052016-05-02 17:41:07 +00001259 return false;
Reid Kleckner04046052016-05-02 17:41:07 +00001260 }
1261
1262 // We can do this if there was no alignment padding.
1263 return Size == getContext().getTypeSize(Ty);
1264}
1265
John McCall7f416cc2015-09-08 08:05:57 +00001266ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001267 // If the return value is indirect, then the hidden argument is consuming one
1268 // integer register.
1269 if (State.FreeRegs) {
1270 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001271 if (!IsMCUABI)
1272 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001273 }
John McCall7f416cc2015-09-08 08:05:57 +00001274 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001275}
1276
Eric Christopher7565e0d2015-05-29 23:09:49 +00001277ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1278 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001279 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001280 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001281
Reid Kleckner80944df2014-10-31 22:00:51 +00001282 const Type *Base = nullptr;
1283 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001284 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1285 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001286 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1287 // The LLVM struct type for such an aggregate should lower properly.
1288 return ABIArgInfo::getDirect();
1289 }
1290
Chris Lattner458b2aa2010-07-29 02:16:43 +00001291 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001292 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001293 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001294 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001295
1296 // 128-bit vectors are a special case; they are returned in
1297 // registers and we need to make sure to pick a type the LLVM
1298 // backend will like.
1299 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001300 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001301 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001302
1303 // Always return in register if it fits in a general purpose
1304 // register, or if it is 64 bits and has a single element.
1305 if ((Size == 8 || Size == 16 || Size == 32) ||
1306 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001307 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001308 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001309
John McCall7f416cc2015-09-08 08:05:57 +00001310 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001311 }
1312
1313 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001314 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001315
John McCalla1dee5302010-08-22 10:59:02 +00001316 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001317 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001318 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001319 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001320 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001321 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001322
David Chisnallde3a0692009-08-17 23:08:21 +00001323 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001324 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001325 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001326
Denis Zobnin380b2242016-02-11 11:26:03 +00001327 // Ignore empty structs/unions.
1328 if (isEmptyRecord(getContext(), RetTy, true))
1329 return ABIArgInfo::getIgnore();
1330
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001331 // Small structures which are register sized are generally returned
1332 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001333 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001334 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001335
1336 // As a special-case, if the struct is a "single-element" struct, and
1337 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001338 // floating-point register. (MSVC does not apply this special case.)
1339 // We apply a similar transformation for pointer types to improve the
1340 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001341 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001342 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001343 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001344 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1345
1346 // FIXME: We should be able to narrow this integer in cases with dead
1347 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001348 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001349 }
1350
John McCall7f416cc2015-09-08 08:05:57 +00001351 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001352 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001353
Chris Lattner458b2aa2010-07-29 02:16:43 +00001354 // Treat an enum type as its underlying type.
1355 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1356 RetTy = EnumTy->getDecl()->getIntegerType();
1357
1358 return (RetTy->isPromotableIntegerType() ?
1359 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001360}
1361
Eli Friedman7919bea2012-06-05 19:40:46 +00001362static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1363 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1364}
1365
Daniel Dunbared23de32010-09-16 20:42:00 +00001366static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1367 const RecordType *RT = Ty->getAs<RecordType>();
1368 if (!RT)
1369 return 0;
1370 const RecordDecl *RD = RT->getDecl();
1371
1372 // If this is a C++ record, check the bases first.
1373 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001374 for (const auto &I : CXXRD->bases())
1375 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001376 return false;
1377
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001378 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001379 QualType FT = i->getType();
1380
Eli Friedman7919bea2012-06-05 19:40:46 +00001381 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001382 return true;
1383
1384 if (isRecordWithSSEVectorType(Context, FT))
1385 return true;
1386 }
1387
1388 return false;
1389}
1390
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001391unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1392 unsigned Align) const {
1393 // Otherwise, if the alignment is less than or equal to the minimum ABI
1394 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001395 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001396 return 0; // Use default alignment.
1397
1398 // On non-Darwin, the stack type alignment is always 4.
1399 if (!IsDarwinVectorABI) {
1400 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001401 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001402 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001403
Daniel Dunbared23de32010-09-16 20:42:00 +00001404 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001405 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1406 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001407 return 16;
1408
1409 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001410}
1411
Rafael Espindola703c47f2012-10-19 05:04:37 +00001412ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001413 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001414 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001415 if (State.FreeRegs) {
1416 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001417 if (!IsMCUABI)
1418 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001419 }
John McCall7f416cc2015-09-08 08:05:57 +00001420 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001421 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001422
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001423 // Compute the byval alignment.
1424 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1425 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1426 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001427 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001428
1429 // If the stack alignment is less than the type alignment, realign the
1430 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001431 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001432 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1433 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001434}
1435
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001436X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1437 const Type *T = isSingleElementStruct(Ty, getContext());
1438 if (!T)
1439 T = Ty.getTypePtr();
1440
1441 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1442 BuiltinType::Kind K = BT->getKind();
1443 if (K == BuiltinType::Float || K == BuiltinType::Double)
1444 return Float;
1445 }
1446 return Integer;
1447}
1448
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001449bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001450 if (!IsSoftFloatABI) {
1451 Class C = classify(Ty);
1452 if (C == Float)
1453 return false;
1454 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001455
Rafael Espindola077dd592012-10-24 01:58:58 +00001456 unsigned Size = getContext().getTypeSize(Ty);
1457 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001458
1459 if (SizeInRegs == 0)
1460 return false;
1461
Michael Kuperstein68901882015-10-25 08:18:20 +00001462 if (!IsMCUABI) {
1463 if (SizeInRegs > State.FreeRegs) {
1464 State.FreeRegs = 0;
1465 return false;
1466 }
1467 } else {
1468 // The MCU psABI allows passing parameters in-reg even if there are
1469 // earlier parameters that are passed on the stack. Also,
1470 // it does not allow passing >8-byte structs in-register,
1471 // even if there are 3 free registers available.
1472 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1473 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001474 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001475
Reid Kleckner661f35b2014-01-18 01:12:41 +00001476 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001477 return true;
1478}
1479
1480bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1481 bool &InReg,
1482 bool &NeedsPadding) const {
Reid Kleckner04046052016-05-02 17:41:07 +00001483 // On Windows, aggregates other than HFAs are never passed in registers, and
1484 // they do not consume register slots. Homogenous floating-point aggregates
1485 // (HFAs) have already been dealt with at this point.
1486 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1487 return false;
1488
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001489 NeedsPadding = false;
1490 InReg = !IsMCUABI;
1491
1492 if (!updateFreeRegs(Ty, State))
1493 return false;
1494
1495 if (IsMCUABI)
1496 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001497
Reid Kleckner80944df2014-10-31 22:00:51 +00001498 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001499 State.CC == llvm::CallingConv::X86_VectorCall ||
1500 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001501 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001502 NeedsPadding = true;
1503
Rafael Espindola077dd592012-10-24 01:58:58 +00001504 return false;
1505 }
1506
Rafael Espindola703c47f2012-10-19 05:04:37 +00001507 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001508}
1509
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001510bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1511 if (!updateFreeRegs(Ty, State))
1512 return false;
1513
1514 if (IsMCUABI)
1515 return false;
1516
1517 if (State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001518 State.CC == llvm::CallingConv::X86_VectorCall ||
1519 State.CC == llvm::CallingConv::X86_RegCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001520 if (getContext().getTypeSize(Ty) > 32)
1521 return false;
1522
1523 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1524 Ty->isReferenceType());
1525 }
1526
1527 return true;
1528}
1529
Erich Keane521ed962017-01-05 00:20:51 +00001530ABIArgInfo
1531X86_32ABIInfo::reclassifyHvaArgType(QualType Ty, CCState &State,
1532 const ABIArgInfo &current) const {
1533 // Assumes vectorCall calling convention.
1534 const Type *Base = nullptr;
1535 uint64_t NumElts = 0;
1536
1537 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
1538 isHomogeneousAggregate(Ty, Base, NumElts)) {
1539 if (State.FreeSSERegs >= NumElts) {
1540 // HVA types get passed directly in registers if there is room.
1541 State.FreeSSERegs -= NumElts;
1542 return getDirectX86Hva();
1543 }
1544 // If there's no room, the HVA gets passed as normal indirect
1545 // structure.
1546 return getIndirectResult(Ty, /*ByVal=*/false, State);
1547 }
1548 return current;
1549}
1550
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001551ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1552 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001553 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001554
Reid Klecknerb1be6832014-11-15 01:41:41 +00001555 Ty = useFirstFieldIfTransparentUnion(Ty);
1556
Reid Kleckner80944df2014-10-31 22:00:51 +00001557 // Check with the C++ ABI first.
1558 const RecordType *RT = Ty->getAs<RecordType>();
1559 if (RT) {
1560 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1561 if (RAA == CGCXXABI::RAA_Indirect) {
1562 return getIndirectResult(Ty, false, State);
1563 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1564 // The field index doesn't matter, we'll fix it up later.
1565 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1566 }
1567 }
1568
1569 // vectorcall adds the concept of a homogenous vector aggregate, similar
Erich Keane521ed962017-01-05 00:20:51 +00001570 // to other targets, regcall uses some of the HVA rules.
Reid Kleckner80944df2014-10-31 22:00:51 +00001571 const Type *Base = nullptr;
1572 uint64_t NumElts = 0;
Erich Keane757d3172016-11-02 18:29:35 +00001573 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1574 State.CC == llvm::CallingConv::X86_RegCall) &&
Reid Kleckner80944df2014-10-31 22:00:51 +00001575 isHomogeneousAggregate(Ty, Base, NumElts)) {
Erich Keane521ed962017-01-05 00:20:51 +00001576
1577 if (State.CC == llvm::CallingConv::X86_RegCall) {
1578 if (State.FreeSSERegs >= NumElts) {
1579 State.FreeSSERegs -= NumElts;
1580 if (Ty->isBuiltinType() || Ty->isVectorType())
1581 return ABIArgInfo::getDirect();
1582 return ABIArgInfo::getExpand();
1583
1584 }
1585 return getIndirectResult(Ty, /*ByVal=*/false, State);
1586 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1587 if (State.FreeSSERegs >= NumElts && (Ty->isBuiltinType() || Ty->isVectorType())) {
1588 // Actual floating-point types get registers first time through if
1589 // there is registers available
1590 State.FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00001591 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00001592 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
1593 // HVA Types only get registers after everything else has been
1594 // set, so it gets set as indirect for now.
1595 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty));
1596 }
Reid Kleckner80944df2014-10-31 22:00:51 +00001597 }
Reid Kleckner80944df2014-10-31 22:00:51 +00001598 }
1599
1600 if (isAggregateTypeForABI(Ty)) {
Reid Kleckner04046052016-05-02 17:41:07 +00001601 // Structures with flexible arrays are always indirect.
1602 // FIXME: This should not be byval!
1603 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1604 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001605
Reid Kleckner04046052016-05-02 17:41:07 +00001606 // Ignore empty structs/unions on non-Windows.
1607 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001608 return ABIArgInfo::getIgnore();
1609
Rafael Espindolafad28de2012-10-24 01:59:00 +00001610 llvm::LLVMContext &LLVMContext = getVMContext();
1611 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Reid Kleckner04046052016-05-02 17:41:07 +00001612 bool NeedsPadding = false;
1613 bool InReg;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001614 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001615 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001616 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001617 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001618 if (InReg)
1619 return ABIArgInfo::getDirectInReg(Result);
1620 else
1621 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001622 }
Craig Topper8a13c412014-05-21 05:09:00 +00001623 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001624
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001625 // Expand small (<= 128-bit) record types when we know that the stack layout
1626 // of those arguments will match the struct. This is important because the
1627 // LLVM backend isn't smart enough to remove byval, which inhibits many
1628 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001629 // Don't do this for the MCU if there are still free integer registers
1630 // (see X86_64 ABI for full explanation).
Reid Kleckner04046052016-05-02 17:41:07 +00001631 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1632 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001633 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001634 State.CC == llvm::CallingConv::X86_FastCall ||
Erich Keane757d3172016-11-02 18:29:35 +00001635 State.CC == llvm::CallingConv::X86_VectorCall ||
1636 State.CC == llvm::CallingConv::X86_RegCall,
Reid Kleckner80944df2014-10-31 22:00:51 +00001637 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001638
Reid Kleckner661f35b2014-01-18 01:12:41 +00001639 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001640 }
1641
Chris Lattnerd774ae92010-08-26 20:05:13 +00001642 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001643 // On Darwin, some vectors are passed in memory, we handle this by passing
1644 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001645 if (IsDarwinVectorABI) {
1646 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001647 if ((Size == 8 || Size == 16 || Size == 32) ||
1648 (Size == 64 && VT->getNumElements() == 1))
1649 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1650 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001651 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001652
Chad Rosier651c1832013-03-25 21:00:27 +00001653 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1654 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001655
Chris Lattnerd774ae92010-08-26 20:05:13 +00001656 return ABIArgInfo::getDirect();
1657 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001658
1659
Chris Lattner458b2aa2010-07-29 02:16:43 +00001660 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1661 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001662
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001663 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001664
1665 if (Ty->isPromotableIntegerType()) {
1666 if (InReg)
1667 return ABIArgInfo::getExtendInReg();
1668 return ABIArgInfo::getExtend();
1669 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001670
Rafael Espindola703c47f2012-10-19 05:04:37 +00001671 if (InReg)
1672 return ABIArgInfo::getDirectInReg();
1673 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001674}
1675
Erich Keane521ed962017-01-05 00:20:51 +00001676void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1677 bool &UsedInAlloca) const {
1678 // Vectorcall only allows the first 6 parameters to be passed in registers,
1679 // and homogeneous vector aggregates are only put into registers as a second
1680 // priority.
1681 unsigned Count = 0;
1682 CCState ZeroState = State;
1683 ZeroState.FreeRegs = ZeroState.FreeSSERegs = 0;
1684 // HVAs must be done as a second priority for registers, so the deferred
1685 // items are dealt with by going through the pattern a second time.
1686 for (auto &I : FI.arguments()) {
1687 if (Count < VectorcallMaxParamNumAsReg)
1688 I.info = classifyArgumentType(I.type, State);
1689 else
1690 // Parameters after the 6th cannot be passed in registers,
1691 // so pretend there are no registers left for them.
1692 I.info = classifyArgumentType(I.type, ZeroState);
1693 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1694 ++Count;
1695 }
1696 Count = 0;
1697 // Go through the arguments a second time to get HVAs registers if there
1698 // are still some available.
1699 for (auto &I : FI.arguments()) {
1700 if (Count < VectorcallMaxParamNumAsReg)
1701 I.info = reclassifyHvaArgType(I.type, State, I.info);
1702 ++Count;
1703 }
1704}
1705
Rafael Espindolaa6472962012-07-24 00:01:07 +00001706void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001707 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001708 if (IsMCUABI)
1709 State.FreeRegs = 3;
1710 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001711 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001712 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1713 State.FreeRegs = 2;
1714 State.FreeSSERegs = 6;
1715 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001716 State.FreeRegs = FI.getRegParm();
Erich Keane757d3172016-11-02 18:29:35 +00001717 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1718 State.FreeRegs = 5;
1719 State.FreeSSERegs = 8;
1720 } else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001721 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001722
Reid Kleckner677539d2014-07-10 01:58:55 +00001723 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001724 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001725 } else if (FI.getReturnInfo().isIndirect()) {
1726 // The C++ ABI is not aware of register usage, so we have to check if the
1727 // return value was sret and put it in a register ourselves if appropriate.
1728 if (State.FreeRegs) {
1729 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001730 if (!IsMCUABI)
1731 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001732 }
1733 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001734
Peter Collingbournef7706832014-12-12 23:41:25 +00001735 // The chain argument effectively gives us another free register.
1736 if (FI.isChainCall())
1737 ++State.FreeRegs;
1738
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001739 bool UsedInAlloca = false;
Erich Keane521ed962017-01-05 00:20:51 +00001740 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1741 computeVectorCallArgs(FI, State, UsedInAlloca);
1742 } else {
1743 // If not vectorcall, revert to normal behavior.
1744 for (auto &I : FI.arguments()) {
1745 I.info = classifyArgumentType(I.type, State);
1746 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1747 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001748 }
1749
1750 // If we needed to use inalloca for any argument, do a second pass and rewrite
1751 // all the memory arguments to use inalloca.
1752 if (UsedInAlloca)
1753 rewriteWithInAlloca(FI);
1754}
1755
1756void
1757X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001758 CharUnits &StackOffset, ABIArgInfo &Info,
1759 QualType Type) const {
1760 // Arguments are always 4-byte-aligned.
1761 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1762
1763 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001764 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1765 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001766 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001767
John McCall7f416cc2015-09-08 08:05:57 +00001768 // Insert padding bytes to respect alignment.
1769 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001770 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001771 if (StackOffset != FieldEnd) {
1772 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001773 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001774 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001775 FrameFields.push_back(Ty);
1776 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001777}
1778
Reid Kleckner852361d2014-07-26 00:12:26 +00001779static bool isArgInAlloca(const ABIArgInfo &Info) {
1780 // Leave ignored and inreg arguments alone.
1781 switch (Info.getKind()) {
1782 case ABIArgInfo::InAlloca:
1783 return true;
1784 case ABIArgInfo::Indirect:
1785 assert(Info.getIndirectByVal());
1786 return true;
1787 case ABIArgInfo::Ignore:
1788 return false;
1789 case ABIArgInfo::Direct:
1790 case ABIArgInfo::Extend:
Reid Kleckner852361d2014-07-26 00:12:26 +00001791 if (Info.getInReg())
1792 return false;
1793 return true;
Reid Kleckner04046052016-05-02 17:41:07 +00001794 case ABIArgInfo::Expand:
1795 case ABIArgInfo::CoerceAndExpand:
1796 // These are aggregate types which are never passed in registers when
1797 // inalloca is involved.
1798 return true;
Reid Kleckner852361d2014-07-26 00:12:26 +00001799 }
1800 llvm_unreachable("invalid enum");
1801}
1802
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001803void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1804 assert(IsWin32StructABI && "inalloca only supported on win32");
1805
1806 // Build a packed struct type for all of the arguments in memory.
1807 SmallVector<llvm::Type *, 6> FrameFields;
1808
John McCall7f416cc2015-09-08 08:05:57 +00001809 // The stack alignment is always 4.
1810 CharUnits StackAlign = CharUnits::fromQuantity(4);
1811
1812 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001813 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1814
1815 // Put 'this' into the struct before 'sret', if necessary.
1816 bool IsThisCall =
1817 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1818 ABIArgInfo &Ret = FI.getReturnInfo();
1819 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1820 isArgInAlloca(I->info)) {
1821 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1822 ++I;
1823 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001824
1825 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001826 if (Ret.isIndirect() && !Ret.getInReg()) {
1827 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1828 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001829 // On Windows, the hidden sret parameter is always returned in eax.
1830 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001831 }
1832
1833 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001834 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001835 ++I;
1836
1837 // Put arguments passed in memory into the struct.
1838 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001839 if (isArgInAlloca(I->info))
1840 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001841 }
1842
1843 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001844 /*isPacked=*/true),
1845 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001846}
1847
John McCall7f416cc2015-09-08 08:05:57 +00001848Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1849 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001850
John McCall7f416cc2015-09-08 08:05:57 +00001851 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001852
John McCall7f416cc2015-09-08 08:05:57 +00001853 // x86-32 changes the alignment of certain arguments on the stack.
1854 //
1855 // Just messing with TypeInfo like this works because we never pass
1856 // anything indirectly.
1857 TypeInfo.second = CharUnits::fromQuantity(
1858 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001859
John McCall7f416cc2015-09-08 08:05:57 +00001860 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1861 TypeInfo, CharUnits::fromQuantity(4),
1862 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001863}
1864
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001865bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1866 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1867 assert(Triple.getArch() == llvm::Triple::x86);
1868
1869 switch (Opts.getStructReturnConvention()) {
1870 case CodeGenOptions::SRCK_Default:
1871 break;
1872 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1873 return false;
1874 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1875 return true;
1876 }
1877
Michael Kupersteind749f232015-10-27 07:46:22 +00001878 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001879 return true;
1880
1881 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001882 case llvm::Triple::DragonFly:
1883 case llvm::Triple::FreeBSD:
1884 case llvm::Triple::OpenBSD:
1885 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001886 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001887 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001888 default:
1889 return false;
1890 }
1891}
1892
Eric Christopher162c91c2015-06-05 22:03:00 +00001893void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001894 llvm::GlobalValue *GV,
1895 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001896 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001897 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1898 // Get the LLVM function.
1899 llvm::Function *Fn = cast<llvm::Function>(GV);
1900
1901 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001902 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001903 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001904 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1905 llvm::AttributeSet::get(CGM.getLLVMContext(),
1906 llvm::AttributeSet::FunctionIndex,
1907 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001908 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001909 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1910 llvm::Function *Fn = cast<llvm::Function>(GV);
1911 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1912 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001913 }
1914}
1915
John McCallbeec5a02010-03-06 00:35:14 +00001916bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1917 CodeGen::CodeGenFunction &CGF,
1918 llvm::Value *Address) const {
1919 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001920
Chris Lattnerece04092012-02-07 00:39:47 +00001921 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001922
John McCallbeec5a02010-03-06 00:35:14 +00001923 // 0-7 are the eight integer registers; the order is different
1924 // on Darwin (for EH), but the range is the same.
1925 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001926 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001927
John McCallc8e01702013-04-16 22:48:15 +00001928 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001929 // 12-16 are st(0..4). Not sure why we stop at 4.
1930 // These have size 16, which is sizeof(long double) on
1931 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001932 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001933 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001934
John McCallbeec5a02010-03-06 00:35:14 +00001935 } else {
1936 // 9 is %eflags, which doesn't get a size on Darwin for some
1937 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001938 Builder.CreateAlignedStore(
1939 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1940 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001941
1942 // 11-16 are st(0..5). Not sure why we stop at 5.
1943 // These have size 12, which is sizeof(long double) on
1944 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001945 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001946 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1947 }
John McCallbeec5a02010-03-06 00:35:14 +00001948
1949 return false;
1950}
1951
Chris Lattner0cf24192010-06-28 20:05:43 +00001952//===----------------------------------------------------------------------===//
1953// X86-64 ABI Implementation
1954//===----------------------------------------------------------------------===//
1955
1956
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001957namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001958/// The AVX ABI level for X86 targets.
1959enum class X86AVXABILevel {
1960 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001961 AVX,
1962 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001963};
1964
1965/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1966static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1967 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001968 case X86AVXABILevel::AVX512:
1969 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001970 case X86AVXABILevel::AVX:
1971 return 256;
1972 case X86AVXABILevel::None:
1973 return 128;
1974 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001975 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001976}
1977
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001978/// X86_64ABIInfo - The X86_64 ABI information.
John McCall12f23522016-04-04 18:33:08 +00001979class X86_64ABIInfo : public SwiftABIInfo {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001980 enum Class {
1981 Integer = 0,
1982 SSE,
1983 SSEUp,
1984 X87,
1985 X87Up,
1986 ComplexX87,
1987 NoClass,
1988 Memory
1989 };
1990
1991 /// merge - Implement the X86_64 ABI merging algorithm.
1992 ///
1993 /// Merge an accumulating classification \arg Accum with a field
1994 /// classification \arg Field.
1995 ///
1996 /// \param Accum - The accumulating classification. This should
1997 /// always be either NoClass or the result of a previous merge
1998 /// call. In addition, this should never be Memory (the caller
1999 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002000 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002001
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002002 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2003 ///
2004 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2005 /// final MEMORY or SSE classes when necessary.
2006 ///
2007 /// \param AggregateSize - The size of the current aggregate in
2008 /// the classification process.
2009 ///
2010 /// \param Lo - The classification for the parts of the type
2011 /// residing in the low word of the containing object.
2012 ///
2013 /// \param Hi - The classification for the parts of the type
2014 /// residing in the higher words of the containing object.
2015 ///
2016 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2017
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002018 /// classify - Determine the x86_64 register classes in which the
2019 /// given type T should be passed.
2020 ///
2021 /// \param Lo - The classification for the parts of the type
2022 /// residing in the low word of the containing object.
2023 ///
2024 /// \param Hi - The classification for the parts of the type
2025 /// residing in the high word of the containing object.
2026 ///
2027 /// \param OffsetBase - The bit offset of this type in the
2028 /// containing object. Some parameters are classified different
2029 /// depending on whether they straddle an eightbyte boundary.
2030 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00002031 /// \param isNamedArg - Whether the argument in question is a "named"
2032 /// argument, as used in AMD64-ABI 3.5.7.
2033 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002034 /// If a word is unused its result will be NoClass; if a type should
2035 /// be passed in Memory then at least the classification of \arg Lo
2036 /// will be Memory.
2037 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00002038 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002039 ///
2040 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2041 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00002042 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2043 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002044
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002045 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002046 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2047 unsigned IROffset, QualType SourceTy,
2048 unsigned SourceOffset) const;
2049 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2050 unsigned IROffset, QualType SourceTy,
2051 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002052
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002053 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00002054 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00002055 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00002056
2057 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002058 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002059 ///
2060 /// \param freeIntRegs - The number of free integer registers remaining
2061 /// available.
2062 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002063
Chris Lattner458b2aa2010-07-29 02:16:43 +00002064 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002065
Erich Keane757d3172016-11-02 18:29:35 +00002066 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2067 unsigned &neededInt, unsigned &neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00002068 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002069
Erich Keane757d3172016-11-02 18:29:35 +00002070 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2071 unsigned &NeededSSE) const;
2072
2073 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2074 unsigned &NeededSSE) const;
2075
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002076 bool IsIllegalVectorType(QualType Ty) const;
2077
John McCalle0fda732011-04-21 01:20:55 +00002078 /// The 0.98 ABI revision clarified a lot of ambiguities,
2079 /// unfortunately in ways that were not always consistent with
2080 /// certain previous compilers. In particular, platforms which
2081 /// required strict binary compatibility with older versions of GCC
2082 /// may need to exempt themselves.
2083 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00002084 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00002085 }
2086
David Majnemere2ae2282016-03-04 05:26:16 +00002087 /// GCC classifies <1 x long long> as SSE but compatibility with older clang
2088 // compilers require us to classify it as INTEGER.
2089 bool classifyIntegerMMXAsSSE() const {
2090 const llvm::Triple &Triple = getTarget().getTriple();
2091 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2092 return false;
2093 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2094 return false;
2095 return true;
2096 }
2097
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002098 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00002099 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2100 // 64-bit hardware.
2101 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002102
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002103public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002104 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
John McCall12f23522016-04-04 18:33:08 +00002105 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00002106 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00002107 }
Chris Lattner22a931e2010-06-29 06:01:59 +00002108
John McCalla729c622012-02-17 03:33:10 +00002109 bool isPassedUsingAVXType(QualType type) const {
2110 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002111 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00002112 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2113 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00002114 if (info.isDirect()) {
2115 llvm::Type *ty = info.getCoerceToType();
2116 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2117 return (vectorTy->getBitWidth() > 128);
2118 }
2119 return false;
2120 }
2121
Craig Topper4f12f102014-03-12 06:41:41 +00002122 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002123
John McCall7f416cc2015-09-08 08:05:57 +00002124 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2125 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00002126 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2127 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002128
2129 bool has64BitPointers() const {
2130 return Has64BitPointers;
2131 }
John McCall12f23522016-04-04 18:33:08 +00002132
2133 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2134 ArrayRef<llvm::Type*> scalars,
2135 bool asReturnValue) const override {
2136 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2137 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002138 bool isSwiftErrorInRegister() const override {
2139 return true;
2140 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002141};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002142
Chris Lattner04dc9572010-08-31 16:44:54 +00002143/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002144class WinX86_64ABIInfo : public SwiftABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00002145public:
Reid Kleckner11a17192015-10-28 22:29:52 +00002146 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002147 : SwiftABIInfo(CGT),
Reid Kleckner11a17192015-10-28 22:29:52 +00002148 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00002149
Craig Topper4f12f102014-03-12 06:41:41 +00002150 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00002151
John McCall7f416cc2015-09-08 08:05:57 +00002152 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2153 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00002154
2155 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2156 // FIXME: Assumes vectorcall is in use.
2157 return isX86VectorTypeForVectorCall(getContext(), Ty);
2158 }
2159
2160 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2161 uint64_t NumMembers) const override {
2162 // FIXME: Assumes vectorcall is in use.
2163 return isX86VectorCallAggregateSmallEnough(NumMembers);
2164 }
Reid Kleckner11a17192015-10-28 22:29:52 +00002165
Arnold Schwaighofer4fc955e2016-10-12 18:59:24 +00002166 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
2167 ArrayRef<llvm::Type *> scalars,
2168 bool asReturnValue) const override {
2169 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2170 }
2171
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00002172 bool isSwiftErrorInRegister() const override {
2173 return true;
2174 }
2175
Reid Kleckner11a17192015-10-28 22:29:52 +00002176private:
Erich Keane521ed962017-01-05 00:20:51 +00002177 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2178 bool IsVectorCall, bool IsRegCall) const;
2179 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2180 const ABIArgInfo &current) const;
2181 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2182 bool IsVectorCall, bool IsRegCall) const;
Reid Kleckner11a17192015-10-28 22:29:52 +00002183
Erich Keane521ed962017-01-05 00:20:51 +00002184 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00002185};
2186
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002187class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2188public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002189 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002190 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00002191
John McCalla729c622012-02-17 03:33:10 +00002192 const X86_64ABIInfo &getABIInfo() const {
2193 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2194 }
2195
Craig Topper4f12f102014-03-12 06:41:41 +00002196 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00002197 return 7;
2198 }
2199
2200 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002201 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002202 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002203
John McCall943fae92010-05-27 06:19:26 +00002204 // 0-15 are the 16 integer registers.
2205 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002206 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00002207 return false;
2208 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002209
Jay Foad7c57be32011-07-11 09:56:20 +00002210 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002211 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00002212 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00002213 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2214 }
2215
John McCalla729c622012-02-17 03:33:10 +00002216 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00002217 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00002218 // The default CC on x86-64 sets %al to the number of SSA
2219 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002220 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00002221 // that when AVX types are involved: the ABI explicitly states it is
2222 // undefined, and it doesn't work in practice because of how the ABI
2223 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00002224 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002225 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00002226 for (CallArgList::const_iterator
2227 it = args.begin(), ie = args.end(); it != ie; ++it) {
2228 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2229 HasAVXType = true;
2230 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002231 }
2232 }
John McCalla729c622012-02-17 03:33:10 +00002233
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00002234 if (!HasAVXType)
2235 return true;
2236 }
John McCallcbc038a2011-09-21 08:08:30 +00002237
John McCalla729c622012-02-17 03:33:10 +00002238 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00002239 }
2240
Craig Topper4f12f102014-03-12 06:41:41 +00002241 llvm::Constant *
2242 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00002243 unsigned Sig;
2244 if (getABIInfo().has64BitPointers())
2245 Sig = (0xeb << 0) | // jmp rel8
2246 (0x0a << 8) | // .+0x0c
2247 ('F' << 16) |
2248 ('T' << 24);
2249 else
2250 Sig = (0xeb << 0) | // jmp rel8
2251 (0x06 << 8) | // .+0x08
2252 ('F' << 16) |
2253 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00002254 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2255 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00002256
2257 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2258 CodeGen::CodeGenModule &CGM) const override {
2259 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2260 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2261 llvm::Function *Fn = cast<llvm::Function>(GV);
2262 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2263 }
2264 }
2265 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00002266};
2267
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002268class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2269public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002270 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2271 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002272
2273 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00002274 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002275 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00002276 // If the argument contains a space, enclose it in quotes.
2277 if (Lib.find(" ") != StringRef::npos)
2278 Opt += "\"" + Lib.str() + "\"";
2279 else
2280 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00002281 }
2282};
2283
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002284static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002285 // If the argument does not end in .lib, automatically add the suffix.
2286 // If the argument contains a space, enclose it in quotes.
2287 // This matches the behavior of MSVC.
2288 bool Quote = (Lib.find(" ") != StringRef::npos);
2289 std::string ArgStr = Quote ? "\"" : "";
2290 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00002291 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002292 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00002293 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002294 return ArgStr;
2295}
2296
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002297class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2298public:
John McCall1fe2a8c2013-06-18 02:46:29 +00002299 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00002300 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2301 unsigned NumRegisterParameters)
2302 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00002303 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002304
Eric Christopher162c91c2015-06-05 22:03:00 +00002305 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002306 CodeGen::CodeGenModule &CGM) const override;
2307
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002308 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002309 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002310 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002311 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002312 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002313
2314 void getDetectMismatchOption(llvm::StringRef Name,
2315 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002316 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002317 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002318 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002319};
2320
Hans Wennborg77dc2362015-01-20 19:45:50 +00002321static void addStackProbeSizeTargetAttribute(const Decl *D,
2322 llvm::GlobalValue *GV,
2323 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002324 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002325 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2326 llvm::Function *Fn = cast<llvm::Function>(GV);
2327
Eric Christopher7565e0d2015-05-29 23:09:49 +00002328 Fn->addFnAttr("stack-probe-size",
2329 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002330 }
2331 }
2332}
2333
Eric Christopher162c91c2015-06-05 22:03:00 +00002334void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002335 llvm::GlobalValue *GV,
2336 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002337 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002338
2339 addStackProbeSizeTargetAttribute(D, GV, CGM);
2340}
2341
Chris Lattner04dc9572010-08-31 16:44:54 +00002342class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2343public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002344 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2345 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002346 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002347
Eric Christopher162c91c2015-06-05 22:03:00 +00002348 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002349 CodeGen::CodeGenModule &CGM) const override;
2350
Craig Topper4f12f102014-03-12 06:41:41 +00002351 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002352 return 7;
2353 }
2354
2355 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002356 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002357 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002358
Chris Lattner04dc9572010-08-31 16:44:54 +00002359 // 0-15 are the 16 integer registers.
2360 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002361 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002362 return false;
2363 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002364
2365 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002366 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002367 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002368 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002369 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002370
2371 void getDetectMismatchOption(llvm::StringRef Name,
2372 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002373 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002374 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002375 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002376};
2377
Eric Christopher162c91c2015-06-05 22:03:00 +00002378void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002379 llvm::GlobalValue *GV,
2380 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002381 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002382
Alexey Bataevd51e9932016-01-15 04:06:31 +00002383 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2384 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2385 llvm::Function *Fn = cast<llvm::Function>(GV);
2386 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2387 }
2388 }
2389
Hans Wennborg77dc2362015-01-20 19:45:50 +00002390 addStackProbeSizeTargetAttribute(D, GV, CGM);
2391}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002392}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002393
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002394void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2395 Class &Hi) const {
2396 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2397 //
2398 // (a) If one of the classes is Memory, the whole argument is passed in
2399 // memory.
2400 //
2401 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2402 // memory.
2403 //
2404 // (c) If the size of the aggregate exceeds two eightbytes and the first
2405 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2406 // argument is passed in memory. NOTE: This is necessary to keep the
2407 // ABI working for processors that don't support the __m256 type.
2408 //
2409 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2410 //
2411 // Some of these are enforced by the merging logic. Others can arise
2412 // only with unions; for example:
2413 // union { _Complex double; unsigned; }
2414 //
2415 // Note that clauses (b) and (c) were added in 0.98.
2416 //
2417 if (Hi == Memory)
2418 Lo = Memory;
2419 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2420 Lo = Memory;
2421 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2422 Lo = Memory;
2423 if (Hi == SSEUp && Lo != SSE)
2424 Hi = SSE;
2425}
2426
Chris Lattnerd776fb12010-06-28 21:43:59 +00002427X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002428 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2429 // classified recursively so that always two fields are
2430 // considered. The resulting class is calculated according to
2431 // the classes of the fields in the eightbyte:
2432 //
2433 // (a) If both classes are equal, this is the resulting class.
2434 //
2435 // (b) If one of the classes is NO_CLASS, the resulting class is
2436 // the other class.
2437 //
2438 // (c) If one of the classes is MEMORY, the result is the MEMORY
2439 // class.
2440 //
2441 // (d) If one of the classes is INTEGER, the result is the
2442 // INTEGER.
2443 //
2444 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2445 // MEMORY is used as class.
2446 //
2447 // (f) Otherwise class SSE is used.
2448
2449 // Accum should never be memory (we should have returned) or
2450 // ComplexX87 (because this cannot be passed in a structure).
2451 assert((Accum != Memory && Accum != ComplexX87) &&
2452 "Invalid accumulated classification during merge.");
2453 if (Accum == Field || Field == NoClass)
2454 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002455 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002456 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002457 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002458 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002459 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002460 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002461 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2462 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002463 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002464 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002465}
2466
Chris Lattner5c740f12010-06-30 19:14:05 +00002467void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002468 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002469 // FIXME: This code can be simplified by introducing a simple value class for
2470 // Class pairs with appropriate constructor methods for the various
2471 // situations.
2472
2473 // FIXME: Some of the split computations are wrong; unaligned vectors
2474 // shouldn't be passed in registers for example, so there is no chance they
2475 // can straddle an eightbyte. Verify & simplify.
2476
2477 Lo = Hi = NoClass;
2478
2479 Class &Current = OffsetBase < 64 ? Lo : Hi;
2480 Current = Memory;
2481
John McCall9dd450b2009-09-21 23:43:11 +00002482 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002483 BuiltinType::Kind k = BT->getKind();
2484
2485 if (k == BuiltinType::Void) {
2486 Current = NoClass;
2487 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2488 Lo = Integer;
2489 Hi = Integer;
2490 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2491 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002492 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002493 Current = SSE;
2494 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002495 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002496 if (LDF == &llvm::APFloat::IEEEquad()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002497 Lo = SSE;
2498 Hi = SSEUp;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002499 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002500 Lo = X87;
2501 Hi = X87Up;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002502 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002503 Current = SSE;
2504 } else
2505 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002506 }
2507 // FIXME: _Decimal32 and _Decimal64 are SSE.
2508 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002509 return;
2510 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002511
Chris Lattnerd776fb12010-06-28 21:43:59 +00002512 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002513 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002514 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002515 return;
2516 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002517
Chris Lattnerd776fb12010-06-28 21:43:59 +00002518 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002519 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002520 return;
2521 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002522
Chris Lattnerd776fb12010-06-28 21:43:59 +00002523 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002524 if (Ty->isMemberFunctionPointerType()) {
2525 if (Has64BitPointers) {
2526 // If Has64BitPointers, this is an {i64, i64}, so classify both
2527 // Lo and Hi now.
2528 Lo = Hi = Integer;
2529 } else {
2530 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2531 // straddles an eightbyte boundary, Hi should be classified as well.
2532 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2533 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2534 if (EB_FuncPtr != EB_ThisAdj) {
2535 Lo = Hi = Integer;
2536 } else {
2537 Current = Integer;
2538 }
2539 }
2540 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002541 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002542 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002543 return;
2544 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002545
Chris Lattnerd776fb12010-06-28 21:43:59 +00002546 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002547 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002548 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2549 // gcc passes the following as integer:
2550 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2551 // 2 bytes - <2 x char>, <1 x short>
2552 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002553 Current = Integer;
2554
2555 // If this type crosses an eightbyte boundary, it should be
2556 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002557 uint64_t EB_Lo = (OffsetBase) / 64;
2558 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2559 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002560 Hi = Lo;
2561 } else if (Size == 64) {
David Majnemere2ae2282016-03-04 05:26:16 +00002562 QualType ElementType = VT->getElementType();
2563
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002564 // gcc passes <1 x double> in memory. :(
David Majnemere2ae2282016-03-04 05:26:16 +00002565 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002566 return;
2567
David Majnemere2ae2282016-03-04 05:26:16 +00002568 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2569 // pass them as integer. For platforms where clang is the de facto
2570 // platform compiler, we must continue to use integer.
2571 if (!classifyIntegerMMXAsSSE() &&
2572 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2573 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2574 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2575 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002576 Current = Integer;
2577 else
2578 Current = SSE;
2579
2580 // If this type crosses an eightbyte boundary, it should be
2581 // split.
2582 if (OffsetBase && OffsetBase != 64)
2583 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002584 } else if (Size == 128 ||
2585 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002586 // Arguments of 256-bits are split into four eightbyte chunks. The
2587 // least significant one belongs to class SSE and all the others to class
2588 // SSEUP. The original Lo and Hi design considers that types can't be
2589 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2590 // This design isn't correct for 256-bits, but since there're no cases
2591 // where the upper parts would need to be inspected, avoid adding
2592 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002593 //
2594 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2595 // registers if they are "named", i.e. not part of the "..." of a
2596 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002597 //
2598 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2599 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002600 Lo = SSE;
2601 Hi = SSEUp;
2602 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002603 return;
2604 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002605
Chris Lattnerd776fb12010-06-28 21:43:59 +00002606 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002607 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002608
Chris Lattner2b037972010-07-29 02:01:43 +00002609 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002610 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002611 if (Size <= 64)
2612 Current = Integer;
2613 else if (Size <= 128)
2614 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002615 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002616 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002617 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002618 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002619 } else if (ET == getContext().LongDoubleTy) {
2620 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002621 if (LDF == &llvm::APFloat::IEEEquad())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002622 Current = Memory;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002623 else if (LDF == &llvm::APFloat::x87DoubleExtended())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002624 Current = ComplexX87;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002625 else if (LDF == &llvm::APFloat::IEEEdouble())
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002626 Lo = Hi = SSE;
2627 else
2628 llvm_unreachable("unexpected long double representation!");
2629 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002630
2631 // If this complex type crosses an eightbyte boundary then it
2632 // should be split.
2633 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002634 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002635 if (Hi == NoClass && EB_Real != EB_Imag)
2636 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002637
Chris Lattnerd776fb12010-06-28 21:43:59 +00002638 return;
2639 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002640
Chris Lattner2b037972010-07-29 02:01:43 +00002641 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002642 // Arrays are treated like structures.
2643
Chris Lattner2b037972010-07-29 02:01:43 +00002644 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002645
2646 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002647 // than eight eightbytes, ..., it has class MEMORY.
2648 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002649 return;
2650
2651 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2652 // fields, it has class MEMORY.
2653 //
2654 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002655 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002656 return;
2657
2658 // Otherwise implement simplified merge. We could be smarter about
2659 // this, but it isn't worth it and would be harder to verify.
2660 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002661 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002662 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002663
2664 // The only case a 256-bit wide vector could be used is when the array
2665 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2666 // to work for sizes wider than 128, early check and fallback to memory.
David Majnemerb229cb02016-08-15 06:39:18 +00002667 //
2668 if (Size > 128 &&
2669 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002670 return;
2671
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002672 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2673 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002674 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002675 Lo = merge(Lo, FieldLo);
2676 Hi = merge(Hi, FieldHi);
2677 if (Lo == Memory || Hi == Memory)
2678 break;
2679 }
2680
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002681 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002682 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002683 return;
2684 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002685
Chris Lattnerd776fb12010-06-28 21:43:59 +00002686 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002687 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002688
2689 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
David Majnemerb229cb02016-08-15 06:39:18 +00002690 // than eight eightbytes, ..., it has class MEMORY.
2691 if (Size > 512)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002692 return;
2693
Anders Carlsson20759ad2009-09-16 15:53:40 +00002694 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2695 // copy constructor or a non-trivial destructor, it is passed by invisible
2696 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002697 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002698 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002699
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002700 const RecordDecl *RD = RT->getDecl();
2701
2702 // Assume variable sized types are passed in memory.
2703 if (RD->hasFlexibleArrayMember())
2704 return;
2705
Chris Lattner2b037972010-07-29 02:01:43 +00002706 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002707
2708 // Reset Lo class, this will be recomputed.
2709 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002710
2711 // If this is a C++ record, classify the bases first.
2712 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002713 for (const auto &I : CXXRD->bases()) {
2714 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002715 "Unexpected base class!");
2716 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002717 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002718
2719 // Classify this field.
2720 //
2721 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2722 // single eightbyte, each is classified separately. Each eightbyte gets
2723 // initialized to class NO_CLASS.
2724 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002725 uint64_t Offset =
2726 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002727 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002728 Lo = merge(Lo, FieldLo);
2729 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002730 if (Lo == Memory || Hi == Memory) {
2731 postMerge(Size, Lo, Hi);
2732 return;
2733 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002734 }
2735 }
2736
2737 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002738 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002739 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002740 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002741 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2742 bool BitField = i->isBitField();
2743
David Majnemerb439dfe2016-08-15 07:20:40 +00002744 // Ignore padding bit-fields.
2745 if (BitField && i->isUnnamedBitfield())
2746 continue;
2747
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002748 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2749 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002750 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002751 // The only case a 256-bit wide vector could be used is when the struct
2752 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2753 // to work for sizes wider than 128, early check and fallback to memory.
2754 //
David Majnemerb229cb02016-08-15 06:39:18 +00002755 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2756 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002757 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002758 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002759 return;
2760 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002761 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002762 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002763 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002764 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002765 return;
2766 }
2767
2768 // Classify this field.
2769 //
2770 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2771 // exceeds a single eightbyte, each is classified
2772 // separately. Each eightbyte gets initialized to class
2773 // NO_CLASS.
2774 Class FieldLo, FieldHi;
2775
2776 // Bit-fields require special handling, they do not force the
2777 // structure to be passed in memory even if unaligned, and
2778 // therefore they can straddle an eightbyte.
2779 if (BitField) {
David Majnemerb439dfe2016-08-15 07:20:40 +00002780 assert(!i->isUnnamedBitfield());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002781 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002782 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002783
2784 uint64_t EB_Lo = Offset / 64;
2785 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002786
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002787 if (EB_Lo) {
2788 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2789 FieldLo = NoClass;
2790 FieldHi = Integer;
2791 } else {
2792 FieldLo = Integer;
2793 FieldHi = EB_Hi ? Integer : NoClass;
2794 }
2795 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002796 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002797 Lo = merge(Lo, FieldLo);
2798 Hi = merge(Hi, FieldHi);
2799 if (Lo == Memory || Hi == Memory)
2800 break;
2801 }
2802
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002803 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002804 }
2805}
2806
Chris Lattner22a931e2010-06-29 06:01:59 +00002807ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002808 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2809 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002810 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002811 // Treat an enum type as its underlying type.
2812 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2813 Ty = EnumTy->getDecl()->getIntegerType();
2814
2815 return (Ty->isPromotableIntegerType() ?
2816 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2817 }
2818
John McCall7f416cc2015-09-08 08:05:57 +00002819 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002820}
2821
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002822bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2823 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2824 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002825 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002826 if (Size <= 64 || Size > LargestVector)
2827 return true;
2828 }
2829
2830 return false;
2831}
2832
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002833ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2834 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002835 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2836 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002837 //
2838 // This assumption is optimistic, as there could be free registers available
2839 // when we need to pass this argument in memory, and LLVM could try to pass
2840 // the argument in the free register. This does not seem to happen currently,
2841 // but this code would be much safer if we could mark the argument with
2842 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002843 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002844 // Treat an enum type as its underlying type.
2845 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2846 Ty = EnumTy->getDecl()->getIntegerType();
2847
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002848 return (Ty->isPromotableIntegerType() ?
2849 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002850 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002851
Mark Lacey3825e832013-10-06 01:33:34 +00002852 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002853 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002854
Chris Lattner44c2b902011-05-22 23:21:23 +00002855 // Compute the byval alignment. We specify the alignment of the byval in all
2856 // cases so that the mid-level optimizer knows the alignment of the byval.
2857 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002858
2859 // Attempt to avoid passing indirect results using byval when possible. This
2860 // is important for good codegen.
2861 //
2862 // We do this by coercing the value into a scalar type which the backend can
2863 // handle naturally (i.e., without using byval).
2864 //
2865 // For simplicity, we currently only do this when we have exhausted all of the
2866 // free integer registers. Doing this when there are free integer registers
2867 // would require more care, as we would have to ensure that the coerced value
2868 // did not claim the unused register. That would require either reording the
2869 // arguments to the function (so that any subsequent inreg values came first),
2870 // or only doing this optimization when there were no following arguments that
2871 // might be inreg.
2872 //
2873 // We currently expect it to be rare (particularly in well written code) for
2874 // arguments to be passed on the stack when there are still free integer
2875 // registers available (this would typically imply large structs being passed
2876 // by value), so this seems like a fair tradeoff for now.
2877 //
2878 // We can revisit this if the backend grows support for 'onstack' parameter
2879 // attributes. See PR12193.
2880 if (freeIntRegs == 0) {
2881 uint64_t Size = getContext().getTypeSize(Ty);
2882
2883 // If this type fits in an eightbyte, coerce it into the matching integral
2884 // type, which will end up on the stack (with alignment 8).
2885 if (Align == 8 && Size <= 64)
2886 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2887 Size));
2888 }
2889
John McCall7f416cc2015-09-08 08:05:57 +00002890 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002891}
2892
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002893/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2894/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002895llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002896 // Wrapper structs/arrays that only contain vectors are passed just like
2897 // vectors; strip them off if present.
2898 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2899 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002900
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002901 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002902 if (isa<llvm::VectorType>(IRType) ||
2903 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002904 return IRType;
2905
2906 // We couldn't find the preferred IR vector type for 'Ty'.
2907 uint64_t Size = getContext().getTypeSize(Ty);
David Majnemerb229cb02016-08-15 06:39:18 +00002908 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002909
2910 // Return a LLVM IR vector type based on the size of 'Ty'.
2911 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2912 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002913}
2914
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002915/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2916/// is known to either be off the end of the specified type or being in
2917/// alignment padding. The user type specified is known to be at most 128 bits
2918/// in size, and have passed through X86_64ABIInfo::classify with a successful
2919/// classification that put one of the two halves in the INTEGER class.
2920///
2921/// It is conservatively correct to return false.
2922static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2923 unsigned EndBit, ASTContext &Context) {
2924 // If the bytes being queried are off the end of the type, there is no user
2925 // data hiding here. This handles analysis of builtins, vectors and other
2926 // types that don't contain interesting padding.
2927 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2928 if (TySize <= StartBit)
2929 return true;
2930
Chris Lattner98076a22010-07-29 07:43:55 +00002931 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2932 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2933 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2934
2935 // Check each element to see if the element overlaps with the queried range.
2936 for (unsigned i = 0; i != NumElts; ++i) {
2937 // If the element is after the span we care about, then we're done..
2938 unsigned EltOffset = i*EltSize;
2939 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002940
Chris Lattner98076a22010-07-29 07:43:55 +00002941 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2942 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2943 EndBit-EltOffset, Context))
2944 return false;
2945 }
2946 // If it overlaps no elements, then it is safe to process as padding.
2947 return true;
2948 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002949
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002950 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2951 const RecordDecl *RD = RT->getDecl();
2952 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002953
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002954 // If this is a C++ record, check the bases first.
2955 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002956 for (const auto &I : CXXRD->bases()) {
2957 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002958 "Unexpected base class!");
2959 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002960 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002961
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002962 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002963 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002964 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002965
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002966 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002967 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002968 EndBit-BaseOffset, Context))
2969 return false;
2970 }
2971 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002972
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002973 // Verify that no field has data that overlaps the region of interest. Yes
2974 // this could be sped up a lot by being smarter about queried fields,
2975 // however we're only looking at structs up to 16 bytes, so we don't care
2976 // much.
2977 unsigned idx = 0;
2978 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2979 i != e; ++i, ++idx) {
2980 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002981
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002982 // If we found a field after the region we care about, then we're done.
2983 if (FieldOffset >= EndBit) break;
2984
2985 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2986 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2987 Context))
2988 return false;
2989 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002990
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002991 // If nothing in this record overlapped the area of interest, then we're
2992 // clean.
2993 return true;
2994 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002995
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002996 return false;
2997}
2998
Chris Lattnere556a712010-07-29 18:39:32 +00002999/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3000/// float member at the specified offset. For example, {int,{float}} has a
3001/// float at offset 4. It is conservatively correct for this routine to return
3002/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00003003static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003004 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00003005 // Base case if we find a float.
3006 if (IROffset == 0 && IRType->isFloatTy())
3007 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003008
Chris Lattnere556a712010-07-29 18:39:32 +00003009 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003010 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00003011 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3012 unsigned Elt = SL->getElementContainingOffset(IROffset);
3013 IROffset -= SL->getElementOffset(Elt);
3014 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3015 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003016
Chris Lattnere556a712010-07-29 18:39:32 +00003017 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00003018 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3019 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00003020 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3021 IROffset -= IROffset/EltSize*EltSize;
3022 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3023 }
3024
3025 return false;
3026}
3027
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003028
3029/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3030/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003031llvm::Type *X86_64ABIInfo::
3032GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003033 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00003034 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003035 // pass as float if the last 4 bytes is just padding. This happens for
3036 // structs that contain 3 floats.
3037 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3038 SourceOffset*8+64, getContext()))
3039 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003040
Chris Lattnere556a712010-07-29 18:39:32 +00003041 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3042 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3043 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003044 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3045 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00003046 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003047
Chris Lattner7f4b81a2010-07-29 18:13:09 +00003048 return llvm::Type::getDoubleTy(getVMContext());
3049}
3050
3051
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003052/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3053/// an 8-byte GPR. This means that we either have a scalar or we are talking
3054/// about the high or low part of an up-to-16-byte struct. This routine picks
3055/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003056/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3057/// etc).
3058///
3059/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3060/// the source type. IROffset is an offset in bytes into the LLVM IR type that
3061/// the 8-byte value references. PrefType may be null.
3062///
Alp Toker9907f082014-07-09 14:06:35 +00003063/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003064/// an offset into this that we're processing (which is always either 0 or 8).
3065///
Chris Lattnera5f58b02011-07-09 17:41:47 +00003066llvm::Type *X86_64ABIInfo::
3067GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003068 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003069 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3070 // returning an 8-byte unit starting with it. See if we can safely use it.
3071 if (IROffset == 0) {
3072 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00003073 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3074 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003075 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003076
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003077 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3078 // goodness in the source type is just tail padding. This is allowed to
3079 // kick in for struct {double,int} on the int, but not on
3080 // struct{double,int,int} because we wouldn't return the second int. We
3081 // have to do this analysis on the source type because we can't depend on
3082 // unions being lowered a specific way etc.
3083 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00003084 IRType->isIntegerTy(32) ||
3085 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3086 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3087 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003088
Chris Lattnerc8b7b532010-07-29 07:30:00 +00003089 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3090 SourceOffset*8+64, getContext()))
3091 return IRType;
3092 }
3093 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003094
Chris Lattner2192fe52011-07-18 04:24:23 +00003095 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003096 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00003097 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003098 if (IROffset < SL->getSizeInBytes()) {
3099 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3100 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003101
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003102 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3103 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003104 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003105 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003106
Chris Lattner2192fe52011-07-18 04:24:23 +00003107 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003108 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00003109 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00003110 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00003111 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3112 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00003113 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003114
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003115 // Okay, we don't have any better idea of what to pass, so we pass this in an
3116 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00003117 unsigned TySizeInBytes =
3118 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003119
Chris Lattner3f763422010-07-29 17:34:39 +00003120 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003121
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003122 // It is always safe to classify this as an integer type up to i64 that
3123 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00003124 return llvm::IntegerType::get(getVMContext(),
3125 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00003126}
3127
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003128
3129/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3130/// be used as elements of a two register pair to pass or return, return a
3131/// first class aggregate to represent them. For example, if the low part of
3132/// a by-value argument should be passed as i32* and the high part as float,
3133/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003134static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00003135GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00003136 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003137 // In order to correctly satisfy the ABI, we need to the high part to start
3138 // at offset 8. If the high and low parts we inferred are both 4-byte types
3139 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3140 // the second element at offset 8. Check for this:
3141 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3142 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003143 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003144 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003145
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003146 // To handle this, we have to increase the size of the low part so that the
3147 // second element will start at an 8 byte offset. We can't increase the size
3148 // of the second element because it might make us access off the end of the
3149 // struct.
3150 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00003151 // There are usually two sorts of types the ABI generation code can produce
3152 // for the low part of a pair that aren't 8 bytes in size: float or
3153 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3154 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003155 // Promote these to a larger type.
3156 if (Lo->isFloatTy())
3157 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3158 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00003159 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3160 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003161 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3162 }
3163 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003164
Reid Kleckneree7cf842014-12-01 22:02:27 +00003165 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003166
3167
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003168 // Verify that the second element is at an 8-byte offset.
3169 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3170 "Invalid x86-64 argument pair!");
3171 return Result;
3172}
3173
Chris Lattner31faff52010-07-28 23:06:14 +00003174ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00003175classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00003176 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3177 // classification algorithm.
3178 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003179 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00003180
3181 // Check some invariants.
3182 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00003183 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3184
Craig Topper8a13c412014-05-21 05:09:00 +00003185 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003186 switch (Lo) {
3187 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003188 if (Hi == NoClass)
3189 return ABIArgInfo::getIgnore();
3190 // If the low part is just padding, it takes no register, leave ResType
3191 // null.
3192 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3193 "Unknown missing lo part");
3194 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003195
3196 case SSEUp:
3197 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003198 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003199
3200 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3201 // hidden argument.
3202 case Memory:
3203 return getIndirectReturnResult(RetTy);
3204
3205 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3206 // available register of the sequence %rax, %rdx is used.
3207 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003208 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003209
Chris Lattner1f3a0632010-07-29 21:42:50 +00003210 // If we have a sign or zero extended integer, make sure to return Extend
3211 // so that the parameter gets the right LLVM IR attributes.
3212 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3213 // Treat an enum type as its underlying type.
3214 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3215 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003216
Chris Lattner1f3a0632010-07-29 21:42:50 +00003217 if (RetTy->isIntegralOrEnumerationType() &&
3218 RetTy->isPromotableIntegerType())
3219 return ABIArgInfo::getExtend();
3220 }
Chris Lattner31faff52010-07-28 23:06:14 +00003221 break;
3222
3223 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3224 // available SSE register of the sequence %xmm0, %xmm1 is used.
3225 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003226 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003227 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003228
3229 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3230 // returned on the X87 stack in %st0 as 80-bit x87 number.
3231 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00003232 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003233 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003234
3235 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3236 // part of the value is returned in %st0 and the imaginary part in
3237 // %st1.
3238 case ComplexX87:
3239 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00003240 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00003241 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00003242 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00003243 break;
3244 }
3245
Craig Topper8a13c412014-05-21 05:09:00 +00003246 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00003247 switch (Hi) {
3248 // Memory was handled previously and X87 should
3249 // never occur as a hi class.
3250 case Memory:
3251 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00003252 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00003253
3254 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00003255 case NoClass:
3256 break;
Chris Lattner31faff52010-07-28 23:06:14 +00003257
Chris Lattner52b3c132010-09-01 00:20:33 +00003258 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003259 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003260 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3261 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003262 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00003263 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003264 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003265 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3266 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00003267 break;
3268
3269 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003270 // is passed in the next available eightbyte chunk if the last used
3271 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00003272 //
Chris Lattner57540c52011-04-15 05:22:18 +00003273 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00003274 case SSEUp:
3275 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003276 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00003277 break;
3278
3279 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3280 // returned together with the previous X87 value in %st0.
3281 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00003282 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00003283 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00003284 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00003285 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00003286 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003287 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00003288 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3289 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00003290 }
Chris Lattner31faff52010-07-28 23:06:14 +00003291 break;
3292 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003293
Chris Lattner52b3c132010-09-01 00:20:33 +00003294 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003295 // known to pass in the high eightbyte of the result. We do this by forming a
3296 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00003297 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003298 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00003299
Chris Lattner1f3a0632010-07-29 21:42:50 +00003300 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00003301}
3302
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003303ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00003304 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3305 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003306 const
3307{
Reid Klecknerb1be6832014-11-15 01:41:41 +00003308 Ty = useFirstFieldIfTransparentUnion(Ty);
3309
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003310 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00003311 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003312
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003313 // Check some invariants.
3314 // FIXME: Enforce these by construction.
3315 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003316 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3317
3318 neededInt = 0;
3319 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00003320 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003321 switch (Lo) {
3322 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003323 if (Hi == NoClass)
3324 return ABIArgInfo::getIgnore();
3325 // If the low part is just padding, it takes no register, leave ResType
3326 // null.
3327 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3328 "Unknown missing lo part");
3329 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003330
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003331 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3332 // on the stack.
3333 case Memory:
3334
3335 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3336 // COMPLEX_X87, it is passed in memory.
3337 case X87:
3338 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003339 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003340 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003341 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003342
3343 case SSEUp:
3344 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003345 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003346
3347 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3348 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3349 // and %r9 is used.
3350 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003351 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003352
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003353 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003354 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003355
3356 // If we have a sign or zero extended integer, make sure to return Extend
3357 // so that the parameter gets the right LLVM IR attributes.
3358 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3359 // Treat an enum type as its underlying type.
3360 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3361 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003362
Chris Lattner1f3a0632010-07-29 21:42:50 +00003363 if (Ty->isIntegralOrEnumerationType() &&
3364 Ty->isPromotableIntegerType())
3365 return ABIArgInfo::getExtend();
3366 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003367
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003368 break;
3369
3370 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3371 // available SSE register is used, the registers are taken in the
3372 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003373 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003374 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003375 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003376 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003377 break;
3378 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003379 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003380
Craig Topper8a13c412014-05-21 05:09:00 +00003381 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003382 switch (Hi) {
3383 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003384 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003385 // which is passed in memory.
3386 case Memory:
3387 case X87:
3388 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003389 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003390
3391 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003392
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003393 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003394 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003395 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003396 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003397
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003398 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3399 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003400 break;
3401
3402 // X87Up generally doesn't occur here (long double is passed in
3403 // memory), except in situations involving unions.
3404 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003405 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003406 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003407
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003408 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3409 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003410
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003411 ++neededSSE;
3412 break;
3413
3414 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3415 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003416 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003417 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003418 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003419 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003420 break;
3421 }
3422
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003423 // If a high part was specified, merge it together with the low part. It is
3424 // known to pass in the high eightbyte of the result. We do this by forming a
3425 // first class struct aggregate with the high and low part: {low, high}
3426 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003427 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003428
Chris Lattner1f3a0632010-07-29 21:42:50 +00003429 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003430}
3431
Erich Keane757d3172016-11-02 18:29:35 +00003432ABIArgInfo
3433X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3434 unsigned &NeededSSE) const {
3435 auto RT = Ty->getAs<RecordType>();
3436 assert(RT && "classifyRegCallStructType only valid with struct types");
3437
3438 if (RT->getDecl()->hasFlexibleArrayMember())
3439 return getIndirectReturnResult(Ty);
3440
3441 // Sum up bases
3442 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3443 if (CXXRD->isDynamicClass()) {
3444 NeededInt = NeededSSE = 0;
3445 return getIndirectReturnResult(Ty);
3446 }
3447
3448 for (const auto &I : CXXRD->bases())
3449 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3450 .isIndirect()) {
3451 NeededInt = NeededSSE = 0;
3452 return getIndirectReturnResult(Ty);
3453 }
3454 }
3455
3456 // Sum up members
3457 for (const auto *FD : RT->getDecl()->fields()) {
3458 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3459 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3460 .isIndirect()) {
3461 NeededInt = NeededSSE = 0;
3462 return getIndirectReturnResult(Ty);
3463 }
3464 } else {
3465 unsigned LocalNeededInt, LocalNeededSSE;
3466 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3467 LocalNeededSSE, true)
3468 .isIndirect()) {
3469 NeededInt = NeededSSE = 0;
3470 return getIndirectReturnResult(Ty);
3471 }
3472 NeededInt += LocalNeededInt;
3473 NeededSSE += LocalNeededSSE;
3474 }
3475 }
3476
3477 return ABIArgInfo::getDirect();
3478}
3479
3480ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3481 unsigned &NeededInt,
3482 unsigned &NeededSSE) const {
3483
3484 NeededInt = 0;
3485 NeededSSE = 0;
3486
3487 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3488}
3489
Chris Lattner22326a12010-07-29 02:31:05 +00003490void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003491
Erich Keane757d3172016-11-02 18:29:35 +00003492 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003493
3494 // Keep track of the number of assigned registers.
Erich Keane757d3172016-11-02 18:29:35 +00003495 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3496 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3497 unsigned NeededInt, NeededSSE;
3498
3499 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3500 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3501 FI.getReturnInfo() =
3502 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3503 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3504 FreeIntRegs -= NeededInt;
3505 FreeSSERegs -= NeededSSE;
3506 } else {
3507 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3508 }
3509 } else if (!getCXXABI().classifyReturnType(FI))
3510 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003511
3512 // If the return value is indirect, then the hidden argument is consuming one
3513 // integer register.
3514 if (FI.getReturnInfo().isIndirect())
Erich Keane757d3172016-11-02 18:29:35 +00003515 --FreeIntRegs;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003516
Peter Collingbournef7706832014-12-12 23:41:25 +00003517 // The chain argument effectively gives us another free register.
3518 if (FI.isChainCall())
Erich Keane757d3172016-11-02 18:29:35 +00003519 ++FreeIntRegs;
Peter Collingbournef7706832014-12-12 23:41:25 +00003520
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003521 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003522 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3523 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003524 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003525 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003526 it != ie; ++it, ++ArgNo) {
3527 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003528
Erich Keane757d3172016-11-02 18:29:35 +00003529 if (IsRegCall && it->type->isStructureOrClassType())
3530 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3531 else
3532 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3533 NeededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003534
3535 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3536 // eightbyte of an argument, the whole argument is passed on the
3537 // stack. If registers have already been assigned for some
3538 // eightbytes of such an argument, the assignments get reverted.
Erich Keane757d3172016-11-02 18:29:35 +00003539 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3540 FreeIntRegs -= NeededInt;
3541 FreeSSERegs -= NeededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003542 } else {
Erich Keane757d3172016-11-02 18:29:35 +00003543 it->info = getIndirectResult(it->type, FreeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003544 }
3545 }
3546}
3547
John McCall7f416cc2015-09-08 08:05:57 +00003548static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3549 Address VAListAddr, QualType Ty) {
3550 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3551 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003552 llvm::Value *overflow_arg_area =
3553 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3554
3555 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3556 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003557 // It isn't stated explicitly in the standard, but in practice we use
3558 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003559 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3560 if (Align > CharUnits::fromQuantity(8)) {
3561 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3562 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003563 }
3564
3565 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003566 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003567 llvm::Value *Res =
3568 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003569 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003570
3571 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3572 // l->overflow_arg_area + sizeof(type).
3573 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3574 // an 8 byte boundary.
3575
3576 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003577 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003578 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003579 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3580 "overflow_arg_area.next");
3581 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3582
3583 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003584 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003585}
3586
John McCall7f416cc2015-09-08 08:05:57 +00003587Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3588 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003589 // Assume that va_list type is correct; should be pointer to LLVM type:
3590 // struct {
3591 // i32 gp_offset;
3592 // i32 fp_offset;
3593 // i8* overflow_arg_area;
3594 // i8* reg_save_area;
3595 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003596 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003597
John McCall7f416cc2015-09-08 08:05:57 +00003598 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003599 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003600 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003601
3602 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3603 // in the registers. If not go to step 7.
3604 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003605 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003606
3607 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3608 // general purpose registers needed to pass type and num_fp to hold
3609 // the number of floating point registers needed.
3610
3611 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3612 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3613 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3614 //
3615 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3616 // register save space).
3617
Craig Topper8a13c412014-05-21 05:09:00 +00003618 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003619 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3620 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003621 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003622 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003623 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3624 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003625 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003626 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3627 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003628 }
3629
3630 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003631 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003632 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3633 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003634 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3635 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003636 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3637 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003638 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3639 }
3640
3641 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3642 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3643 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3644 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3645
3646 // Emit code to load the value if it was passed in registers.
3647
3648 CGF.EmitBlock(InRegBlock);
3649
3650 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3651 // an offset of l->gp_offset and/or l->fp_offset. This may require
3652 // copying to a temporary location in case the parameter is passed
3653 // in different register classes or requires an alignment greater
3654 // than 8 for general purpose registers and 16 for XMM registers.
3655 //
3656 // FIXME: This really results in shameful code when we end up needing to
3657 // collect arguments from different places; often what should result in a
3658 // simple assembling of a structure from scattered addresses has many more
3659 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003660 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003661 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3662 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3663 "reg_save_area");
3664
3665 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003666 if (neededInt && neededSSE) {
3667 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003668 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003669 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003670 Address Tmp = CGF.CreateMemTemp(Ty);
3671 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003672 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003673 llvm::Type *TyLo = ST->getElementType(0);
3674 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003675 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003676 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003677 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3678 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003679 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3680 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003681 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3682 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003683
John McCall7f416cc2015-09-08 08:05:57 +00003684 // Copy the first element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003685 // FIXME: Our choice of alignment here and below is probably pessimistic.
3686 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3687 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3688 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
John McCall7f416cc2015-09-08 08:05:57 +00003689 CGF.Builder.CreateStore(V,
3690 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3691
3692 // Copy the second element.
Peter Collingbourneb367c562016-11-28 22:30:21 +00003693 V = CGF.Builder.CreateAlignedLoad(
3694 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3695 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
John McCall7f416cc2015-09-08 08:05:57 +00003696 CharUnits Offset = CharUnits::fromQuantity(
3697 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3698 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3699
3700 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003701 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003702 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3703 CharUnits::fromQuantity(8));
3704 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003705
3706 // Copy to a temporary if necessary to ensure the appropriate alignment.
3707 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003708 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003709 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003710 CharUnits TyAlign = SizeAlign.second;
3711
3712 // Copy into a temporary if the type is more aligned than the
3713 // register save area.
3714 if (TyAlign.getQuantity() > 8) {
3715 Address Tmp = CGF.CreateMemTemp(Ty);
3716 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003717 RegAddr = Tmp;
3718 }
John McCall7f416cc2015-09-08 08:05:57 +00003719
Chris Lattner0cf24192010-06-28 20:05:43 +00003720 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003721 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3722 CharUnits::fromQuantity(16));
3723 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003724 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003725 assert(neededSSE == 2 && "Invalid number of needed registers!");
3726 // SSE registers are spaced 16 bytes apart in the register save
3727 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003728 // The ABI isn't explicit about this, but it seems reasonable
3729 // to assume that the slots are 16-byte aligned, since the stack is
3730 // naturally 16-byte aligned and the prologue is expected to store
3731 // all the SSE registers to the RSA.
3732 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3733 CharUnits::fromQuantity(16));
3734 Address RegAddrHi =
3735 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3736 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003737 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003738 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003739 llvm::Value *V;
3740 Address Tmp = CGF.CreateMemTemp(Ty);
3741 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3742 V = CGF.Builder.CreateLoad(
3743 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3744 CGF.Builder.CreateStore(V,
3745 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3746 V = CGF.Builder.CreateLoad(
3747 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3748 CGF.Builder.CreateStore(V,
3749 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3750
3751 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003752 }
3753
3754 // AMD64-ABI 3.5.7p5: Step 5. Set:
3755 // l->gp_offset = l->gp_offset + num_gp * 8
3756 // l->fp_offset = l->fp_offset + num_fp * 16.
3757 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003758 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003759 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3760 gp_offset_p);
3761 }
3762 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003763 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003764 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3765 fp_offset_p);
3766 }
3767 CGF.EmitBranch(ContBlock);
3768
3769 // Emit code to load the value if it was passed in memory.
3770
3771 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003772 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003773
3774 // Return the appropriate result.
3775
3776 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003777 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3778 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003779 return ResAddr;
3780}
3781
Charles Davisc7d5c942015-09-17 20:55:33 +00003782Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3783 QualType Ty) const {
3784 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3785 CGF.getContext().getTypeInfoInChars(Ty),
3786 CharUnits::fromQuantity(8),
3787 /*allowHigherAlign*/ false);
3788}
3789
Erich Keane521ed962017-01-05 00:20:51 +00003790ABIArgInfo
3791WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3792 const ABIArgInfo &current) const {
3793 // Assumes vectorCall calling convention.
3794 const Type *Base = nullptr;
3795 uint64_t NumElts = 0;
3796
3797 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3798 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3799 FreeSSERegs -= NumElts;
3800 return getDirectX86Hva();
3801 }
3802 return current;
3803}
3804
Reid Kleckner80944df2014-10-31 22:00:51 +00003805ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
Erich Keane521ed962017-01-05 00:20:51 +00003806 bool IsReturnType, bool IsVectorCall,
3807 bool IsRegCall) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003808
3809 if (Ty->isVoidType())
3810 return ABIArgInfo::getIgnore();
3811
3812 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3813 Ty = EnumTy->getDecl()->getIntegerType();
3814
Reid Kleckner80944df2014-10-31 22:00:51 +00003815 TypeInfo Info = getContext().getTypeInfo(Ty);
3816 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003817 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003818
Reid Kleckner9005f412014-05-02 00:51:20 +00003819 const RecordType *RT = Ty->getAs<RecordType>();
3820 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003821 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003822 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003823 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003824 }
3825
3826 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003827 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003828
Reid Kleckner9005f412014-05-02 00:51:20 +00003829 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003830
Reid Kleckner80944df2014-10-31 22:00:51 +00003831 const Type *Base = nullptr;
3832 uint64_t NumElts = 0;
Erich Keane521ed962017-01-05 00:20:51 +00003833 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3834 // other targets.
3835 if ((IsVectorCall || IsRegCall) &&
3836 isHomogeneousAggregate(Ty, Base, NumElts)) {
3837 if (IsRegCall) {
3838 if (FreeSSERegs >= NumElts) {
3839 FreeSSERegs -= NumElts;
3840 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3841 return ABIArgInfo::getDirect();
3842 return ABIArgInfo::getExpand();
3843 }
3844 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3845 } else if (IsVectorCall) {
3846 if (FreeSSERegs >= NumElts &&
3847 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3848 FreeSSERegs -= NumElts;
Reid Kleckner80944df2014-10-31 22:00:51 +00003849 return ABIArgInfo::getDirect();
Erich Keane521ed962017-01-05 00:20:51 +00003850 } else if (IsReturnType) {
3851 return ABIArgInfo::getExpand();
3852 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3853 // HVAs are delayed and reclassified in the 2nd step.
3854 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3855 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003856 }
Reid Kleckner80944df2014-10-31 22:00:51 +00003857 }
3858
Reid Klecknerec87fec2014-05-02 01:17:12 +00003859 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003860 // If the member pointer is represented by an LLVM int or ptr, pass it
3861 // directly.
3862 llvm::Type *LLTy = CGT.ConvertType(Ty);
3863 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3864 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003865 }
3866
Michael Kuperstein4f818702015-02-24 09:35:58 +00003867 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003868 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3869 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003870 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003871 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003872
Reid Kleckner9005f412014-05-02 00:51:20 +00003873 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003874 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003875 }
3876
Julien Lerouge10dcff82014-08-27 00:36:55 +00003877 // Bool type is always extended to the ABI, other builtin types are not
3878 // extended.
3879 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3880 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003881 return ABIArgInfo::getExtend();
3882
Reid Kleckner11a17192015-10-28 22:29:52 +00003883 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3884 // passes them indirectly through memory.
3885 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3886 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003887 if (LDF == &llvm::APFloat::x87DoubleExtended())
Reid Kleckner11a17192015-10-28 22:29:52 +00003888 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3889 }
3890
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003891 return ABIArgInfo::getDirect();
3892}
3893
Erich Keane521ed962017-01-05 00:20:51 +00003894void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3895 unsigned FreeSSERegs,
3896 bool IsVectorCall,
3897 bool IsRegCall) const {
3898 unsigned Count = 0;
3899 for (auto &I : FI.arguments()) {
3900 if (Count < VectorcallMaxParamNumAsReg)
3901 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3902 else {
3903 // Since these cannot be passed in registers, pretend no registers
3904 // are left.
3905 unsigned ZeroSSERegsAvail = 0;
3906 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3907 IsVectorCall, IsRegCall);
3908 }
3909 ++Count;
3910 }
3911
3912 Count = 0;
3913 for (auto &I : FI.arguments()) {
3914 if (Count < VectorcallMaxParamNumAsReg)
3915 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
3916 ++Count;
3917 }
3918}
3919
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003920void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003921 bool IsVectorCall =
3922 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Erich Keane757d3172016-11-02 18:29:35 +00003923 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003924
Erich Keane757d3172016-11-02 18:29:35 +00003925 unsigned FreeSSERegs = 0;
3926 if (IsVectorCall) {
3927 // We can use up to 4 SSE return registers with vectorcall.
3928 FreeSSERegs = 4;
3929 } else if (IsRegCall) {
3930 // RegCall gives us 16 SSE registers.
3931 FreeSSERegs = 16;
3932 }
3933
Reid Kleckner80944df2014-10-31 22:00:51 +00003934 if (!getCXXABI().classifyReturnType(FI))
Erich Keane521ed962017-01-05 00:20:51 +00003935 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
3936 IsVectorCall, IsRegCall);
Reid Kleckner80944df2014-10-31 22:00:51 +00003937
Erich Keane757d3172016-11-02 18:29:35 +00003938 if (IsVectorCall) {
3939 // We can use up to 6 SSE register parameters with vectorcall.
3940 FreeSSERegs = 6;
3941 } else if (IsRegCall) {
Erich Keane521ed962017-01-05 00:20:51 +00003942 // RegCall gives us 16 SSE registers, we can reuse the return registers.
Erich Keane757d3172016-11-02 18:29:35 +00003943 FreeSSERegs = 16;
3944 }
3945
Erich Keane521ed962017-01-05 00:20:51 +00003946 if (IsVectorCall) {
3947 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
3948 } else {
3949 for (auto &I : FI.arguments())
3950 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3951 }
3952
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003953}
3954
John McCall7f416cc2015-09-08 08:05:57 +00003955Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3956 QualType Ty) const {
Reid Klecknerb04449d2016-08-25 20:42:26 +00003957
3958 bool IsIndirect = false;
3959
3960 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3961 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3962 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
3963 uint64_t Width = getContext().getTypeSize(Ty);
3964 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
3965 }
3966
3967 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
John McCall7f416cc2015-09-08 08:05:57 +00003968 CGF.getContext().getTypeInfoInChars(Ty),
3969 CharUnits::fromQuantity(8),
3970 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003971}
Chris Lattner0cf24192010-06-28 20:05:43 +00003972
John McCallea8d8bb2010-03-11 00:10:12 +00003973// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003974namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003975/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3976class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003977bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003978public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003979 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3980 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003981
John McCall7f416cc2015-09-08 08:05:57 +00003982 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3983 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003984};
3985
3986class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3987public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003988 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3989 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003990
Craig Topper4f12f102014-03-12 06:41:41 +00003991 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003992 // This is recovered from gcc output.
3993 return 1; // r1 is the dedicated stack pointer
3994 }
3995
3996 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003997 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003998};
3999
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004000}
John McCallea8d8bb2010-03-11 00:10:12 +00004001
James Y Knight29b5f082016-02-24 02:59:33 +00004002// TODO: this implementation is now likely redundant with
4003// DefaultABIInfo::EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00004004Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4005 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00004006 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00004007 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4008 // TODO: Implement this. For now ignore.
4009 (void)CTy;
James Y Knight29b5f082016-02-24 02:59:33 +00004010 return Address::invalid(); // FIXME?
Roman Divacky8a12d842014-11-03 18:32:54 +00004011 }
4012
John McCall7f416cc2015-09-08 08:05:57 +00004013 // struct __va_list_tag {
4014 // unsigned char gpr;
4015 // unsigned char fpr;
4016 // unsigned short reserved;
4017 // void *overflow_arg_area;
4018 // void *reg_save_area;
4019 // };
4020
Roman Divacky8a12d842014-11-03 18:32:54 +00004021 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00004022 bool isInt =
4023 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004024 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00004025
4026 // All aggregates are passed indirectly? That doesn't seem consistent
4027 // with the argument-lowering code.
4028 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00004029
4030 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00004031
4032 // The calling convention either uses 1-2 GPRs or 1 FPR.
4033 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004034 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00004035 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4036 } else {
4037 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004038 }
John McCall7f416cc2015-09-08 08:05:57 +00004039
4040 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4041
4042 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004043 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004044 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4045 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4046 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004047
Eric Christopher7565e0d2015-05-29 23:09:49 +00004048 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00004049 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00004050
4051 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4052 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4053 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4054
4055 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4056
John McCall7f416cc2015-09-08 08:05:57 +00004057 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4058 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00004059
John McCall7f416cc2015-09-08 08:05:57 +00004060 // Case 1: consume registers.
4061 Address RegAddr = Address::invalid();
4062 {
4063 CGF.EmitBlock(UsingRegs);
4064
4065 Address RegSaveAreaPtr =
4066 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4067 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4068 CharUnits::fromQuantity(8));
4069 assert(RegAddr.getElementType() == CGF.Int8Ty);
4070
4071 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004072 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00004073 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4074 CharUnits::fromQuantity(32));
4075 }
4076
4077 // Get the address of the saved value by scaling the number of
4078 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004079 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00004080 llvm::Value *RegOffset =
4081 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4082 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4083 RegAddr.getPointer(), RegOffset),
4084 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4085 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4086
4087 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00004088 NumRegs =
4089 Builder.CreateAdd(NumRegs,
4090 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00004091 Builder.CreateStore(NumRegs, NumRegsAddr);
4092
4093 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00004094 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004095
John McCall7f416cc2015-09-08 08:05:57 +00004096 // Case 2: consume space in the overflow area.
4097 Address MemAddr = Address::invalid();
4098 {
4099 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00004100
Roman Divacky039b9702016-02-20 08:31:24 +00004101 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4102
John McCall7f416cc2015-09-08 08:05:57 +00004103 // Everything in the overflow area is rounded up to a size of at least 4.
4104 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4105
4106 CharUnits Size;
4107 if (!isIndirect) {
4108 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004109 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00004110 } else {
4111 Size = CGF.getPointerSize();
4112 }
4113
4114 Address OverflowAreaAddr =
4115 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00004116 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00004117 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00004118 // Round up address of argument to alignment
4119 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4120 if (Align > OverflowAreaAlign) {
4121 llvm::Value *Ptr = OverflowArea.getPointer();
4122 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4123 Align);
4124 }
4125
John McCall7f416cc2015-09-08 08:05:57 +00004126 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4127
4128 // Increase the overflow area.
4129 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4130 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4131 CGF.EmitBranch(Cont);
4132 }
Roman Divacky8a12d842014-11-03 18:32:54 +00004133
4134 CGF.EmitBlock(Cont);
4135
John McCall7f416cc2015-09-08 08:05:57 +00004136 // Merge the cases with a phi.
4137 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4138 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00004139
John McCall7f416cc2015-09-08 08:05:57 +00004140 // Load the pointer if the argument was passed indirectly.
4141 if (isIndirect) {
4142 Result = Address(Builder.CreateLoad(Result, "aggr"),
4143 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00004144 }
4145
4146 return Result;
4147}
4148
John McCallea8d8bb2010-03-11 00:10:12 +00004149bool
4150PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4151 llvm::Value *Address) const {
4152 // This is calculated from the LLVM and GCC tables and verified
4153 // against gcc output. AFAIK all ABIs use the same encoding.
4154
4155 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00004156
Chris Lattnerece04092012-02-07 00:39:47 +00004157 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00004158 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4159 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4160 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4161
4162 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00004163 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00004164
4165 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00004166 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00004167
4168 // 64-76 are various 4-byte special-purpose registers:
4169 // 64: mq
4170 // 65: lr
4171 // 66: ctr
4172 // 67: ap
4173 // 68-75 cr0-7
4174 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00004175 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00004176
4177 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00004178 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00004179
4180 // 109: vrsave
4181 // 110: vscr
4182 // 111: spe_acc
4183 // 112: spefscr
4184 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00004185 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00004186
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00004187 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00004188}
4189
Roman Divackyd966e722012-05-09 18:22:46 +00004190// PowerPC-64
4191
4192namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004193/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
James Y Knight29b5f082016-02-24 02:59:33 +00004194class PPC64_SVR4_ABIInfo : public ABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004195public:
4196 enum ABIKind {
4197 ELFv1 = 0,
4198 ELFv2
4199 };
4200
4201private:
4202 static const unsigned GPRBits = 64;
4203 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004204 bool HasQPX;
Hal Finkel415c2a32016-10-02 02:10:45 +00004205 bool IsSoftFloatABI;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004206
4207 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4208 // will be passed in a QPX register.
4209 bool IsQPXVectorTy(const Type *Ty) const {
4210 if (!HasQPX)
4211 return false;
4212
4213 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4214 unsigned NumElements = VT->getNumElements();
4215 if (NumElements == 1)
4216 return false;
4217
4218 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4219 if (getContext().getTypeSize(Ty) <= 256)
4220 return true;
4221 } else if (VT->getElementType()->
4222 isSpecificBuiltinType(BuiltinType::Float)) {
4223 if (getContext().getTypeSize(Ty) <= 128)
4224 return true;
4225 }
4226 }
4227
4228 return false;
4229 }
4230
4231 bool IsQPXVectorTy(QualType Ty) const {
4232 return IsQPXVectorTy(Ty.getTypePtr());
4233 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004234
4235public:
Hal Finkel415c2a32016-10-02 02:10:45 +00004236 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4237 bool SoftFloatABI)
4238 : ABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4239 IsSoftFloatABI(SoftFloatABI) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004240
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004241 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00004242 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004243
4244 ABIArgInfo classifyReturnType(QualType RetTy) const;
4245 ABIArgInfo classifyArgumentType(QualType Ty) const;
4246
Reid Klecknere9f6a712014-10-31 17:10:41 +00004247 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4248 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4249 uint64_t Members) const override;
4250
Bill Schmidt84d37792012-10-12 19:26:17 +00004251 // TODO: We can add more logic to computeInfo to improve performance.
4252 // Example: For aggregate arguments that fit in a register, we could
4253 // use getDirectInReg (as is done below for structs containing a single
4254 // floating-point value) to avoid pushing them to memory on function
4255 // entry. This would require changing the logic in PPCISelLowering
4256 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00004257 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004258 if (!getCXXABI().classifyReturnType(FI))
4259 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004260 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004261 // We rely on the default argument classification for the most part.
4262 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00004263 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004264 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00004265 if (T) {
4266 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004267 if (IsQPXVectorTy(T) ||
4268 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004269 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00004270 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004271 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00004272 continue;
4273 }
4274 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00004275 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00004276 }
4277 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00004278
John McCall7f416cc2015-09-08 08:05:57 +00004279 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4280 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004281};
4282
4283class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004284
Bill Schmidt25cb3492012-10-03 19:18:57 +00004285public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00004286 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel415c2a32016-10-02 02:10:45 +00004287 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4288 bool SoftFloatABI)
4289 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4290 SoftFloatABI)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00004291
Craig Topper4f12f102014-03-12 06:41:41 +00004292 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00004293 // This is recovered from gcc output.
4294 return 1; // r1 is the dedicated stack pointer
4295 }
4296
4297 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004298 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00004299};
4300
Roman Divackyd966e722012-05-09 18:22:46 +00004301class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4302public:
4303 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4304
Craig Topper4f12f102014-03-12 06:41:41 +00004305 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00004306 // This is recovered from gcc output.
4307 return 1; // r1 is the dedicated stack pointer
4308 }
4309
4310 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004311 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00004312};
4313
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004314}
Roman Divackyd966e722012-05-09 18:22:46 +00004315
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004316// Return true if the ABI requires Ty to be passed sign- or zero-
4317// extended to 64 bits.
4318bool
4319PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4320 // Treat an enum type as its underlying type.
4321 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4322 Ty = EnumTy->getDecl()->getIntegerType();
4323
4324 // Promotable integer types are required to be promoted by the ABI.
4325 if (Ty->isPromotableIntegerType())
4326 return true;
4327
4328 // In addition to the usual promotable integer types, we also need to
4329 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4330 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4331 switch (BT->getKind()) {
4332 case BuiltinType::Int:
4333 case BuiltinType::UInt:
4334 return true;
4335 default:
4336 break;
4337 }
4338
4339 return false;
4340}
4341
John McCall7f416cc2015-09-08 08:05:57 +00004342/// isAlignedParamType - Determine whether a type requires 16-byte or
4343/// higher alignment in the parameter area. Always returns at least 8.
4344CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00004345 // Complex types are passed just like their elements.
4346 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4347 Ty = CTy->getElementType();
4348
4349 // Only vector types of size 16 bytes need alignment (larger types are
4350 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004351 if (IsQPXVectorTy(Ty)) {
4352 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004353 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004354
John McCall7f416cc2015-09-08 08:05:57 +00004355 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004356 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00004357 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004358 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004359
4360 // For single-element float/vector structs, we consider the whole type
4361 // to have the same alignment requirements as its single element.
4362 const Type *AlignAsType = nullptr;
4363 const Type *EltType = isSingleElementStruct(Ty, getContext());
4364 if (EltType) {
4365 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004366 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00004367 getContext().getTypeSize(EltType) == 128) ||
4368 (BT && BT->isFloatingPoint()))
4369 AlignAsType = EltType;
4370 }
4371
Ulrich Weigandb7122372014-07-21 00:48:09 +00004372 // Likewise for ELFv2 homogeneous aggregates.
4373 const Type *Base = nullptr;
4374 uint64_t Members = 0;
4375 if (!AlignAsType && Kind == ELFv2 &&
4376 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4377 AlignAsType = Base;
4378
Ulrich Weigand581badc2014-07-10 17:20:07 +00004379 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004380 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4381 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004382 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004383
John McCall7f416cc2015-09-08 08:05:57 +00004384 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004385 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00004386 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004387 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004388
4389 // Otherwise, we only need alignment for any aggregate type that
4390 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004391 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4392 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00004393 return CharUnits::fromQuantity(32);
4394 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004395 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00004396
John McCall7f416cc2015-09-08 08:05:57 +00004397 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00004398}
4399
Ulrich Weigandb7122372014-07-21 00:48:09 +00004400/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4401/// aggregate. Base is set to the base element type, and Members is set
4402/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004403bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4404 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004405 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4406 uint64_t NElements = AT->getSize().getZExtValue();
4407 if (NElements == 0)
4408 return false;
4409 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4410 return false;
4411 Members *= NElements;
4412 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4413 const RecordDecl *RD = RT->getDecl();
4414 if (RD->hasFlexibleArrayMember())
4415 return false;
4416
4417 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00004418
4419 // If this is a C++ record, check the bases first.
4420 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4421 for (const auto &I : CXXRD->bases()) {
4422 // Ignore empty records.
4423 if (isEmptyRecord(getContext(), I.getType(), true))
4424 continue;
4425
4426 uint64_t FldMembers;
4427 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4428 return false;
4429
4430 Members += FldMembers;
4431 }
4432 }
4433
Ulrich Weigandb7122372014-07-21 00:48:09 +00004434 for (const auto *FD : RD->fields()) {
4435 // Ignore (non-zero arrays of) empty records.
4436 QualType FT = FD->getType();
4437 while (const ConstantArrayType *AT =
4438 getContext().getAsConstantArrayType(FT)) {
4439 if (AT->getSize().getZExtValue() == 0)
4440 return false;
4441 FT = AT->getElementType();
4442 }
4443 if (isEmptyRecord(getContext(), FT, true))
4444 continue;
4445
4446 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4447 if (getContext().getLangOpts().CPlusPlus &&
4448 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
4449 continue;
4450
4451 uint64_t FldMembers;
4452 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4453 return false;
4454
4455 Members = (RD->isUnion() ?
4456 std::max(Members, FldMembers) : Members + FldMembers);
4457 }
4458
4459 if (!Base)
4460 return false;
4461
4462 // Ensure there is no padding.
4463 if (getContext().getTypeSize(Base) * Members !=
4464 getContext().getTypeSize(Ty))
4465 return false;
4466 } else {
4467 Members = 1;
4468 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4469 Members = 2;
4470 Ty = CT->getElementType();
4471 }
4472
Reid Klecknere9f6a712014-10-31 17:10:41 +00004473 // Most ABIs only support float, double, and some vector type widths.
4474 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00004475 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004476
4477 // The base type must be the same for all members. Types that
4478 // agree in both total size and mode (float vs. vector) are
4479 // treated as being equivalent here.
4480 const Type *TyPtr = Ty.getTypePtr();
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004481 if (!Base) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004482 Base = TyPtr;
Ahmed Bougacha40a34c22016-04-19 17:54:29 +00004483 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4484 // so make sure to widen it explicitly.
4485 if (const VectorType *VT = Base->getAs<VectorType>()) {
4486 QualType EltTy = VT->getElementType();
4487 unsigned NumElements =
4488 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4489 Base = getContext()
4490 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4491 .getTypePtr();
4492 }
4493 }
Ulrich Weigandb7122372014-07-21 00:48:09 +00004494
4495 if (Base->isVectorType() != TyPtr->isVectorType() ||
4496 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4497 return false;
4498 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004499 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4500}
Ulrich Weigandb7122372014-07-21 00:48:09 +00004501
Reid Klecknere9f6a712014-10-31 17:10:41 +00004502bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4503 // Homogeneous aggregates for ELFv2 must have base types of float,
4504 // double, long double, or 128-bit vectors.
4505 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4506 if (BT->getKind() == BuiltinType::Float ||
4507 BT->getKind() == BuiltinType::Double ||
Hal Finkel415c2a32016-10-02 02:10:45 +00004508 BT->getKind() == BuiltinType::LongDouble) {
4509 if (IsSoftFloatABI)
4510 return false;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004511 return true;
Hal Finkel415c2a32016-10-02 02:10:45 +00004512 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00004513 }
4514 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004515 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004516 return true;
4517 }
4518 return false;
4519}
4520
4521bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4522 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004523 // Vector types require one register, floating point types require one
4524 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004525 uint32_t NumRegs =
4526 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004527
4528 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004529 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004530}
4531
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004532ABIArgInfo
4533PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004534 Ty = useFirstFieldIfTransparentUnion(Ty);
4535
Bill Schmidt90b22c92012-11-27 02:46:43 +00004536 if (Ty->isAnyComplexType())
4537 return ABIArgInfo::getDirect();
4538
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004539 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4540 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004541 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004542 uint64_t Size = getContext().getTypeSize(Ty);
4543 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004544 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004545 else if (Size < 128) {
4546 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4547 return ABIArgInfo::getDirect(CoerceTy);
4548 }
4549 }
4550
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004551 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004552 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004553 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004554
John McCall7f416cc2015-09-08 08:05:57 +00004555 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4556 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004557
4558 // ELFv2 homogeneous aggregates are passed as array types.
4559 const Type *Base = nullptr;
4560 uint64_t Members = 0;
4561 if (Kind == ELFv2 &&
4562 isHomogeneousAggregate(Ty, Base, Members)) {
4563 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4564 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4565 return ABIArgInfo::getDirect(CoerceTy);
4566 }
4567
Ulrich Weigand601957f2014-07-21 00:56:36 +00004568 // If an aggregate may end up fully in registers, we do not
4569 // use the ByVal method, but pass the aggregate as array.
4570 // This is usually beneficial since we avoid forcing the
4571 // back-end to store the argument to memory.
4572 uint64_t Bits = getContext().getTypeSize(Ty);
4573 if (Bits > 0 && Bits <= 8 * GPRBits) {
4574 llvm::Type *CoerceTy;
4575
4576 // Types up to 8 bytes are passed as integer type (which will be
4577 // properly aligned in the argument save area doubleword).
4578 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004579 CoerceTy =
4580 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004581 // Larger types are passed as arrays, with the base type selected
4582 // according to the required alignment in the save area.
4583 else {
4584 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004585 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004586 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4587 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4588 }
4589
4590 return ABIArgInfo::getDirect(CoerceTy);
4591 }
4592
Ulrich Weigandb7122372014-07-21 00:48:09 +00004593 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004594 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4595 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004596 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004597 }
4598
4599 return (isPromotableTypeForABI(Ty) ?
4600 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4601}
4602
4603ABIArgInfo
4604PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4605 if (RetTy->isVoidType())
4606 return ABIArgInfo::getIgnore();
4607
Bill Schmidta3d121c2012-12-17 04:20:17 +00004608 if (RetTy->isAnyComplexType())
4609 return ABIArgInfo::getDirect();
4610
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004611 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4612 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004613 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004614 uint64_t Size = getContext().getTypeSize(RetTy);
4615 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004616 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004617 else if (Size < 128) {
4618 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4619 return ABIArgInfo::getDirect(CoerceTy);
4620 }
4621 }
4622
Ulrich Weigandb7122372014-07-21 00:48:09 +00004623 if (isAggregateTypeForABI(RetTy)) {
4624 // ELFv2 homogeneous aggregates are returned as array types.
4625 const Type *Base = nullptr;
4626 uint64_t Members = 0;
4627 if (Kind == ELFv2 &&
4628 isHomogeneousAggregate(RetTy, Base, Members)) {
4629 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4630 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4631 return ABIArgInfo::getDirect(CoerceTy);
4632 }
4633
4634 // ELFv2 small aggregates are returned in up to two registers.
4635 uint64_t Bits = getContext().getTypeSize(RetTy);
4636 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4637 if (Bits == 0)
4638 return ABIArgInfo::getIgnore();
4639
4640 llvm::Type *CoerceTy;
4641 if (Bits > GPRBits) {
4642 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004643 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004644 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004645 CoerceTy =
4646 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004647 return ABIArgInfo::getDirect(CoerceTy);
4648 }
4649
4650 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004651 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004652 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004653
4654 return (isPromotableTypeForABI(RetTy) ?
4655 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4656}
4657
Bill Schmidt25cb3492012-10-03 19:18:57 +00004658// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004659Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4660 QualType Ty) const {
4661 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4662 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004663
John McCall7f416cc2015-09-08 08:05:57 +00004664 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004665
Bill Schmidt924c4782013-01-14 17:45:36 +00004666 // If we have a complex type and the base type is smaller than 8 bytes,
4667 // the ABI calls for the real and imaginary parts to be right-adjusted
4668 // in separate doublewords. However, Clang expects us to produce a
4669 // pointer to a structure with the two parts packed tightly. So generate
4670 // loads of the real and imaginary parts relative to the va_list pointer,
4671 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004672 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4673 CharUnits EltSize = TypeInfo.first / 2;
4674 if (EltSize < SlotSize) {
4675 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4676 SlotSize * 2, SlotSize,
4677 SlotSize, /*AllowHigher*/ true);
4678
4679 Address RealAddr = Addr;
4680 Address ImagAddr = RealAddr;
4681 if (CGF.CGM.getDataLayout().isBigEndian()) {
4682 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4683 SlotSize - EltSize);
4684 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4685 2 * SlotSize - EltSize);
4686 } else {
4687 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4688 }
4689
4690 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4691 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4692 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4693 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4694 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4695
4696 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4697 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4698 /*init*/ true);
4699 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004700 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004701 }
4702
John McCall7f416cc2015-09-08 08:05:57 +00004703 // Otherwise, just use the general rule.
4704 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4705 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004706}
4707
4708static bool
4709PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4710 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004711 // This is calculated from the LLVM and GCC tables and verified
4712 // against gcc output. AFAIK all ABIs use the same encoding.
4713
4714 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4715
4716 llvm::IntegerType *i8 = CGF.Int8Ty;
4717 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4718 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4719 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4720
4721 // 0-31: r0-31, the 8-byte general-purpose registers
4722 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4723
4724 // 32-63: fp0-31, the 8-byte floating-point registers
4725 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4726
Hal Finkel84832a72016-08-30 02:38:34 +00004727 // 64-67 are various 8-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004728 // 64: mq
4729 // 65: lr
4730 // 66: ctr
4731 // 67: ap
Hal Finkel84832a72016-08-30 02:38:34 +00004732 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4733
4734 // 68-76 are various 4-byte special-purpose registers:
Roman Divackyd966e722012-05-09 18:22:46 +00004735 // 68-75 cr0-7
4736 // 76: xer
Hal Finkel84832a72016-08-30 02:38:34 +00004737 AssignToArrayRange(Builder, Address, Four8, 68, 76);
Roman Divackyd966e722012-05-09 18:22:46 +00004738
4739 // 77-108: v0-31, the 16-byte vector registers
4740 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4741
4742 // 109: vrsave
4743 // 110: vscr
4744 // 111: spe_acc
4745 // 112: spefscr
4746 // 113: sfp
Hal Finkel84832a72016-08-30 02:38:34 +00004747 // 114: tfhar
4748 // 115: tfiar
4749 // 116: texasr
4750 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
Roman Divackyd966e722012-05-09 18:22:46 +00004751
4752 return false;
4753}
John McCallea8d8bb2010-03-11 00:10:12 +00004754
Bill Schmidt25cb3492012-10-03 19:18:57 +00004755bool
4756PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4757 CodeGen::CodeGenFunction &CGF,
4758 llvm::Value *Address) const {
4759
4760 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4761}
4762
4763bool
4764PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4765 llvm::Value *Address) const {
4766
4767 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4768}
4769
Chris Lattner0cf24192010-06-28 20:05:43 +00004770//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004771// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004772//===----------------------------------------------------------------------===//
4773
4774namespace {
4775
John McCall12f23522016-04-04 18:33:08 +00004776class AArch64ABIInfo : public SwiftABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004777public:
4778 enum ABIKind {
4779 AAPCS = 0,
4780 DarwinPCS
4781 };
4782
4783private:
4784 ABIKind Kind;
4785
4786public:
John McCall12f23522016-04-04 18:33:08 +00004787 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4788 : SwiftABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004789
4790private:
4791 ABIKind getABIKind() const { return Kind; }
4792 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4793
4794 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004795 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004796 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4797 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4798 uint64_t Members) const override;
4799
Tim Northovera2ee4332014-03-29 15:09:45 +00004800 bool isIllegalVectorType(QualType Ty) const;
4801
David Blaikie1cbb9712014-11-14 19:09:44 +00004802 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004803 if (!getCXXABI().classifyReturnType(FI))
4804 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004805
Tim Northoverb047bfa2014-11-27 21:02:49 +00004806 for (auto &it : FI.arguments())
4807 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004808 }
4809
John McCall7f416cc2015-09-08 08:05:57 +00004810 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4811 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004812
John McCall7f416cc2015-09-08 08:05:57 +00004813 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4814 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004815
John McCall7f416cc2015-09-08 08:05:57 +00004816 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4817 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004818 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4819 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4820 }
John McCall12f23522016-04-04 18:33:08 +00004821
4822 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
4823 ArrayRef<llvm::Type*> scalars,
4824 bool asReturnValue) const override {
4825 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4826 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00004827 bool isSwiftErrorInRegister() const override {
4828 return true;
4829 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004830};
4831
Tim Northover573cbee2014-05-24 12:52:07 +00004832class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004833public:
Tim Northover573cbee2014-05-24 12:52:07 +00004834 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4835 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004836
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004837 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004838 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4839 }
4840
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004841 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4842 return 31;
4843 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004844
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004845 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004846};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004847}
Tim Northovera2ee4332014-03-29 15:09:45 +00004848
Tim Northoverb047bfa2014-11-27 21:02:49 +00004849ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004850 Ty = useFirstFieldIfTransparentUnion(Ty);
4851
Tim Northovera2ee4332014-03-29 15:09:45 +00004852 // Handle illegal vector types here.
4853 if (isIllegalVectorType(Ty)) {
4854 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004855 // Android promotes <2 x i8> to i16, not i32
Ahmed Bougacha8862cae2016-04-19 17:54:24 +00004856 if (isAndroid() && (Size <= 16)) {
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004857 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4858 return ABIArgInfo::getDirect(ResType);
4859 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004860 if (Size <= 32) {
4861 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004862 return ABIArgInfo::getDirect(ResType);
4863 }
4864 if (Size == 64) {
4865 llvm::Type *ResType =
4866 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004867 return ABIArgInfo::getDirect(ResType);
4868 }
4869 if (Size == 128) {
4870 llvm::Type *ResType =
4871 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004872 return ABIArgInfo::getDirect(ResType);
4873 }
John McCall7f416cc2015-09-08 08:05:57 +00004874 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004875 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004876
4877 if (!isAggregateTypeForABI(Ty)) {
4878 // Treat an enum type as its underlying type.
4879 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4880 Ty = EnumTy->getDecl()->getIntegerType();
4881
Tim Northovera2ee4332014-03-29 15:09:45 +00004882 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4883 ? ABIArgInfo::getExtend()
4884 : ABIArgInfo::getDirect());
4885 }
4886
4887 // Structures with either a non-trivial destructor or a non-trivial
4888 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004889 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004890 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4891 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004892 }
4893
4894 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4895 // elsewhere for GNU compatibility.
4896 if (isEmptyRecord(getContext(), Ty, true)) {
4897 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4898 return ABIArgInfo::getIgnore();
4899
Tim Northovera2ee4332014-03-29 15:09:45 +00004900 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4901 }
4902
4903 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004904 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004905 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004906 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004907 return ABIArgInfo::getDirect(
4908 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004909 }
4910
4911 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4912 uint64_t Size = getContext().getTypeSize(Ty);
4913 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004914 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4915 // same size and alignment.
4916 if (getTarget().isRenderScriptTarget()) {
4917 return coerceToIntArray(Ty, getContext(), getVMContext());
4918 }
Tim Northoverc801b4a2014-04-15 14:55:11 +00004919 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004920 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004921
Tim Northovera2ee4332014-03-29 15:09:45 +00004922 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4923 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004924 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004925 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4926 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4927 }
4928 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4929 }
4930
John McCall7f416cc2015-09-08 08:05:57 +00004931 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004932}
4933
Tim Northover573cbee2014-05-24 12:52:07 +00004934ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004935 if (RetTy->isVoidType())
4936 return ABIArgInfo::getIgnore();
4937
4938 // Large vector types should be returned via memory.
4939 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004940 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004941
4942 if (!isAggregateTypeForABI(RetTy)) {
4943 // Treat an enum type as its underlying type.
4944 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4945 RetTy = EnumTy->getDecl()->getIntegerType();
4946
Tim Northover4dab6982014-04-18 13:46:08 +00004947 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4948 ? ABIArgInfo::getExtend()
4949 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004950 }
4951
Tim Northovera2ee4332014-03-29 15:09:45 +00004952 if (isEmptyRecord(getContext(), RetTy, true))
4953 return ABIArgInfo::getIgnore();
4954
Craig Topper8a13c412014-05-21 05:09:00 +00004955 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004956 uint64_t Members = 0;
4957 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004958 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4959 return ABIArgInfo::getDirect();
4960
4961 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4962 uint64_t Size = getContext().getTypeSize(RetTy);
4963 if (Size <= 128) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00004964 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
4965 // same size and alignment.
4966 if (getTarget().isRenderScriptTarget()) {
4967 return coerceToIntArray(RetTy, getContext(), getVMContext());
4968 }
Pete Cooper635b5092015-04-17 22:16:24 +00004969 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004970 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004971
4972 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4973 // For aggregates with 16-byte alignment, we use i128.
4974 if (Alignment < 128 && Size == 128) {
4975 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4976 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4977 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004978 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4979 }
4980
John McCall7f416cc2015-09-08 08:05:57 +00004981 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004982}
4983
Tim Northover573cbee2014-05-24 12:52:07 +00004984/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4985bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004986 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4987 // Check whether VT is legal.
4988 unsigned NumElements = VT->getNumElements();
4989 uint64_t Size = getContext().getTypeSize(VT);
Tim Northover34fd4fb2016-05-03 19:24:47 +00004990 // NumElements should be power of 2.
Tim Northover360d2b32016-05-03 19:22:41 +00004991 if (!llvm::isPowerOf2_32(NumElements))
Tim Northovera2ee4332014-03-29 15:09:45 +00004992 return true;
4993 return Size != 64 && (Size != 128 || NumElements == 1);
4994 }
4995 return false;
4996}
4997
Reid Klecknere9f6a712014-10-31 17:10:41 +00004998bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4999 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5000 // point type or a short-vector type. This is the same as the 32-bit ABI,
5001 // but with the difference that any floating-point type is allowed,
5002 // including __fp16.
5003 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5004 if (BT->isFloatingPoint())
5005 return true;
5006 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5007 unsigned VecSize = getContext().getTypeSize(VT);
5008 if (VecSize == 64 || VecSize == 128)
5009 return true;
5010 }
5011 return false;
5012}
5013
5014bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5015 uint64_t Members) const {
5016 return Members <= 4;
5017}
5018
John McCall7f416cc2015-09-08 08:05:57 +00005019Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00005020 QualType Ty,
5021 CodeGenFunction &CGF) const {
5022 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00005023 bool IsIndirect = AI.isIndirect();
5024
Tim Northoverb047bfa2014-11-27 21:02:49 +00005025 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5026 if (IsIndirect)
5027 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5028 else if (AI.getCoerceToType())
5029 BaseTy = AI.getCoerceToType();
5030
5031 unsigned NumRegs = 1;
5032 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5033 BaseTy = ArrTy->getElementType();
5034 NumRegs = ArrTy->getNumElements();
5035 }
5036 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5037
Tim Northovera2ee4332014-03-29 15:09:45 +00005038 // The AArch64 va_list type and handling is specified in the Procedure Call
5039 // Standard, section B.4:
5040 //
5041 // struct {
5042 // void *__stack;
5043 // void *__gr_top;
5044 // void *__vr_top;
5045 // int __gr_offs;
5046 // int __vr_offs;
5047 // };
5048
5049 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5050 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5051 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5052 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00005053
John McCall7f416cc2015-09-08 08:05:57 +00005054 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5055 CharUnits TyAlign = TyInfo.second;
5056
5057 Address reg_offs_p = Address::invalid();
5058 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005059 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00005060 CharUnits reg_top_offset;
5061 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00005062 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005063 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00005064 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005065 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5066 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005067 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5068 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00005069 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00005070 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005071 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00005072 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00005073 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00005074 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5075 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005076 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5077 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00005078 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00005079 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00005080 }
5081
5082 //=======================================
5083 // Find out where argument was passed
5084 //=======================================
5085
5086 // If reg_offs >= 0 we're already using the stack for this type of
5087 // argument. We don't want to keep updating reg_offs (in case it overflows,
5088 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5089 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00005090 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005091 UsingStack = CGF.Builder.CreateICmpSGE(
5092 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5093
5094 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5095
5096 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00005097 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00005098 CGF.EmitBlock(MaybeRegBlock);
5099
5100 // Integer arguments may need to correct register alignment (for example a
5101 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5102 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00005103 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5104 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005105
5106 reg_offs = CGF.Builder.CreateAdd(
5107 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5108 "align_regoffs");
5109 reg_offs = CGF.Builder.CreateAnd(
5110 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5111 "aligned_regoffs");
5112 }
5113
5114 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00005115 // The fact that this is done unconditionally reflects the fact that
5116 // allocating an argument to the stack also uses up all the remaining
5117 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00005118 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005119 NewOffset = CGF.Builder.CreateAdd(
5120 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5121 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5122
5123 // Now we're in a position to decide whether this argument really was in
5124 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00005125 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005126 InRegs = CGF.Builder.CreateICmpSLE(
5127 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5128
5129 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5130
5131 //=======================================
5132 // Argument was in registers
5133 //=======================================
5134
5135 // Now we emit the code for if the argument was originally passed in
5136 // registers. First start the appropriate block:
5137 CGF.EmitBlock(InRegBlock);
5138
John McCall7f416cc2015-09-08 08:05:57 +00005139 llvm::Value *reg_top = nullptr;
5140 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5141 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00005142 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00005143 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5144 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5145 Address RegAddr = Address::invalid();
5146 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005147
5148 if (IsIndirect) {
5149 // If it's been passed indirectly (actually a struct), whatever we find from
5150 // stored registers or on the stack will actually be a struct **.
5151 MemTy = llvm::PointerType::getUnqual(MemTy);
5152 }
5153
Craig Topper8a13c412014-05-21 05:09:00 +00005154 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005155 uint64_t NumMembers = 0;
5156 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00005157 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00005158 // Homogeneous aggregates passed in registers will have their elements split
5159 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5160 // qN+1, ...). We reload and store into a temporary local variable
5161 // contiguously.
5162 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00005163 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00005164 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5165 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00005166 Address Tmp = CGF.CreateTempAlloca(HFATy,
5167 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00005168
John McCall7f416cc2015-09-08 08:05:57 +00005169 // On big-endian platforms, the value will be right-aligned in its slot.
5170 int Offset = 0;
5171 if (CGF.CGM.getDataLayout().isBigEndian() &&
5172 BaseTyInfo.first.getQuantity() < 16)
5173 Offset = 16 - BaseTyInfo.first.getQuantity();
5174
Tim Northovera2ee4332014-03-29 15:09:45 +00005175 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00005176 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5177 Address LoadAddr =
5178 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5179 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5180
5181 Address StoreAddr =
5182 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00005183
5184 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5185 CGF.Builder.CreateStore(Elem, StoreAddr);
5186 }
5187
John McCall7f416cc2015-09-08 08:05:57 +00005188 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005189 } else {
John McCall7f416cc2015-09-08 08:05:57 +00005190 // Otherwise the object is contiguous in memory.
5191
5192 // It might be right-aligned in its slot.
5193 CharUnits SlotSize = BaseAddr.getAlignment();
5194 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00005195 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00005196 TyInfo.first < SlotSize) {
5197 CharUnits Offset = SlotSize - TyInfo.first;
5198 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005199 }
5200
John McCall7f416cc2015-09-08 08:05:57 +00005201 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005202 }
5203
5204 CGF.EmitBranch(ContBlock);
5205
5206 //=======================================
5207 // Argument was on the stack
5208 //=======================================
5209 CGF.EmitBlock(OnStackBlock);
5210
John McCall7f416cc2015-09-08 08:05:57 +00005211 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5212 CharUnits::Zero(), "stack_p");
5213 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005214
John McCall7f416cc2015-09-08 08:05:57 +00005215 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00005216 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00005217 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5218 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00005219
John McCall7f416cc2015-09-08 08:05:57 +00005220 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00005221
John McCall7f416cc2015-09-08 08:05:57 +00005222 OnStackPtr = CGF.Builder.CreateAdd(
5223 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00005224 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00005225 OnStackPtr = CGF.Builder.CreateAnd(
5226 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00005227 "align_stack");
5228
John McCall7f416cc2015-09-08 08:05:57 +00005229 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005230 }
John McCall7f416cc2015-09-08 08:05:57 +00005231 Address OnStackAddr(OnStackPtr,
5232 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00005233
John McCall7f416cc2015-09-08 08:05:57 +00005234 // All stack slots are multiples of 8 bytes.
5235 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5236 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005237 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005238 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00005239 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00005240 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005241
John McCall7f416cc2015-09-08 08:05:57 +00005242 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00005243 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00005244 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00005245
5246 // Write the new value of __stack for the next call to va_arg
5247 CGF.Builder.CreateStore(NewStack, stack_p);
5248
5249 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00005250 TyInfo.first < StackSlotSize) {
5251 CharUnits Offset = StackSlotSize - TyInfo.first;
5252 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00005253 }
5254
John McCall7f416cc2015-09-08 08:05:57 +00005255 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00005256
5257 CGF.EmitBranch(ContBlock);
5258
5259 //=======================================
5260 // Tidy up
5261 //=======================================
5262 CGF.EmitBlock(ContBlock);
5263
John McCall7f416cc2015-09-08 08:05:57 +00005264 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5265 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00005266
5267 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005268 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5269 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00005270
5271 return ResAddr;
5272}
5273
John McCall7f416cc2015-09-08 08:05:57 +00005274Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5275 CodeGenFunction &CGF) const {
5276 // The backend's lowering doesn't support va_arg for aggregates or
5277 // illegal vector types. Lower VAArg here for these cases and use
5278 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00005279 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
James Y Knight29b5f082016-02-24 02:59:33 +00005280 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00005281
John McCall7f416cc2015-09-08 08:05:57 +00005282 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00005283
John McCall7f416cc2015-09-08 08:05:57 +00005284 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00005285 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005286 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5287 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5288 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00005289 }
5290
John McCall7f416cc2015-09-08 08:05:57 +00005291 // The size of the actual thing passed, which might end up just
5292 // being a pointer for indirect types.
5293 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5294
5295 // Arguments bigger than 16 bytes which aren't homogeneous
5296 // aggregates should be passed indirectly.
5297 bool IsIndirect = false;
5298 if (TyInfo.first.getQuantity() > 16) {
5299 const Type *Base = nullptr;
5300 uint64_t Members = 0;
5301 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00005302 }
5303
John McCall7f416cc2015-09-08 08:05:57 +00005304 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5305 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00005306}
5307
5308//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005309// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005310//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00005311
5312namespace {
5313
John McCall12f23522016-04-04 18:33:08 +00005314class ARMABIInfo : public SwiftABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005315public:
5316 enum ABIKind {
5317 APCS = 0,
5318 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00005319 AAPCS_VFP = 2,
5320 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00005321 };
5322
5323private:
5324 ABIKind Kind;
5325
5326public:
John McCall12f23522016-04-04 18:33:08 +00005327 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5328 : SwiftABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005329 setCCs();
John McCall882987f2013-02-28 19:01:20 +00005330 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00005331
John McCall3480ef22011-08-30 01:42:09 +00005332 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005333 switch (getTarget().getTriple().getEnvironment()) {
5334 case llvm::Triple::Android:
5335 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005336 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005337 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00005338 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005339 case llvm::Triple::MuslEABI:
5340 case llvm::Triple::MuslEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00005341 return true;
5342 default:
5343 return false;
5344 }
John McCall3480ef22011-08-30 01:42:09 +00005345 }
5346
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005347 bool isEABIHF() const {
5348 switch (getTarget().getTriple().getEnvironment()) {
5349 case llvm::Triple::EABIHF:
5350 case llvm::Triple::GNUEABIHF:
Rafael Espindola0fa66802016-06-24 21:35:06 +00005351 case llvm::Triple::MuslEABIHF:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00005352 return true;
5353 default:
5354 return false;
5355 }
5356 }
5357
Daniel Dunbar020daa92009-09-12 01:00:39 +00005358 ABIKind getABIKind() const { return Kind; }
5359
Tim Northovera484bc02013-10-01 14:34:25 +00005360private:
Amara Emerson9dc78782014-01-28 10:56:36 +00005361 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00005362 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00005363 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005364
Reid Klecknere9f6a712014-10-31 17:10:41 +00005365 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5366 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5367 uint64_t Members) const override;
5368
Craig Topper4f12f102014-03-12 06:41:41 +00005369 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005370
John McCall7f416cc2015-09-08 08:05:57 +00005371 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5372 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00005373
5374 llvm::CallingConv::ID getLLVMDefaultCC() const;
5375 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005376 void setCCs();
John McCall12f23522016-04-04 18:33:08 +00005377
5378 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
5379 ArrayRef<llvm::Type*> scalars,
5380 bool asReturnValue) const override {
5381 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5382 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00005383 bool isSwiftErrorInRegister() const override {
5384 return true;
5385 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005386};
5387
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005388class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5389public:
Chris Lattner2b037972010-07-29 02:01:43 +00005390 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5391 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00005392
John McCall3480ef22011-08-30 01:42:09 +00005393 const ARMABIInfo &getABIInfo() const {
5394 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5395 }
5396
Craig Topper4f12f102014-03-12 06:41:41 +00005397 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00005398 return 13;
5399 }
Roman Divackyc1617352011-05-18 19:36:54 +00005400
Craig Topper4f12f102014-03-12 06:41:41 +00005401 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00005402 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
5403 }
5404
Roman Divackyc1617352011-05-18 19:36:54 +00005405 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005406 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00005407 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00005408
5409 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00005410 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00005411 return false;
5412 }
John McCall3480ef22011-08-30 01:42:09 +00005413
Craig Topper4f12f102014-03-12 06:41:41 +00005414 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00005415 if (getABIInfo().isEABI()) return 88;
5416 return TargetCodeGenInfo::getSizeOfUnwindException();
5417 }
Tim Northovera484bc02013-10-01 14:34:25 +00005418
Eric Christopher162c91c2015-06-05 22:03:00 +00005419 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005420 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005421 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00005422 if (!FD)
5423 return;
5424
5425 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5426 if (!Attr)
5427 return;
5428
5429 const char *Kind;
5430 switch (Attr->getInterrupt()) {
5431 case ARMInterruptAttr::Generic: Kind = ""; break;
5432 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5433 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5434 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5435 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5436 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5437 }
5438
5439 llvm::Function *Fn = cast<llvm::Function>(GV);
5440
5441 Fn->addFnAttr("interrupt", Kind);
5442
Tim Northover5627d392015-10-30 16:30:45 +00005443 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5444 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00005445 return;
5446
5447 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5448 // however this is not necessarily true on taking any interrupt. Instruct
5449 // the backend to perform a realignment as part of the function prologue.
5450 llvm::AttrBuilder B;
5451 B.addStackAlignmentAttr(8);
5452 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
5453 llvm::AttributeSet::get(CGM.getLLVMContext(),
5454 llvm::AttributeSet::FunctionIndex,
5455 B));
5456 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005457};
5458
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005459class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005460public:
5461 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5462 : ARMTargetCodeGenInfo(CGT, K) {}
5463
Eric Christopher162c91c2015-06-05 22:03:00 +00005464 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005465 CodeGen::CodeGenModule &CGM) const override;
Saleem Abdulrasool6e9e88b2016-06-23 13:45:33 +00005466
5467 void getDependentLibraryOption(llvm::StringRef Lib,
5468 llvm::SmallString<24> &Opt) const override {
5469 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5470 }
5471
5472 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5473 llvm::SmallString<32> &Opt) const override {
5474 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5475 }
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005476};
5477
Eric Christopher162c91c2015-06-05 22:03:00 +00005478void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005479 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00005480 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00005481 addStackProbeSizeTargetAttribute(D, GV, CGM);
5482}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005483}
Daniel Dunbard59655c2009-09-12 00:59:49 +00005484
Chris Lattner22326a12010-07-29 02:31:05 +00005485void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00005486 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00005487 FI.getReturnInfo() =
5488 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00005489
Tim Northoverbc784d12015-02-24 17:22:40 +00005490 for (auto &I : FI.arguments())
5491 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00005492
Anton Korobeynikov231e8752011-04-14 20:06:49 +00005493 // Always honor user-specified calling convention.
5494 if (FI.getCallingConvention() != llvm::CallingConv::C)
5495 return;
5496
John McCall882987f2013-02-28 19:01:20 +00005497 llvm::CallingConv::ID cc = getRuntimeCC();
5498 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00005499 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00005500}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00005501
John McCall882987f2013-02-28 19:01:20 +00005502/// Return the default calling convention that LLVM will use.
5503llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5504 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00005505 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00005506 return llvm::CallingConv::ARM_AAPCS_VFP;
5507 else if (isEABI())
5508 return llvm::CallingConv::ARM_AAPCS;
5509 else
5510 return llvm::CallingConv::ARM_APCS;
5511}
5512
5513/// Return the calling convention that our ABI would like us to use
5514/// as the C calling convention.
5515llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00005516 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00005517 case APCS: return llvm::CallingConv::ARM_APCS;
5518 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5519 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00005520 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00005521 }
John McCall882987f2013-02-28 19:01:20 +00005522 llvm_unreachable("bad ABI kind");
5523}
5524
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005525void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00005526 assert(getRuntimeCC() == llvm::CallingConv::C);
5527
5528 // Don't muddy up the IR with a ton of explicit annotations if
5529 // they'd just match what LLVM will infer from the triple.
5530 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5531 if (abiCC != getLLVMDefaultCC())
5532 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00005533
Tim Northover5627d392015-10-30 16:30:45 +00005534 // AAPCS apparently requires runtime support functions to be soft-float, but
5535 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
5536 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
5537 switch (getABIKind()) {
5538 case APCS:
5539 case AAPCS16_VFP:
5540 if (abiCC != getLLVMDefaultCC())
5541 BuiltinCC = abiCC;
5542 break;
5543 case AAPCS:
5544 case AAPCS_VFP:
5545 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
5546 break;
5547 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005548}
5549
Tim Northoverbc784d12015-02-24 17:22:40 +00005550ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5551 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00005552 // 6.1.2.1 The following argument types are VFP CPRCs:
5553 // A single-precision floating-point type (including promoted
5554 // half-precision types); A double-precision floating-point type;
5555 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5556 // with a Base Type of a single- or double-precision floating-point type,
5557 // 64-bit containerized vectors or 128-bit containerized vectors with one
5558 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00005559 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005560
Reid Klecknerb1be6832014-11-15 01:41:41 +00005561 Ty = useFirstFieldIfTransparentUnion(Ty);
5562
Manman Renfef9e312012-10-16 19:18:39 +00005563 // Handle illegal vector types here.
5564 if (isIllegalVectorType(Ty)) {
5565 uint64_t Size = getContext().getTypeSize(Ty);
5566 if (Size <= 32) {
5567 llvm::Type *ResType =
5568 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005569 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005570 }
5571 if (Size == 64) {
5572 llvm::Type *ResType = llvm::VectorType::get(
5573 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005574 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005575 }
5576 if (Size == 128) {
5577 llvm::Type *ResType = llvm::VectorType::get(
5578 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005579 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005580 }
John McCall7f416cc2015-09-08 08:05:57 +00005581 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005582 }
5583
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005584 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5585 // unspecified. This is not done for OpenCL as it handles the half type
5586 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005587 if (Ty->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005588 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5589 llvm::Type::getFloatTy(getVMContext()) :
5590 llvm::Type::getInt32Ty(getVMContext());
5591 return ABIArgInfo::getDirect(ResType);
5592 }
5593
John McCalla1dee5302010-08-22 10:59:02 +00005594 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005595 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005596 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005597 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005598 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005599
Tim Northover5a1558e2014-11-07 22:30:50 +00005600 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5601 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005602 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005603
Oliver Stannard405bded2014-02-11 09:25:50 +00005604 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005605 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005606 }
Tim Northover1060eae2013-06-21 22:49:34 +00005607
Daniel Dunbar09d33622009-09-14 21:54:03 +00005608 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005609 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005610 return ABIArgInfo::getIgnore();
5611
Tim Northover5a1558e2014-11-07 22:30:50 +00005612 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005613 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5614 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005615 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005616 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005617 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005618 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005619 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005620 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005621 }
Tim Northover5627d392015-10-30 16:30:45 +00005622 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5623 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5624 // this convention even for a variadic function: the backend will use GPRs
5625 // if needed.
5626 const Type *Base = nullptr;
5627 uint64_t Members = 0;
5628 if (isHomogeneousAggregate(Ty, Base, Members)) {
5629 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5630 llvm::Type *Ty =
5631 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5632 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5633 }
5634 }
5635
5636 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5637 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5638 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5639 // bigger than 128-bits, they get placed in space allocated by the caller,
5640 // and a pointer is passed.
5641 return ABIArgInfo::getIndirect(
5642 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005643 }
5644
Manman Ren6c30e132012-08-13 21:23:55 +00005645 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005646 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5647 // most 8-byte. We realign the indirect argument if type alignment is bigger
5648 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005649 uint64_t ABIAlign = 4;
5650 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5651 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005652 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005653 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005654
Manman Ren8cd99812012-11-06 04:58:01 +00005655 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005656 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005657 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5658 /*ByVal=*/true,
5659 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005660 }
5661
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005662 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5663 // same size and alignment.
5664 if (getTarget().isRenderScriptTarget()) {
5665 return coerceToIntArray(Ty, getContext(), getVMContext());
5666 }
5667
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005668 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005669 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005670 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005671 // FIXME: Try to match the types of the arguments more accurately where
5672 // we can.
5673 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005674 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5675 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005676 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005677 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5678 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005679 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005680
Tim Northover5a1558e2014-11-07 22:30:50 +00005681 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005682}
5683
Chris Lattner458b2aa2010-07-29 02:16:43 +00005684static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005685 llvm::LLVMContext &VMContext) {
5686 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5687 // is called integer-like if its size is less than or equal to one word, and
5688 // the offset of each of its addressable sub-fields is zero.
5689
5690 uint64_t Size = Context.getTypeSize(Ty);
5691
5692 // Check that the type fits in a word.
5693 if (Size > 32)
5694 return false;
5695
5696 // FIXME: Handle vector types!
5697 if (Ty->isVectorType())
5698 return false;
5699
Daniel Dunbard53bac72009-09-14 02:20:34 +00005700 // Float types are never treated as "integer like".
5701 if (Ty->isRealFloatingType())
5702 return false;
5703
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005704 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005705 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005706 return true;
5707
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005708 // Small complex integer types are "integer like".
5709 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5710 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005711
5712 // Single element and zero sized arrays should be allowed, by the definition
5713 // above, but they are not.
5714
5715 // Otherwise, it must be a record type.
5716 const RecordType *RT = Ty->getAs<RecordType>();
5717 if (!RT) return false;
5718
5719 // Ignore records with flexible arrays.
5720 const RecordDecl *RD = RT->getDecl();
5721 if (RD->hasFlexibleArrayMember())
5722 return false;
5723
5724 // Check that all sub-fields are at offset 0, and are themselves "integer
5725 // like".
5726 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5727
5728 bool HadField = false;
5729 unsigned idx = 0;
5730 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5731 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005732 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005733
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005734 // Bit-fields are not addressable, we only need to verify they are "integer
5735 // like". We still have to disallow a subsequent non-bitfield, for example:
5736 // struct { int : 0; int x }
5737 // is non-integer like according to gcc.
5738 if (FD->isBitField()) {
5739 if (!RD->isUnion())
5740 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005741
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005742 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5743 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005744
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005745 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005746 }
5747
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005748 // Check if this field is at offset 0.
5749 if (Layout.getFieldOffset(idx) != 0)
5750 return false;
5751
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005752 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5753 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005754
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005755 // Only allow at most one field in a structure. This doesn't match the
5756 // wording above, but follows gcc in situations with a field following an
5757 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005758 if (!RD->isUnion()) {
5759 if (HadField)
5760 return false;
5761
5762 HadField = true;
5763 }
5764 }
5765
5766 return true;
5767}
5768
Oliver Stannard405bded2014-02-11 09:25:50 +00005769ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5770 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005771 bool IsEffectivelyAAPCS_VFP =
5772 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005773
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005774 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005775 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005776
Daniel Dunbar19964db2010-09-23 01:54:32 +00005777 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005778 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005779 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005780 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005781
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005782 // __fp16 gets returned as if it were an int or float, but with the top 16
5783 // bits unspecified. This is not done for OpenCL as it handles the half type
5784 // natively, and does not need to interwork with AAPCS code.
Pirama Arumuga Nainar8e2e9d62016-03-18 16:58:36 +00005785 if (RetTy->isHalfType() && !getContext().getLangOpts().NativeHalfArgsAndReturns) {
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005786 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5787 llvm::Type::getFloatTy(getVMContext()) :
5788 llvm::Type::getInt32Ty(getVMContext());
5789 return ABIArgInfo::getDirect(ResType);
5790 }
5791
John McCalla1dee5302010-08-22 10:59:02 +00005792 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005793 // Treat an enum type as its underlying type.
5794 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5795 RetTy = EnumTy->getDecl()->getIntegerType();
5796
Tim Northover5a1558e2014-11-07 22:30:50 +00005797 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5798 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005799 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005800
5801 // Are we following APCS?
5802 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005803 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005804 return ABIArgInfo::getIgnore();
5805
Daniel Dunbareedf1512010-02-01 23:31:19 +00005806 // Complex types are all returned as packed integers.
5807 //
5808 // FIXME: Consider using 2 x vector types if the back end handles them
5809 // correctly.
5810 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005811 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5812 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005813
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005814 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005815 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005816 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005817 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005818 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005819 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005820 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005821 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5822 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005823 }
5824
5825 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005826 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005827 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005828
5829 // Otherwise this is an AAPCS variant.
5830
Chris Lattner458b2aa2010-07-29 02:16:43 +00005831 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005832 return ABIArgInfo::getIgnore();
5833
Bob Wilson1d9269a2011-11-02 04:51:36 +00005834 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005835 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005836 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005837 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005838 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005839 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005840 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005841 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005842 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005843 }
5844
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005845 // Aggregates <= 4 bytes are returned in r0; other aggregates
5846 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005847 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005848 if (Size <= 32) {
Pirama Arumuga Nainarbb846a32016-07-27 19:01:51 +00005849 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
5850 // same size and alignment.
5851 if (getTarget().isRenderScriptTarget()) {
5852 return coerceToIntArray(RetTy, getContext(), getVMContext());
5853 }
Christian Pirkerc3d32172014-07-03 09:28:12 +00005854 if (getDataLayout().isBigEndian())
5855 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005856 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005857
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005858 // Return in the smallest viable integer type.
5859 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005860 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005861 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005862 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5863 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005864 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5865 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5866 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005867 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005868 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005869 }
5870
John McCall7f416cc2015-09-08 08:05:57 +00005871 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005872}
5873
Manman Renfef9e312012-10-16 19:18:39 +00005874/// isIllegalVector - check whether Ty is an illegal vector type.
5875bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005876 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5877 if (isAndroid()) {
5878 // Android shipped using Clang 3.1, which supported a slightly different
5879 // vector ABI. The primary differences were that 3-element vector types
5880 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5881 // accepts that legacy behavior for Android only.
5882 // Check whether VT is legal.
5883 unsigned NumElements = VT->getNumElements();
5884 // NumElements should be power of 2 or equal to 3.
5885 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5886 return true;
5887 } else {
5888 // Check whether VT is legal.
5889 unsigned NumElements = VT->getNumElements();
5890 uint64_t Size = getContext().getTypeSize(VT);
5891 // NumElements should be power of 2.
5892 if (!llvm::isPowerOf2_32(NumElements))
5893 return true;
5894 // Size should be greater than 32 bits.
5895 return Size <= 32;
5896 }
Manman Renfef9e312012-10-16 19:18:39 +00005897 }
5898 return false;
5899}
5900
Reid Klecknere9f6a712014-10-31 17:10:41 +00005901bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5902 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5903 // double, or 64-bit or 128-bit vectors.
5904 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5905 if (BT->getKind() == BuiltinType::Float ||
5906 BT->getKind() == BuiltinType::Double ||
5907 BT->getKind() == BuiltinType::LongDouble)
5908 return true;
5909 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5910 unsigned VecSize = getContext().getTypeSize(VT);
5911 if (VecSize == 64 || VecSize == 128)
5912 return true;
5913 }
5914 return false;
5915}
5916
5917bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5918 uint64_t Members) const {
5919 return Members <= 4;
5920}
5921
John McCall7f416cc2015-09-08 08:05:57 +00005922Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5923 QualType Ty) const {
5924 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005925
John McCall7f416cc2015-09-08 08:05:57 +00005926 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005927 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005928 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5929 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5930 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005931 }
5932
John McCall7f416cc2015-09-08 08:05:57 +00005933 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5934 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005935
John McCall7f416cc2015-09-08 08:05:57 +00005936 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5937 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005938 const Type *Base = nullptr;
5939 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005940 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5941 IsIndirect = true;
5942
Tim Northover5627d392015-10-30 16:30:45 +00005943 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5944 // allocated by the caller.
5945 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5946 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5947 !isHomogeneousAggregate(Ty, Base, Members)) {
5948 IsIndirect = true;
5949
John McCall7f416cc2015-09-08 08:05:57 +00005950 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005951 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5952 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005953 // Our callers should be prepared to handle an under-aligned address.
5954 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5955 getABIKind() == ARMABIInfo::AAPCS) {
5956 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5957 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005958 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5959 // ARMv7k allows type alignment up to 16 bytes.
5960 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5961 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005962 } else {
5963 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005964 }
John McCall7f416cc2015-09-08 08:05:57 +00005965 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005966
John McCall7f416cc2015-09-08 08:05:57 +00005967 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5968 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005969}
5970
Chris Lattner0cf24192010-06-28 20:05:43 +00005971//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005972// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005973//===----------------------------------------------------------------------===//
5974
5975namespace {
5976
Justin Holewinski83e96682012-05-24 17:43:12 +00005977class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005978public:
Justin Holewinski36837432013-03-30 14:38:24 +00005979 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005980
5981 ABIArgInfo classifyReturnType(QualType RetTy) const;
5982 ABIArgInfo classifyArgumentType(QualType Ty) const;
5983
Craig Topper4f12f102014-03-12 06:41:41 +00005984 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005985 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5986 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005987};
5988
Justin Holewinski83e96682012-05-24 17:43:12 +00005989class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005990public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005991 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5992 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005993
Eric Christopher162c91c2015-06-05 22:03:00 +00005994 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005995 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005996private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005997 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5998 // resulting MDNode to the nvvm.annotations MDNode.
5999 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006000};
6001
Justin Holewinski83e96682012-05-24 17:43:12 +00006002ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006003 if (RetTy->isVoidType())
6004 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006005
6006 // note: this is different from default ABI
6007 if (!RetTy->isScalarType())
6008 return ABIArgInfo::getDirect();
6009
6010 // Treat an enum type as its underlying type.
6011 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6012 RetTy = EnumTy->getDecl()->getIntegerType();
6013
6014 return (RetTy->isPromotableIntegerType() ?
6015 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006016}
6017
Justin Holewinski83e96682012-05-24 17:43:12 +00006018ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006019 // Treat an enum type as its underlying type.
6020 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6021 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006022
Eli Bendersky95338a02014-10-29 13:43:21 +00006023 // Return aggregates type as indirect by value
6024 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006025 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00006026
Justin Holewinskif9329ff2013-11-20 20:35:34 +00006027 return (Ty->isPromotableIntegerType() ?
6028 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006029}
6030
Justin Holewinski83e96682012-05-24 17:43:12 +00006031void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006032 if (!getCXXABI().classifyReturnType(FI))
6033 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006034 for (auto &I : FI.arguments())
6035 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006036
6037 // Always honor user-specified calling convention.
6038 if (FI.getCallingConvention() != llvm::CallingConv::C)
6039 return;
6040
John McCall882987f2013-02-28 19:01:20 +00006041 FI.setEffectiveCallingConvention(getRuntimeCC());
6042}
6043
John McCall7f416cc2015-09-08 08:05:57 +00006044Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6045 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00006046 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006047}
6048
Justin Holewinski83e96682012-05-24 17:43:12 +00006049void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00006050setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00006051 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006052 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00006053 if (!FD) return;
6054
6055 llvm::Function *F = cast<llvm::Function>(GV);
6056
6057 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00006058 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00006059 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00006060 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00006061 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00006062 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00006063 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6064 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00006065 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006066 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00006067 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006068 }
Justin Holewinski38031972011-10-05 17:58:44 +00006069
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006070 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006071 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00006072 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00006073 // __global__ functions cannot be called from the device, we do not
6074 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00006075 if (FD->hasAttr<CUDAGlobalAttr>()) {
6076 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6077 addNVVMMetadata(F, "kernel", 1);
6078 }
Artem Belevich7093e402015-04-21 22:55:54 +00006079 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00006080 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00006081 llvm::APSInt MaxThreads(32);
6082 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6083 if (MaxThreads > 0)
6084 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6085
6086 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6087 // not specified in __launch_bounds__ or if the user specified a 0 value,
6088 // we don't have to add a PTX directive.
6089 if (Attr->getMinBlocks()) {
6090 llvm::APSInt MinBlocks(32);
6091 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6092 if (MinBlocks > 0)
6093 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6094 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00006095 }
6096 }
Justin Holewinski38031972011-10-05 17:58:44 +00006097 }
6098}
6099
Eli Benderskye06a2c42014-04-15 16:57:05 +00006100void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6101 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00006102 llvm::Module *M = F->getParent();
6103 llvm::LLVMContext &Ctx = M->getContext();
6104
6105 // Get "nvvm.annotations" metadata node
6106 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6107
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006108 llvm::Metadata *MDVals[] = {
6109 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6110 llvm::ConstantAsMetadata::get(
6111 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00006112 // Append metadata to nvvm.annotations
6113 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6114}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006115}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00006116
6117//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00006118// SystemZ ABI Implementation
6119//===----------------------------------------------------------------------===//
6120
6121namespace {
6122
Bryan Chane3f1ed52016-04-28 13:56:43 +00006123class SystemZABIInfo : public SwiftABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006124 bool HasVector;
6125
Ulrich Weigand47445072013-05-06 16:26:41 +00006126public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006127 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
Bryan Chane3f1ed52016-04-28 13:56:43 +00006128 : SwiftABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006129
6130 bool isPromotableIntegerType(QualType Ty) const;
6131 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006132 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006133 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006134 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00006135
6136 ABIArgInfo classifyReturnType(QualType RetTy) const;
6137 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6138
Craig Topper4f12f102014-03-12 06:41:41 +00006139 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006140 if (!getCXXABI().classifyReturnType(FI))
6141 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006142 for (auto &I : FI.arguments())
6143 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00006144 }
6145
John McCall7f416cc2015-09-08 08:05:57 +00006146 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6147 QualType Ty) const override;
Bryan Chane3f1ed52016-04-28 13:56:43 +00006148
6149 bool shouldPassIndirectlyForSwift(CharUnits totalSize,
6150 ArrayRef<llvm::Type*> scalars,
6151 bool asReturnValue) const override {
6152 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6153 }
Arnold Schwaighoferb0f2c332016-12-01 18:07:38 +00006154 bool isSwiftErrorInRegister() const override {
6155 return true;
6156 }
Ulrich Weigand47445072013-05-06 16:26:41 +00006157};
6158
6159class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6160public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006161 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6162 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00006163};
6164
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006165}
Ulrich Weigand47445072013-05-06 16:26:41 +00006166
6167bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6168 // Treat an enum type as its underlying type.
6169 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6170 Ty = EnumTy->getDecl()->getIntegerType();
6171
6172 // Promotable integer types are required to be promoted by the ABI.
6173 if (Ty->isPromotableIntegerType())
6174 return true;
6175
6176 // 32-bit values must also be promoted.
6177 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6178 switch (BT->getKind()) {
6179 case BuiltinType::Int:
6180 case BuiltinType::UInt:
6181 return true;
6182 default:
6183 return false;
6184 }
6185 return false;
6186}
6187
6188bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006189 return (Ty->isAnyComplexType() ||
6190 Ty->isVectorType() ||
6191 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00006192}
6193
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006194bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6195 return (HasVector &&
6196 Ty->isVectorType() &&
6197 getContext().getTypeSize(Ty) <= 128);
6198}
6199
Ulrich Weigand47445072013-05-06 16:26:41 +00006200bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6201 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6202 switch (BT->getKind()) {
6203 case BuiltinType::Float:
6204 case BuiltinType::Double:
6205 return true;
6206 default:
6207 return false;
6208 }
6209
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006210 return false;
6211}
6212
6213QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006214 if (const RecordType *RT = Ty->getAsStructureType()) {
6215 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006216 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006217
6218 // If this is a C++ record, check the bases first.
6219 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00006220 for (const auto &I : CXXRD->bases()) {
6221 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00006222
6223 // Empty bases don't affect things either way.
6224 if (isEmptyRecord(getContext(), Base, true))
6225 continue;
6226
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006227 if (!Found.isNull())
6228 return Ty;
6229 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00006230 }
6231
6232 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006233 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00006234 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00006235 // Unlike isSingleElementStruct(), empty structure and array fields
6236 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00006237 if (getContext().getLangOpts().CPlusPlus &&
6238 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
6239 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00006240
6241 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006242 // Nested structures still do though.
6243 if (!Found.isNull())
6244 return Ty;
6245 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00006246 }
6247
6248 // Unlike isSingleElementStruct(), trailing padding is allowed.
6249 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006250 if (!Found.isNull())
6251 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00006252 }
6253
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006254 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00006255}
6256
John McCall7f416cc2015-09-08 08:05:57 +00006257Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6258 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00006259 // Assume that va_list type is correct; should be pointer to LLVM type:
6260 // struct {
6261 // i64 __gpr;
6262 // i64 __fpr;
6263 // i8 *__overflow_arg_area;
6264 // i8 *__reg_save_area;
6265 // };
6266
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006267 // Every non-vector argument occupies 8 bytes and is passed by preference
6268 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6269 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00006270 Ty = getContext().getCanonicalType(Ty);
6271 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006272 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006273 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00006274 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00006275 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00006276 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006277 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00006278 CharUnits UnpaddedSize;
6279 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00006280 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00006281 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6282 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00006283 } else {
6284 if (AI.getCoerceToType())
6285 ArgTy = AI.getCoerceToType();
6286 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006287 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00006288 UnpaddedSize = TyInfo.first;
6289 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00006290 }
John McCall7f416cc2015-09-08 08:05:57 +00006291 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6292 if (IsVector && UnpaddedSize > PaddedSize)
6293 PaddedSize = CharUnits::fromQuantity(16);
6294 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00006295
John McCall7f416cc2015-09-08 08:05:57 +00006296 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00006297
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006298 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00006299 llvm::Value *PaddedSizeV =
6300 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006301
6302 if (IsVector) {
6303 // Work out the address of a vector argument on the stack.
6304 // Vector arguments are always passed in the high bits of a
6305 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00006306 Address OverflowArgAreaPtr =
6307 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006308 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00006309 Address OverflowArgArea =
6310 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6311 TyInfo.second);
6312 Address MemAddr =
6313 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006314
6315 // Update overflow_arg_area_ptr pointer
6316 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006317 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6318 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006319 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6320
6321 return MemAddr;
6322 }
6323
John McCall7f416cc2015-09-08 08:05:57 +00006324 assert(PaddedSize.getQuantity() == 8);
6325
6326 unsigned MaxRegs, RegCountField, RegSaveIndex;
6327 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00006328 if (InFPRs) {
6329 MaxRegs = 4; // Maximum of 4 FPR arguments
6330 RegCountField = 1; // __fpr
6331 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00006332 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00006333 } else {
6334 MaxRegs = 5; // Maximum of 5 GPR arguments
6335 RegCountField = 0; // __gpr
6336 RegSaveIndex = 2; // save offset for r2
6337 RegPadding = Padding; // values are passed in the low bits of a GPR
6338 }
6339
John McCall7f416cc2015-09-08 08:05:57 +00006340 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6341 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6342 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006343 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00006344 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6345 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00006346 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00006347
6348 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6349 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6350 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6351 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6352
6353 // Emit code to load the value if it was passed in registers.
6354 CGF.EmitBlock(InRegBlock);
6355
6356 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00006357 llvm::Value *ScaledRegCount =
6358 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6359 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00006360 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6361 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00006362 llvm::Value *RegOffset =
6363 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00006364 Address RegSaveAreaPtr =
6365 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6366 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006367 llvm::Value *RegSaveArea =
6368 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00006369 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6370 "raw_reg_addr"),
6371 PaddedSize);
6372 Address RegAddr =
6373 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006374
6375 // Update the register count
6376 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6377 llvm::Value *NewRegCount =
6378 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6379 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6380 CGF.EmitBranch(ContBlock);
6381
6382 // Emit code to load the value if it was passed in memory.
6383 CGF.EmitBlock(InMemBlock);
6384
6385 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00006386 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6387 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6388 Address OverflowArgArea =
6389 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6390 PaddedSize);
6391 Address RawMemAddr =
6392 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6393 Address MemAddr =
6394 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006395
6396 // Update overflow_arg_area_ptr pointer
6397 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00006398 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6399 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00006400 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6401 CGF.EmitBranch(ContBlock);
6402
6403 // Return the appropriate result.
6404 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00006405 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6406 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00006407
6408 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00006409 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6410 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00006411
6412 return ResAddr;
6413}
6414
Ulrich Weigand47445072013-05-06 16:26:41 +00006415ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6416 if (RetTy->isVoidType())
6417 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006418 if (isVectorArgumentType(RetTy))
6419 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00006420 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006421 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00006422 return (isPromotableIntegerType(RetTy) ?
6423 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6424}
6425
6426ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6427 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00006428 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006429 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00006430
6431 // Integers and enums are extended to full register width.
6432 if (isPromotableIntegerType(Ty))
6433 return ABIArgInfo::getExtend();
6434
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006435 // Handle vector types and vector-like structure types. Note that
6436 // as opposed to float-like structure types, we do not allow any
6437 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00006438 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006439 QualType SingleElementTy = GetSingleElementType(Ty);
6440 if (isVectorArgumentType(SingleElementTy) &&
6441 getContext().getTypeSize(SingleElementTy) == Size)
6442 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6443
6444 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00006445 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00006446 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006447
6448 // Handle small structures.
6449 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6450 // Structures with flexible arrays have variable length, so really
6451 // fail the size test above.
6452 const RecordDecl *RD = RT->getDecl();
6453 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00006454 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006455
6456 // The structure is passed as an unextended integer, a float, or a double.
6457 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00006458 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00006459 assert(Size == 32 || Size == 64);
6460 if (Size == 32)
6461 PassTy = llvm::Type::getFloatTy(getVMContext());
6462 else
6463 PassTy = llvm::Type::getDoubleTy(getVMContext());
6464 } else
6465 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6466 return ABIArgInfo::getDirect(PassTy);
6467 }
6468
6469 // Non-structure compounds are passed indirectly.
6470 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00006471 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00006472
Craig Topper8a13c412014-05-21 05:09:00 +00006473 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00006474}
6475
6476//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006477// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00006478//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006479
6480namespace {
6481
6482class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6483public:
Chris Lattner2b037972010-07-29 02:01:43 +00006484 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6485 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006486 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006487 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006488};
6489
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006490}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006491
Eric Christopher162c91c2015-06-05 22:03:00 +00006492void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006493 llvm::GlobalValue *GV,
6494 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006495 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006496 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6497 // Handle 'interrupt' attribute:
6498 llvm::Function *F = cast<llvm::Function>(GV);
6499
6500 // Step 1: Set ISR calling convention.
6501 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6502
6503 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00006504 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006505
6506 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00006507 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00006508 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6509 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00006510 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00006511 }
6512}
6513
Chris Lattner0cf24192010-06-28 20:05:43 +00006514//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00006515// MIPS ABI Implementation. This works for both little-endian and
6516// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00006517//===----------------------------------------------------------------------===//
6518
John McCall943fae92010-05-27 06:19:26 +00006519namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006520class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00006521 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006522 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6523 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00006524 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006525 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006526 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006527 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006528public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006529 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006530 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006531 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00006532
6533 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006534 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006535 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006536 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6537 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006538 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006539};
6540
John McCall943fae92010-05-27 06:19:26 +00006541class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006542 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00006543public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00006544 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6545 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00006546 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00006547
Craig Topper4f12f102014-03-12 06:41:41 +00006548 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00006549 return 29;
6550 }
6551
Eric Christopher162c91c2015-06-05 22:03:00 +00006552 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006553 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006554 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006555 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00006556 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00006557 if (FD->hasAttr<Mips16Attr>()) {
6558 Fn->addFnAttr("mips16");
6559 }
6560 else if (FD->hasAttr<NoMips16Attr>()) {
6561 Fn->addFnAttr("nomips16");
6562 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006563
6564 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6565 if (!Attr)
6566 return;
6567
6568 const char *Kind;
6569 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00006570 case MipsInterruptAttr::eic: Kind = "eic"; break;
6571 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6572 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6573 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6574 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6575 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6576 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6577 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6578 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6579 }
6580
6581 Fn->addFnAttr("interrupt", Kind);
6582
Reed Kotler373feca2013-01-16 17:10:28 +00006583 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006584
John McCall943fae92010-05-27 06:19:26 +00006585 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006586 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006587
Craig Topper4f12f102014-03-12 06:41:41 +00006588 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006589 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006590 }
John McCall943fae92010-05-27 06:19:26 +00006591};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006592}
John McCall943fae92010-05-27 06:19:26 +00006593
Eric Christopher7565e0d2015-05-29 23:09:49 +00006594void MipsABIInfo::CoerceToIntArgs(
6595 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006596 llvm::IntegerType *IntTy =
6597 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006598
6599 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6600 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6601 ArgList.push_back(IntTy);
6602
6603 // If necessary, add one more integer type to ArgList.
6604 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6605
6606 if (R)
6607 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006608}
6609
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006610// In N32/64, an aligned double precision floating point field is passed in
6611// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006612llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006613 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6614
6615 if (IsO32) {
6616 CoerceToIntArgs(TySize, ArgList);
6617 return llvm::StructType::get(getVMContext(), ArgList);
6618 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006619
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006620 if (Ty->isComplexType())
6621 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006622
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006623 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006624
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006625 // Unions/vectors are passed in integer registers.
6626 if (!RT || !RT->isStructureOrClassType()) {
6627 CoerceToIntArgs(TySize, ArgList);
6628 return llvm::StructType::get(getVMContext(), ArgList);
6629 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006630
6631 const RecordDecl *RD = RT->getDecl();
6632 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006633 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006634
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006635 uint64_t LastOffset = 0;
6636 unsigned idx = 0;
6637 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6638
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006639 // Iterate over fields in the struct/class and check if there are any aligned
6640 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006641 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6642 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006643 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006644 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6645
6646 if (!BT || BT->getKind() != BuiltinType::Double)
6647 continue;
6648
6649 uint64_t Offset = Layout.getFieldOffset(idx);
6650 if (Offset % 64) // Ignore doubles that are not aligned.
6651 continue;
6652
6653 // Add ((Offset - LastOffset) / 64) args of type i64.
6654 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6655 ArgList.push_back(I64);
6656
6657 // Add double type.
6658 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6659 LastOffset = Offset + 64;
6660 }
6661
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006662 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6663 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006664
6665 return llvm::StructType::get(getVMContext(), ArgList);
6666}
6667
Akira Hatanakaddd66342013-10-29 18:41:15 +00006668llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6669 uint64_t Offset) const {
6670 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006671 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006672
Akira Hatanakaddd66342013-10-29 18:41:15 +00006673 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006674}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006675
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006676ABIArgInfo
6677MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006678 Ty = useFirstFieldIfTransparentUnion(Ty);
6679
Akira Hatanaka1632af62012-01-09 19:31:25 +00006680 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006681 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006682 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006683
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006684 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6685 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006686 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6687 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006688
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006689 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006690 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006691 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006692 return ABIArgInfo::getIgnore();
6693
Mark Lacey3825e832013-10-06 01:33:34 +00006694 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006695 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006696 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006697 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006698
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006699 // If we have reached here, aggregates are passed directly by coercing to
6700 // another structure type. Padding is inserted if the offset of the
6701 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006702 ABIArgInfo ArgInfo =
6703 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6704 getPaddingType(OrigOffset, CurrOffset));
6705 ArgInfo.setInReg(true);
6706 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006707 }
6708
6709 // Treat an enum type as its underlying type.
6710 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6711 Ty = EnumTy->getDecl()->getIntegerType();
6712
Daniel Sanders5b445b32014-10-24 14:42:42 +00006713 // All integral types are promoted to the GPR width.
6714 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006715 return ABIArgInfo::getExtend();
6716
Akira Hatanakaddd66342013-10-29 18:41:15 +00006717 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006718 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006719}
6720
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006721llvm::Type*
6722MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006723 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006724 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006725
Akira Hatanakab6f74432012-02-09 18:49:26 +00006726 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006727 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006728 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6729 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006730
Akira Hatanakab6f74432012-02-09 18:49:26 +00006731 // N32/64 returns struct/classes in floating point registers if the
6732 // following conditions are met:
6733 // 1. The size of the struct/class is no larger than 128-bit.
6734 // 2. The struct/class has one or two fields all of which are floating
6735 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006736 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006737 //
6738 // Any other composite results are returned in integer registers.
6739 //
6740 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6741 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6742 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006743 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006744
Akira Hatanakab6f74432012-02-09 18:49:26 +00006745 if (!BT || !BT->isFloatingPoint())
6746 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006747
David Blaikie2d7c57e2012-04-30 02:36:29 +00006748 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006749 }
6750
6751 if (b == e)
6752 return llvm::StructType::get(getVMContext(), RTList,
6753 RD->hasAttr<PackedAttr>());
6754
6755 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006756 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006757 }
6758
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006759 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006760 return llvm::StructType::get(getVMContext(), RTList);
6761}
6762
Akira Hatanakab579fe52011-06-02 00:09:17 +00006763ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006764 uint64_t Size = getContext().getTypeSize(RetTy);
6765
Daniel Sandersed39f582014-09-04 13:28:14 +00006766 if (RetTy->isVoidType())
6767 return ABIArgInfo::getIgnore();
6768
6769 // O32 doesn't treat zero-sized structs differently from other structs.
6770 // However, N32/N64 ignores zero sized return values.
6771 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006772 return ABIArgInfo::getIgnore();
6773
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006774 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006775 if (Size <= 128) {
6776 if (RetTy->isAnyComplexType())
6777 return ABIArgInfo::getDirect();
6778
Daniel Sanderse5018b62014-09-04 15:05:39 +00006779 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006780 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006781 if (!IsO32 ||
6782 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6783 ABIArgInfo ArgInfo =
6784 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6785 ArgInfo.setInReg(true);
6786 return ArgInfo;
6787 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006788 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006789
John McCall7f416cc2015-09-08 08:05:57 +00006790 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006791 }
6792
6793 // Treat an enum type as its underlying type.
6794 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6795 RetTy = EnumTy->getDecl()->getIntegerType();
6796
6797 return (RetTy->isPromotableIntegerType() ?
6798 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6799}
6800
6801void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006802 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006803 if (!getCXXABI().classifyReturnType(FI))
6804 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006805
Eric Christopher7565e0d2015-05-29 23:09:49 +00006806 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006807 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006808
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006809 for (auto &I : FI.arguments())
6810 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006811}
6812
John McCall7f416cc2015-09-08 08:05:57 +00006813Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6814 QualType OrigTy) const {
6815 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006816
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006817 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6818 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006819 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006820 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006821 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006822 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006823 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006824 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006825 DidPromote = true;
6826 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6827 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006828 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006829
John McCall7f416cc2015-09-08 08:05:57 +00006830 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006831
John McCall7f416cc2015-09-08 08:05:57 +00006832 // The alignment of things in the argument area is never larger than
6833 // StackAlignInBytes.
6834 TyInfo.second =
6835 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6836
6837 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6838 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6839
6840 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6841 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6842
6843
6844 // If there was a promotion, "unpromote" into a temporary.
6845 // TODO: can we just use a pointer into a subset of the original slot?
6846 if (DidPromote) {
6847 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6848 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6849
6850 // Truncate down to the right width.
6851 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6852 : CGF.IntPtrTy);
6853 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6854 if (OrigTy->isPointerType())
6855 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6856
6857 CGF.Builder.CreateStore(V, Temp);
6858 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006859 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006860
John McCall7f416cc2015-09-08 08:05:57 +00006861 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006862}
6863
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006864bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6865 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006866
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006867 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6868 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6869 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006870
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006871 return false;
6872}
6873
John McCall943fae92010-05-27 06:19:26 +00006874bool
6875MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6876 llvm::Value *Address) const {
6877 // This information comes from gcc's implementation, which seems to
6878 // as canonical as it gets.
6879
John McCall943fae92010-05-27 06:19:26 +00006880 // Everything on MIPS is 4 bytes. Double-precision FP registers
6881 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006882 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006883
6884 // 0-31 are the general purpose registers, $0 - $31.
6885 // 32-63 are the floating-point registers, $f0 - $f31.
6886 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6887 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006888 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006889
6890 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6891 // They are one bit wide and ignored here.
6892
6893 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6894 // (coprocessor 1 is the FP unit)
6895 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6896 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6897 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006898 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006899 return false;
6900}
6901
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006902//===----------------------------------------------------------------------===//
Dylan McKaye8232d72017-02-08 05:09:26 +00006903// AVR ABI Implementation.
6904//===----------------------------------------------------------------------===//
6905
6906namespace {
6907class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
6908public:
6909 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
6910 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
6911
6912 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6913 CodeGen::CodeGenModule &CGM) const override {
6914 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
6915 if (!FD) return;
6916 auto *Fn = cast<llvm::Function>(GV);
6917
6918 if (FD->getAttr<AVRInterruptAttr>())
6919 Fn->addFnAttr("interrupt");
6920
6921 if (FD->getAttr<AVRSignalAttr>())
6922 Fn->addFnAttr("signal");
6923 }
6924};
6925}
6926
6927//===----------------------------------------------------------------------===//
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006928// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006929// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006930// handling.
6931//===----------------------------------------------------------------------===//
6932
6933namespace {
6934
6935class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6936public:
6937 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6938 : DefaultTargetCodeGenInfo(CGT) {}
6939
Eric Christopher162c91c2015-06-05 22:03:00 +00006940 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006941 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006942};
6943
Eric Christopher162c91c2015-06-05 22:03:00 +00006944void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006945 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006946 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006947 if (!FD) return;
6948
6949 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006950
David Blaikiebbafb8a2012-03-11 07:00:24 +00006951 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006952 if (FD->hasAttr<OpenCLKernelAttr>()) {
6953 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006954 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006955 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6956 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006957 // Convert the reqd_work_group_size() attributes to metadata.
6958 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006959 llvm::NamedMDNode *OpenCLMetadata =
6960 M.getModule().getOrInsertNamedMetadata(
6961 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006962
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006963 SmallVector<llvm::Metadata *, 5> Operands;
6964 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006965
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006966 Operands.push_back(
6967 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6968 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6969 Operands.push_back(
6970 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6971 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6972 Operands.push_back(
6973 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6974 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006975
Eric Christopher7565e0d2015-05-29 23:09:49 +00006976 // Add a boolean constant operand for "required" (true) or "hint"
6977 // (false) for implementing the work_group_size_hint attr later.
6978 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006979 Operands.push_back(
6980 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006981 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6982 }
6983 }
6984 }
6985}
6986
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006987}
John McCall943fae92010-05-27 06:19:26 +00006988
Tony Linthicum76329bf2011-12-12 21:14:55 +00006989//===----------------------------------------------------------------------===//
6990// Hexagon ABI Implementation
6991//===----------------------------------------------------------------------===//
6992
6993namespace {
6994
6995class HexagonABIInfo : public ABIInfo {
6996
6997
6998public:
6999 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7000
7001private:
7002
7003 ABIArgInfo classifyReturnType(QualType RetTy) const;
7004 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7005
Craig Topper4f12f102014-03-12 06:41:41 +00007006 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007007
John McCall7f416cc2015-09-08 08:05:57 +00007008 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7009 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00007010};
7011
7012class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7013public:
7014 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7015 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7016
Craig Topper4f12f102014-03-12 06:41:41 +00007017 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00007018 return 29;
7019 }
7020};
7021
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007022}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007023
7024void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00007025 if (!getCXXABI().classifyReturnType(FI))
7026 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007027 for (auto &I : FI.arguments())
7028 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007029}
7030
7031ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7032 if (!isAggregateTypeForABI(Ty)) {
7033 // Treat an enum type as its underlying type.
7034 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7035 Ty = EnumTy->getDecl()->getIntegerType();
7036
7037 return (Ty->isPromotableIntegerType() ?
7038 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7039 }
7040
7041 // Ignore empty records.
7042 if (isEmptyRecord(getContext(), Ty, true))
7043 return ABIArgInfo::getIgnore();
7044
Mark Lacey3825e832013-10-06 01:33:34 +00007045 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007046 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007047
7048 uint64_t Size = getContext().getTypeSize(Ty);
7049 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007050 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007051 // Pass in the smallest viable integer type.
7052 else if (Size > 32)
7053 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7054 else if (Size > 16)
7055 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7056 else if (Size > 8)
7057 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7058 else
7059 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7060}
7061
7062ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7063 if (RetTy->isVoidType())
7064 return ABIArgInfo::getIgnore();
7065
7066 // Large vector types should be returned via memory.
7067 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00007068 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007069
7070 if (!isAggregateTypeForABI(RetTy)) {
7071 // Treat an enum type as its underlying type.
7072 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7073 RetTy = EnumTy->getDecl()->getIntegerType();
7074
7075 return (RetTy->isPromotableIntegerType() ?
7076 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
7077 }
7078
Tony Linthicum76329bf2011-12-12 21:14:55 +00007079 if (isEmptyRecord(getContext(), RetTy, true))
7080 return ABIArgInfo::getIgnore();
7081
7082 // Aggregates <= 8 bytes are returned in r0; other aggregates
7083 // are returned indirectly.
7084 uint64_t Size = getContext().getTypeSize(RetTy);
7085 if (Size <= 64) {
7086 // Return in the smallest viable integer type.
7087 if (Size <= 8)
7088 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7089 if (Size <= 16)
7090 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7091 if (Size <= 32)
7092 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7093 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7094 }
7095
John McCall7f416cc2015-09-08 08:05:57 +00007096 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007097}
7098
John McCall7f416cc2015-09-08 08:05:57 +00007099Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7100 QualType Ty) const {
7101 // FIXME: Someone needs to audit that this handle alignment correctly.
7102 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7103 getContext().getTypeInfoInChars(Ty),
7104 CharUnits::fromQuantity(4),
7105 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00007106}
7107
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007108//===----------------------------------------------------------------------===//
Jacques Pienaard964cc22016-03-28 21:02:54 +00007109// Lanai ABI Implementation
7110//===----------------------------------------------------------------------===//
7111
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007112namespace {
Jacques Pienaard964cc22016-03-28 21:02:54 +00007113class LanaiABIInfo : public DefaultABIInfo {
7114public:
7115 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7116
7117 bool shouldUseInReg(QualType Ty, CCState &State) const;
7118
7119 void computeInfo(CGFunctionInfo &FI) const override {
7120 CCState State(FI.getCallingConvention());
7121 // Lanai uses 4 registers to pass arguments unless the function has the
7122 // regparm attribute set.
7123 if (FI.getHasRegParm()) {
7124 State.FreeRegs = FI.getRegParm();
7125 } else {
7126 State.FreeRegs = 4;
7127 }
7128
7129 if (!getCXXABI().classifyReturnType(FI))
7130 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7131 for (auto &I : FI.arguments())
7132 I.info = classifyArgumentType(I.type, State);
7133 }
7134
Jacques Pienaare74d9132016-04-26 00:09:29 +00007135 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
Jacques Pienaard964cc22016-03-28 21:02:54 +00007136 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7137};
Benjamin Kramer5d28c7f2016-04-07 10:14:54 +00007138} // end anonymous namespace
Jacques Pienaard964cc22016-03-28 21:02:54 +00007139
7140bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7141 unsigned Size = getContext().getTypeSize(Ty);
7142 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7143
7144 if (SizeInRegs == 0)
7145 return false;
7146
7147 if (SizeInRegs > State.FreeRegs) {
7148 State.FreeRegs = 0;
7149 return false;
7150 }
7151
7152 State.FreeRegs -= SizeInRegs;
7153
7154 return true;
7155}
7156
Jacques Pienaare74d9132016-04-26 00:09:29 +00007157ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7158 CCState &State) const {
7159 if (!ByVal) {
7160 if (State.FreeRegs) {
7161 --State.FreeRegs; // Non-byval indirects just use one pointer.
7162 return getNaturalAlignIndirectInReg(Ty);
7163 }
7164 return getNaturalAlignIndirect(Ty, false);
7165 }
7166
7167 // Compute the byval alignment.
Kostya Serebryany0da44422016-04-26 01:53:49 +00007168 const unsigned MinABIStackAlignInBytes = 4;
Jacques Pienaare74d9132016-04-26 00:09:29 +00007169 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7170 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7171 /*Realign=*/TypeAlign >
7172 MinABIStackAlignInBytes);
7173}
7174
Jacques Pienaard964cc22016-03-28 21:02:54 +00007175ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7176 CCState &State) const {
Jacques Pienaare74d9132016-04-26 00:09:29 +00007177 // Check with the C++ ABI first.
7178 const RecordType *RT = Ty->getAs<RecordType>();
7179 if (RT) {
7180 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7181 if (RAA == CGCXXABI::RAA_Indirect) {
7182 return getIndirectResult(Ty, /*ByVal=*/false, State);
7183 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7184 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7185 }
7186 }
7187
7188 if (isAggregateTypeForABI(Ty)) {
7189 // Structures with flexible arrays are always indirect.
7190 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7191 return getIndirectResult(Ty, /*ByVal=*/true, State);
7192
7193 // Ignore empty structs/unions.
7194 if (isEmptyRecord(getContext(), Ty, true))
7195 return ABIArgInfo::getIgnore();
7196
7197 llvm::LLVMContext &LLVMContext = getVMContext();
7198 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7199 if (SizeInRegs <= State.FreeRegs) {
7200 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7201 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7202 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7203 State.FreeRegs -= SizeInRegs;
7204 return ABIArgInfo::getDirectInReg(Result);
7205 } else {
7206 State.FreeRegs = 0;
7207 }
7208 return getIndirectResult(Ty, true, State);
7209 }
Jacques Pienaard964cc22016-03-28 21:02:54 +00007210
7211 // Treat an enum type as its underlying type.
7212 if (const auto *EnumTy = Ty->getAs<EnumType>())
7213 Ty = EnumTy->getDecl()->getIntegerType();
7214
Jacques Pienaare74d9132016-04-26 00:09:29 +00007215 bool InReg = shouldUseInReg(Ty, State);
7216 if (Ty->isPromotableIntegerType()) {
7217 if (InReg)
7218 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007219 return ABIArgInfo::getExtend();
Jacques Pienaare74d9132016-04-26 00:09:29 +00007220 }
7221 if (InReg)
7222 return ABIArgInfo::getDirectInReg();
Jacques Pienaard964cc22016-03-28 21:02:54 +00007223 return ABIArgInfo::getDirect();
7224}
7225
7226namespace {
7227class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7228public:
7229 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7230 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7231};
7232}
7233
7234//===----------------------------------------------------------------------===//
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007235// AMDGPU ABI Implementation
7236//===----------------------------------------------------------------------===//
7237
7238namespace {
7239
Matt Arsenault88d7da02016-08-22 19:25:59 +00007240class AMDGPUABIInfo final : public DefaultABIInfo {
7241public:
7242 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7243
7244private:
7245 ABIArgInfo classifyArgumentType(QualType Ty) const;
7246
7247 void computeInfo(CGFunctionInfo &FI) const override;
7248};
7249
7250void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7251 if (!getCXXABI().classifyReturnType(FI))
7252 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7253
7254 unsigned CC = FI.getCallingConvention();
7255 for (auto &Arg : FI.arguments())
7256 if (CC == llvm::CallingConv::AMDGPU_KERNEL)
7257 Arg.info = classifyArgumentType(Arg.type);
7258 else
7259 Arg.info = DefaultABIInfo::classifyArgumentType(Arg.type);
7260}
7261
7262/// \brief Classify argument of given type \p Ty.
7263ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty) const {
7264 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7265 if (!StrTy) {
7266 return DefaultABIInfo::classifyArgumentType(Ty);
7267 }
7268
7269 // Coerce single element structs to its element.
7270 if (StrTy->getNumElements() == 1) {
7271 return ABIArgInfo::getDirect();
7272 }
7273
7274 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7275 // individual elements, which confuses the Clover OpenCL backend; therefore we
7276 // have to set it to false here. Other args of getDirect() are just defaults.
7277 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7278}
7279
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007280class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7281public:
7282 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
Matt Arsenault88d7da02016-08-22 19:25:59 +00007283 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00007284 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007285 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007286 unsigned getOpenCLKernelCallingConv() const override;
Nico Weber7849eeb2016-12-14 21:38:18 +00007287
Yaxun Liu402804b2016-12-15 08:09:08 +00007288 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7289 llvm::PointerType *T, QualType QT) const override;
7290};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007291}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007292
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007293static void appendOpenCLVersionMD (CodeGen::CodeGenModule &CGM);
7294
Eric Christopher162c91c2015-06-05 22:03:00 +00007295void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007296 const Decl *D,
7297 llvm::GlobalValue *GV,
7298 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00007299 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007300 if (!FD)
7301 return;
7302
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007303 llvm::Function *F = cast<llvm::Function>(GV);
7304
7305 if (const auto *Attr = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) {
7306 unsigned Min = Attr->getMin();
7307 unsigned Max = Attr->getMax();
7308
7309 if (Min != 0) {
7310 assert(Min <= Max && "Min must be less than or equal Max");
7311
7312 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7313 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7314 } else
7315 assert(Max == 0 && "Max must be zero");
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007316 }
7317
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007318 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7319 unsigned Min = Attr->getMin();
7320 unsigned Max = Attr->getMax();
7321
7322 if (Min != 0) {
7323 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7324
7325 std::string AttrVal = llvm::utostr(Min);
7326 if (Max != 0)
7327 AttrVal = AttrVal + "," + llvm::utostr(Max);
7328 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7329 } else
7330 assert(Max == 0 && "Max must be zero");
7331 }
7332
7333 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007334 unsigned NumSGPR = Attr->getNumSGPR();
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007335
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007336 if (NumSGPR != 0)
Konstantin Zhuravlyov5b48d722016-09-26 01:02:57 +00007337 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7338 }
7339
7340 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7341 uint32_t NumVGPR = Attr->getNumVGPR();
7342
7343 if (NumVGPR != 0)
7344 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007345 }
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007346
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00007347 appendOpenCLVersionMD(M);
7348}
Tony Linthicum76329bf2011-12-12 21:14:55 +00007349
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00007350unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7351 return llvm::CallingConv::AMDGPU_KERNEL;
7352}
7353
Yaxun Liu402804b2016-12-15 08:09:08 +00007354// Currently LLVM assumes null pointers always have value 0,
7355// which results in incorrectly transformed IR. Therefore, instead of
7356// emitting null pointers in private and local address spaces, a null
7357// pointer in generic address space is emitted which is casted to a
7358// pointer in local or private address space.
7359llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7360 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7361 QualType QT) const {
7362 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7363 return llvm::ConstantPointerNull::get(PT);
7364
7365 auto &Ctx = CGM.getContext();
7366 auto NPT = llvm::PointerType::get(PT->getElementType(),
7367 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7368 return llvm::ConstantExpr::getAddrSpaceCast(
7369 llvm::ConstantPointerNull::get(NPT), PT);
7370}
7371
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007372//===----------------------------------------------------------------------===//
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00007373// SPARC v8 ABI Implementation.
7374// Based on the SPARC Compliance Definition version 2.4.1.
7375//
7376// Ensures that complex values are passed in registers.
7377//
7378namespace {
7379class SparcV8ABIInfo : public DefaultABIInfo {
7380public:
7381 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7382
7383private:
7384 ABIArgInfo classifyReturnType(QualType RetTy) const;
7385 void computeInfo(CGFunctionInfo &FI) const override;
7386};
7387} // end anonymous namespace
7388
7389
7390ABIArgInfo
7391SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7392 if (Ty->isAnyComplexType()) {
7393 return ABIArgInfo::getDirect();
7394 }
7395 else {
7396 return DefaultABIInfo::classifyReturnType(Ty);
7397 }
7398}
7399
7400void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7401
7402 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7403 for (auto &Arg : FI.arguments())
7404 Arg.info = classifyArgumentType(Arg.type);
7405}
7406
7407namespace {
7408class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7409public:
7410 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7411 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7412};
7413} // end anonymous namespace
7414
7415//===----------------------------------------------------------------------===//
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007416// SPARC v9 ABI Implementation.
7417// Based on the SPARC Compliance Definition version 2.4.1.
7418//
7419// Function arguments a mapped to a nominal "parameter array" and promoted to
7420// registers depending on their type. Each argument occupies 8 or 16 bytes in
7421// the array, structs larger than 16 bytes are passed indirectly.
7422//
7423// One case requires special care:
7424//
7425// struct mixed {
7426// int i;
7427// float f;
7428// };
7429//
7430// When a struct mixed is passed by value, it only occupies 8 bytes in the
7431// parameter array, but the int is passed in an integer register, and the float
7432// is passed in a floating point register. This is represented as two arguments
7433// with the LLVM IR inreg attribute:
7434//
7435// declare void f(i32 inreg %i, float inreg %f)
7436//
7437// The code generator will only allocate 4 bytes from the parameter array for
7438// the inreg arguments. All other arguments are allocated a multiple of 8
7439// bytes.
7440//
7441namespace {
7442class SparcV9ABIInfo : public ABIInfo {
7443public:
7444 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7445
7446private:
7447 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00007448 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00007449 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7450 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007451
7452 // Coercion type builder for structs passed in registers. The coercion type
7453 // serves two purposes:
7454 //
7455 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7456 // in registers.
7457 // 2. Expose aligned floating point elements as first-level elements, so the
7458 // code generator knows to pass them in floating point registers.
7459 //
7460 // We also compute the InReg flag which indicates that the struct contains
7461 // aligned 32-bit floats.
7462 //
7463 struct CoerceBuilder {
7464 llvm::LLVMContext &Context;
7465 const llvm::DataLayout &DL;
7466 SmallVector<llvm::Type*, 8> Elems;
7467 uint64_t Size;
7468 bool InReg;
7469
7470 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7471 : Context(c), DL(dl), Size(0), InReg(false) {}
7472
7473 // Pad Elems with integers until Size is ToSize.
7474 void pad(uint64_t ToSize) {
7475 assert(ToSize >= Size && "Cannot remove elements");
7476 if (ToSize == Size)
7477 return;
7478
7479 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00007480 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007481 if (Aligned > Size && Aligned <= ToSize) {
7482 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7483 Size = Aligned;
7484 }
7485
7486 // Add whole 64-bit words.
7487 while (Size + 64 <= ToSize) {
7488 Elems.push_back(llvm::Type::getInt64Ty(Context));
7489 Size += 64;
7490 }
7491
7492 // Final in-word padding.
7493 if (Size < ToSize) {
7494 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7495 Size = ToSize;
7496 }
7497 }
7498
7499 // Add a floating point element at Offset.
7500 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7501 // Unaligned floats are treated as integers.
7502 if (Offset % Bits)
7503 return;
7504 // The InReg flag is only required if there are any floats < 64 bits.
7505 if (Bits < 64)
7506 InReg = true;
7507 pad(Offset);
7508 Elems.push_back(Ty);
7509 Size = Offset + Bits;
7510 }
7511
7512 // Add a struct type to the coercion type, starting at Offset (in bits).
7513 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7514 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7515 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7516 llvm::Type *ElemTy = StrTy->getElementType(i);
7517 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7518 switch (ElemTy->getTypeID()) {
7519 case llvm::Type::StructTyID:
7520 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7521 break;
7522 case llvm::Type::FloatTyID:
7523 addFloat(ElemOffset, ElemTy, 32);
7524 break;
7525 case llvm::Type::DoubleTyID:
7526 addFloat(ElemOffset, ElemTy, 64);
7527 break;
7528 case llvm::Type::FP128TyID:
7529 addFloat(ElemOffset, ElemTy, 128);
7530 break;
7531 case llvm::Type::PointerTyID:
7532 if (ElemOffset % 64 == 0) {
7533 pad(ElemOffset);
7534 Elems.push_back(ElemTy);
7535 Size += 64;
7536 }
7537 break;
7538 default:
7539 break;
7540 }
7541 }
7542 }
7543
7544 // Check if Ty is a usable substitute for the coercion type.
7545 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00007546 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007547 }
7548
7549 // Get the coercion type as a literal struct type.
7550 llvm::Type *getType() const {
7551 if (Elems.size() == 1)
7552 return Elems.front();
7553 else
7554 return llvm::StructType::get(Context, Elems);
7555 }
7556 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007557};
7558} // end anonymous namespace
7559
7560ABIArgInfo
7561SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7562 if (Ty->isVoidType())
7563 return ABIArgInfo::getIgnore();
7564
7565 uint64_t Size = getContext().getTypeSize(Ty);
7566
7567 // Anything too big to fit in registers is passed with an explicit indirect
7568 // pointer / sret pointer.
7569 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00007570 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007571
7572 // Treat an enum type as its underlying type.
7573 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7574 Ty = EnumTy->getDecl()->getIntegerType();
7575
7576 // Integer types smaller than a register are extended.
7577 if (Size < 64 && Ty->isIntegerType())
7578 return ABIArgInfo::getExtend();
7579
7580 // Other non-aggregates go in registers.
7581 if (!isAggregateTypeForABI(Ty))
7582 return ABIArgInfo::getDirect();
7583
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007584 // If a C++ object has either a non-trivial copy constructor or a non-trivial
7585 // destructor, it is passed with an explicit indirect pointer / sret pointer.
7586 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00007587 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00007588
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007589 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007590 // Build a coercion type from the LLVM struct type.
7591 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
7592 if (!StrTy)
7593 return ABIArgInfo::getDirect();
7594
7595 CoerceBuilder CB(getVMContext(), getDataLayout());
7596 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00007597 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00007598
7599 // Try to use the original type for coercion.
7600 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
7601
7602 if (CB.InReg)
7603 return ABIArgInfo::getDirectInReg(CoerceTy);
7604 else
7605 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007606}
7607
John McCall7f416cc2015-09-08 08:05:57 +00007608Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7609 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007610 ABIArgInfo AI = classifyType(Ty, 16 * 8);
7611 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7612 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7613 AI.setCoerceToType(ArgTy);
7614
John McCall7f416cc2015-09-08 08:05:57 +00007615 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007616
John McCall7f416cc2015-09-08 08:05:57 +00007617 CGBuilderTy &Builder = CGF.Builder;
7618 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
7619 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
7620
7621 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
7622
7623 Address ArgAddr = Address::invalid();
7624 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007625 switch (AI.getKind()) {
7626 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007627 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007628 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007629 llvm_unreachable("Unsupported ABI kind for va_arg");
7630
John McCall7f416cc2015-09-08 08:05:57 +00007631 case ABIArgInfo::Extend: {
7632 Stride = SlotSize;
7633 CharUnits Offset = SlotSize - TypeInfo.first;
7634 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007635 break;
John McCall7f416cc2015-09-08 08:05:57 +00007636 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007637
John McCall7f416cc2015-09-08 08:05:57 +00007638 case ABIArgInfo::Direct: {
7639 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00007640 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007641 ArgAddr = Addr;
7642 break;
John McCall7f416cc2015-09-08 08:05:57 +00007643 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007644
7645 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007646 Stride = SlotSize;
7647 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
7648 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
7649 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007650 break;
7651
7652 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007653 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007654 }
7655
7656 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007657 llvm::Value *NextPtr =
7658 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
7659 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00007660
John McCall7f416cc2015-09-08 08:05:57 +00007661 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007662}
7663
7664void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7665 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00007666 for (auto &I : FI.arguments())
7667 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007668}
7669
7670namespace {
7671class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
7672public:
7673 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
7674 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00007675
Craig Topper4f12f102014-03-12 06:41:41 +00007676 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00007677 return 14;
7678 }
7679
7680 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00007681 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007682};
7683} // end anonymous namespace
7684
Roman Divackyf02c9942014-02-24 18:46:27 +00007685bool
7686SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7687 llvm::Value *Address) const {
7688 // This is calculated from the LLVM and GCC tables and verified
7689 // against gcc output. AFAIK all ABIs use the same encoding.
7690
7691 CodeGen::CGBuilderTy &Builder = CGF.Builder;
7692
7693 llvm::IntegerType *i8 = CGF.Int8Ty;
7694 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
7695 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
7696
7697 // 0-31: the 8-byte general-purpose registers
7698 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
7699
7700 // 32-63: f0-31, the 4-byte floating-point registers
7701 AssignToArrayRange(Builder, Address, Four8, 32, 63);
7702
7703 // Y = 64
7704 // PSR = 65
7705 // WIM = 66
7706 // TBR = 67
7707 // PC = 68
7708 // NPC = 69
7709 // FSR = 70
7710 // CSR = 71
7711 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00007712
Roman Divackyf02c9942014-02-24 18:46:27 +00007713 // 72-87: d0-15, the 8-byte floating-point registers
7714 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
7715
7716 return false;
7717}
7718
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007719
Robert Lytton0e076492013-08-13 09:43:10 +00007720//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00007721// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00007722//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00007723
Robert Lytton0e076492013-08-13 09:43:10 +00007724namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007725
7726/// A SmallStringEnc instance is used to build up the TypeString by passing
7727/// it by reference between functions that append to it.
7728typedef llvm::SmallString<128> SmallStringEnc;
7729
7730/// TypeStringCache caches the meta encodings of Types.
7731///
7732/// The reason for caching TypeStrings is two fold:
7733/// 1. To cache a type's encoding for later uses;
7734/// 2. As a means to break recursive member type inclusion.
7735///
7736/// A cache Entry can have a Status of:
7737/// NonRecursive: The type encoding is not recursive;
7738/// Recursive: The type encoding is recursive;
7739/// Incomplete: An incomplete TypeString;
7740/// IncompleteUsed: An incomplete TypeString that has been used in a
7741/// Recursive type encoding.
7742///
7743/// A NonRecursive entry will have all of its sub-members expanded as fully
7744/// as possible. Whilst it may contain types which are recursive, the type
7745/// itself is not recursive and thus its encoding may be safely used whenever
7746/// the type is encountered.
7747///
7748/// A Recursive entry will have all of its sub-members expanded as fully as
7749/// possible. The type itself is recursive and it may contain other types which
7750/// are recursive. The Recursive encoding must not be used during the expansion
7751/// of a recursive type's recursive branch. For simplicity the code uses
7752/// IncompleteCount to reject all usage of Recursive encodings for member types.
7753///
7754/// An Incomplete entry is always a RecordType and only encodes its
7755/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
7756/// are placed into the cache during type expansion as a means to identify and
7757/// handle recursive inclusion of types as sub-members. If there is recursion
7758/// the entry becomes IncompleteUsed.
7759///
7760/// During the expansion of a RecordType's members:
7761///
7762/// If the cache contains a NonRecursive encoding for the member type, the
7763/// cached encoding is used;
7764///
7765/// If the cache contains a Recursive encoding for the member type, the
7766/// cached encoding is 'Swapped' out, as it may be incorrect, and...
7767///
7768/// If the member is a RecordType, an Incomplete encoding is placed into the
7769/// cache to break potential recursive inclusion of itself as a sub-member;
7770///
7771/// Once a member RecordType has been expanded, its temporary incomplete
7772/// entry is removed from the cache. If a Recursive encoding was swapped out
7773/// it is swapped back in;
7774///
7775/// If an incomplete entry is used to expand a sub-member, the incomplete
7776/// entry is marked as IncompleteUsed. The cache keeps count of how many
7777/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
7778///
7779/// If a member's encoding is found to be a NonRecursive or Recursive viz:
7780/// IncompleteUsedCount==0, the member's encoding is added to the cache.
7781/// Else the member is part of a recursive type and thus the recursion has
7782/// been exited too soon for the encoding to be correct for the member.
7783///
7784class TypeStringCache {
7785 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
7786 struct Entry {
7787 std::string Str; // The encoded TypeString for the type.
7788 enum Status State; // Information about the encoding in 'Str'.
7789 std::string Swapped; // A temporary place holder for a Recursive encoding
7790 // during the expansion of RecordType's members.
7791 };
7792 std::map<const IdentifierInfo *, struct Entry> Map;
7793 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
7794 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
7795public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007796 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00007797 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
7798 bool removeIncomplete(const IdentifierInfo *ID);
7799 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
7800 bool IsRecursive);
7801 StringRef lookupStr(const IdentifierInfo *ID);
7802};
7803
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007804/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007805/// FieldEncoding is a helper for this ordering process.
7806class FieldEncoding {
7807 bool HasName;
7808 std::string Enc;
7809public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00007810 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007811 StringRef str() { return Enc; }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007812 bool operator<(const FieldEncoding &rhs) const {
7813 if (HasName != rhs.HasName) return HasName;
7814 return Enc < rhs.Enc;
7815 }
7816};
7817
Robert Lytton7d1db152013-08-19 09:46:39 +00007818class XCoreABIInfo : public DefaultABIInfo {
7819public:
7820 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00007821 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7822 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00007823};
7824
Robert Lyttond21e2d72014-03-03 13:45:29 +00007825class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007826 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00007827public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007828 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00007829 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00007830 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7831 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00007832};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007833
Robert Lytton2d196952013-10-11 10:29:34 +00007834} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00007835
James Y Knight29b5f082016-02-24 02:59:33 +00007836// TODO: this implementation is likely now redundant with the default
7837// EmitVAArg.
John McCall7f416cc2015-09-08 08:05:57 +00007838Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7839 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00007840 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00007841
Robert Lytton2d196952013-10-11 10:29:34 +00007842 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007843 CharUnits SlotSize = CharUnits::fromQuantity(4);
7844 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00007845
Robert Lytton2d196952013-10-11 10:29:34 +00007846 // Handle the argument.
7847 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00007848 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00007849 llvm::Type *ArgTy = CGT.ConvertType(Ty);
7850 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
7851 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00007852 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00007853
7854 Address Val = Address::invalid();
7855 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00007856 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00007857 case ABIArgInfo::Expand:
John McCallf26e73d2016-03-11 04:30:43 +00007858 case ABIArgInfo::CoerceAndExpand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00007859 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00007860 llvm_unreachable("Unsupported ABI kind for va_arg");
7861 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00007862 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
7863 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00007864 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007865 case ABIArgInfo::Extend:
7866 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00007867 Val = Builder.CreateBitCast(AP, ArgPtrTy);
7868 ArgSize = CharUnits::fromQuantity(
7869 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00007870 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00007871 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007872 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00007873 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
7874 Val = Address(Builder.CreateLoad(Val), TypeAlign);
7875 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00007876 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00007877 }
Robert Lytton2d196952013-10-11 10:29:34 +00007878
7879 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007880 if (!ArgSize.isZero()) {
7881 llvm::Value *APN =
7882 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7883 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007884 }
John McCall7f416cc2015-09-08 08:05:57 +00007885
Robert Lytton2d196952013-10-11 10:29:34 +00007886 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007887}
Robert Lytton0e076492013-08-13 09:43:10 +00007888
Robert Lytton844aeeb2014-05-02 09:33:20 +00007889/// During the expansion of a RecordType, an incomplete TypeString is placed
7890/// into the cache as a means to identify and break recursion.
7891/// If there is a Recursive encoding in the cache, it is swapped out and will
7892/// be reinserted by removeIncomplete().
7893/// All other types of encoding should have been used rather than arriving here.
7894void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7895 std::string StubEnc) {
7896 if (!ID)
7897 return;
7898 Entry &E = Map[ID];
7899 assert( (E.Str.empty() || E.State == Recursive) &&
7900 "Incorrectly use of addIncomplete");
7901 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7902 E.Swapped.swap(E.Str); // swap out the Recursive
7903 E.Str.swap(StubEnc);
7904 E.State = Incomplete;
7905 ++IncompleteCount;
7906}
7907
7908/// Once the RecordType has been expanded, the temporary incomplete TypeString
7909/// must be removed from the cache.
7910/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7911/// Returns true if the RecordType was defined recursively.
7912bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7913 if (!ID)
7914 return false;
7915 auto I = Map.find(ID);
7916 assert(I != Map.end() && "Entry not present");
7917 Entry &E = I->second;
7918 assert( (E.State == Incomplete ||
7919 E.State == IncompleteUsed) &&
7920 "Entry must be an incomplete type");
7921 bool IsRecursive = false;
7922 if (E.State == IncompleteUsed) {
7923 // We made use of our Incomplete encoding, thus we are recursive.
7924 IsRecursive = true;
7925 --IncompleteUsedCount;
7926 }
7927 if (E.Swapped.empty())
7928 Map.erase(I);
7929 else {
7930 // Swap the Recursive back.
7931 E.Swapped.swap(E.Str);
7932 E.Swapped.clear();
7933 E.State = Recursive;
7934 }
7935 --IncompleteCount;
7936 return IsRecursive;
7937}
7938
7939/// Add the encoded TypeString to the cache only if it is NonRecursive or
7940/// Recursive (viz: all sub-members were expanded as fully as possible).
7941void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7942 bool IsRecursive) {
7943 if (!ID || IncompleteUsedCount)
7944 return; // No key or it is is an incomplete sub-type so don't add.
7945 Entry &E = Map[ID];
7946 if (IsRecursive && !E.Str.empty()) {
7947 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7948 "This is not the same Recursive entry");
7949 // The parent container was not recursive after all, so we could have used
7950 // this Recursive sub-member entry after all, but we assumed the worse when
7951 // we started viz: IncompleteCount!=0.
7952 return;
7953 }
7954 assert(E.Str.empty() && "Entry already present");
7955 E.Str = Str.str();
7956 E.State = IsRecursive? Recursive : NonRecursive;
7957}
7958
7959/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7960/// are recursively expanding a type (IncompleteCount != 0) and the cached
7961/// encoding is Recursive, return an empty StringRef.
7962StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7963 if (!ID)
7964 return StringRef(); // We have no key.
7965 auto I = Map.find(ID);
7966 if (I == Map.end())
7967 return StringRef(); // We have no encoding.
7968 Entry &E = I->second;
7969 if (E.State == Recursive && IncompleteCount)
7970 return StringRef(); // We don't use Recursive encodings for member types.
7971
7972 if (E.State == Incomplete) {
7973 // The incomplete type is being used to break out of recursion.
7974 E.State = IncompleteUsed;
7975 ++IncompleteUsedCount;
7976 }
Malcolm Parsonsf76f6502016-11-02 10:39:27 +00007977 return E.Str;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007978}
7979
7980/// The XCore ABI includes a type information section that communicates symbol
7981/// type information to the linker. The linker uses this information to verify
7982/// safety/correctness of things such as array bound and pointers et al.
7983/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7984/// This type information (TypeString) is emitted into meta data for all global
7985/// symbols: definitions, declarations, functions & variables.
7986///
7987/// The TypeString carries type, qualifier, name, size & value details.
7988/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007989/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007990/// The output is tested by test/CodeGen/xcore-stringtype.c.
7991///
7992static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7993 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7994
7995/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7996void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7997 CodeGen::CodeGenModule &CGM) const {
7998 SmallStringEnc Enc;
7999 if (getTypeString(Enc, D, CGM, TSC)) {
8000 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Benjamin Kramer30934732016-07-02 11:41:41 +00008001 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8002 llvm::MDString::get(Ctx, Enc.str())};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008003 llvm::NamedMDNode *MD =
8004 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8005 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8006 }
8007}
8008
Xiuli Pan972bea82016-03-24 03:57:17 +00008009//===----------------------------------------------------------------------===//
8010// SPIR ABI Implementation
8011//===----------------------------------------------------------------------===//
8012
8013namespace {
8014class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8015public:
8016 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8017 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8018 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8019 CodeGen::CodeGenModule &M) const override;
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008020 unsigned getOpenCLKernelCallingConv() const override;
Xiuli Pan972bea82016-03-24 03:57:17 +00008021};
8022} // End anonymous namespace.
8023
8024/// Emit SPIR specific metadata: OpenCL and SPIR version.
8025void SPIRTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8026 CodeGen::CodeGenModule &CGM) const {
Xiuli Pan972bea82016-03-24 03:57:17 +00008027 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8028 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8029 llvm::Module &M = CGM.getModule();
8030 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
8031 // opencl.spir.version named metadata.
8032 llvm::Metadata *SPIRVerElts[] = {
Alexey Baderb3190822016-12-07 08:38:24 +00008033 llvm::ConstantAsMetadata::get(
8034 llvm::ConstantInt::get(Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8035 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8036 Int32Ty, (CGM.getLangOpts().OpenCLVersion / 100 > 1) ? 0 : 2))};
Xiuli Pan972bea82016-03-24 03:57:17 +00008037 llvm::NamedMDNode *SPIRVerMD =
8038 M.getOrInsertNamedMetadata("opencl.spir.version");
8039 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00008040 appendOpenCLVersionMD(CGM);
8041}
8042
Matt Arsenault8afb5cd2016-09-07 07:07:59 +00008043static void appendOpenCLVersionMD(CodeGen::CodeGenModule &CGM) {
Yaxun Liuf2e8ab22016-07-19 19:39:45 +00008044 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8045 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(Ctx);
8046 llvm::Module &M = CGM.getModule();
Xiuli Pan972bea82016-03-24 03:57:17 +00008047 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
8048 // opencl.ocl.version named metadata node.
8049 llvm::Metadata *OCLVerElts[] = {
8050 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8051 Int32Ty, CGM.getLangOpts().OpenCLVersion / 100)),
8052 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
8053 Int32Ty, (CGM.getLangOpts().OpenCLVersion % 100) / 10))};
8054 llvm::NamedMDNode *OCLVerMD =
8055 M.getOrInsertNamedMetadata("opencl.ocl.version");
8056 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
8057}
8058
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00008059unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8060 return llvm::CallingConv::SPIR_KERNEL;
8061}
8062
Robert Lytton844aeeb2014-05-02 09:33:20 +00008063static bool appendType(SmallStringEnc &Enc, QualType QType,
8064 const CodeGen::CodeGenModule &CGM,
8065 TypeStringCache &TSC);
8066
8067/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00008068/// Builds a SmallVector containing the encoded field types in declaration
8069/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008070static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8071 const RecordDecl *RD,
8072 const CodeGen::CodeGenModule &CGM,
8073 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00008074 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008075 SmallStringEnc Enc;
8076 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00008077 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008078 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00008079 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00008080 Enc += "b(";
8081 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00008082 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00008083 Enc += ':';
8084 }
Hans Wennborga302cd92014-08-21 16:06:57 +00008085 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00008086 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00008087 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00008088 Enc += ')';
8089 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00008090 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008091 }
8092 return true;
8093}
8094
8095/// Appends structure and union types to Enc and adds encoding to cache.
8096/// Recursively calls appendType (via extractFieldType) for each field.
8097/// Union types have their fields ordered according to the ABI.
8098static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8099 const CodeGen::CodeGenModule &CGM,
8100 TypeStringCache &TSC, const IdentifierInfo *ID) {
8101 // Append the cached TypeString if we have one.
8102 StringRef TypeString = TSC.lookupStr(ID);
8103 if (!TypeString.empty()) {
8104 Enc += TypeString;
8105 return true;
8106 }
8107
8108 // Start to emit an incomplete TypeString.
8109 size_t Start = Enc.size();
8110 Enc += (RT->isUnionType()? 'u' : 's');
8111 Enc += '(';
8112 if (ID)
8113 Enc += ID->getName();
8114 Enc += "){";
8115
8116 // We collect all encoded fields and order as necessary.
8117 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008118 const RecordDecl *RD = RT->getDecl()->getDefinition();
8119 if (RD && !RD->field_empty()) {
8120 // An incomplete TypeString stub is placed in the cache for this RecordType
8121 // so that recursive calls to this RecordType will use it whilst building a
8122 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008123 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00008124 std::string StubEnc(Enc.substr(Start).str());
8125 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8126 TSC.addIncomplete(ID, std::move(StubEnc));
8127 if (!extractFieldType(FE, RD, CGM, TSC)) {
8128 (void) TSC.removeIncomplete(ID);
8129 return false;
8130 }
8131 IsRecursive = TSC.removeIncomplete(ID);
8132 // The ABI requires unions to be sorted but not structures.
8133 // See FieldEncoding::operator< for sort algorithm.
8134 if (RT->isUnionType())
8135 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008136 // We can now complete the TypeString.
8137 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008138 for (unsigned I = 0; I != E; ++I) {
8139 if (I)
8140 Enc += ',';
8141 Enc += FE[I].str();
8142 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008143 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00008144 Enc += '}';
8145 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8146 return true;
8147}
8148
8149/// Appends enum types to Enc and adds the encoding to the cache.
8150static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8151 TypeStringCache &TSC,
8152 const IdentifierInfo *ID) {
8153 // Append the cached TypeString if we have one.
8154 StringRef TypeString = TSC.lookupStr(ID);
8155 if (!TypeString.empty()) {
8156 Enc += TypeString;
8157 return true;
8158 }
8159
8160 size_t Start = Enc.size();
8161 Enc += "e(";
8162 if (ID)
8163 Enc += ID->getName();
8164 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008165
8166 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00008167 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008168 SmallVector<FieldEncoding, 16> FE;
8169 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8170 ++I) {
8171 SmallStringEnc EnumEnc;
8172 EnumEnc += "m(";
8173 EnumEnc += I->getName();
8174 EnumEnc += "){";
8175 I->getInitVal().toString(EnumEnc);
8176 EnumEnc += '}';
8177 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8178 }
8179 std::sort(FE.begin(), FE.end());
8180 unsigned E = FE.size();
8181 for (unsigned I = 0; I != E; ++I) {
8182 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00008183 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00008184 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00008185 }
8186 }
8187 Enc += '}';
8188 TSC.addIfComplete(ID, Enc.substr(Start), false);
8189 return true;
8190}
8191
8192/// Appends type's qualifier to Enc.
8193/// This is done prior to appending the type's encoding.
8194static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8195 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00008196 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00008197 int Lookup = 0;
8198 if (QT.isConstQualified())
8199 Lookup += 1<<0;
8200 if (QT.isRestrictQualified())
8201 Lookup += 1<<1;
8202 if (QT.isVolatileQualified())
8203 Lookup += 1<<2;
8204 Enc += Table[Lookup];
8205}
8206
8207/// Appends built-in types to Enc.
8208static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8209 const char *EncType;
8210 switch (BT->getKind()) {
8211 case BuiltinType::Void:
8212 EncType = "0";
8213 break;
8214 case BuiltinType::Bool:
8215 EncType = "b";
8216 break;
8217 case BuiltinType::Char_U:
8218 EncType = "uc";
8219 break;
8220 case BuiltinType::UChar:
8221 EncType = "uc";
8222 break;
8223 case BuiltinType::SChar:
8224 EncType = "sc";
8225 break;
8226 case BuiltinType::UShort:
8227 EncType = "us";
8228 break;
8229 case BuiltinType::Short:
8230 EncType = "ss";
8231 break;
8232 case BuiltinType::UInt:
8233 EncType = "ui";
8234 break;
8235 case BuiltinType::Int:
8236 EncType = "si";
8237 break;
8238 case BuiltinType::ULong:
8239 EncType = "ul";
8240 break;
8241 case BuiltinType::Long:
8242 EncType = "sl";
8243 break;
8244 case BuiltinType::ULongLong:
8245 EncType = "ull";
8246 break;
8247 case BuiltinType::LongLong:
8248 EncType = "sll";
8249 break;
8250 case BuiltinType::Float:
8251 EncType = "ft";
8252 break;
8253 case BuiltinType::Double:
8254 EncType = "d";
8255 break;
8256 case BuiltinType::LongDouble:
8257 EncType = "ld";
8258 break;
8259 default:
8260 return false;
8261 }
8262 Enc += EncType;
8263 return true;
8264}
8265
8266/// Appends a pointer encoding to Enc before calling appendType for the pointee.
8267static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8268 const CodeGen::CodeGenModule &CGM,
8269 TypeStringCache &TSC) {
8270 Enc += "p(";
8271 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8272 return false;
8273 Enc += ')';
8274 return true;
8275}
8276
8277/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008278static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8279 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00008280 const CodeGen::CodeGenModule &CGM,
8281 TypeStringCache &TSC, StringRef NoSizeEnc) {
8282 if (AT->getSizeModifier() != ArrayType::Normal)
8283 return false;
8284 Enc += "a(";
8285 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8286 CAT->getSize().toStringUnsigned(Enc);
8287 else
8288 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8289 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00008290 // The Qualifiers should be attached to the type rather than the array.
8291 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00008292 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8293 return false;
8294 Enc += ')';
8295 return true;
8296}
8297
8298/// Appends a function encoding to Enc, calling appendType for the return type
8299/// and the arguments.
8300static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8301 const CodeGen::CodeGenModule &CGM,
8302 TypeStringCache &TSC) {
8303 Enc += "f{";
8304 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8305 return false;
8306 Enc += "}(";
8307 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8308 // N.B. we are only interested in the adjusted param types.
8309 auto I = FPT->param_type_begin();
8310 auto E = FPT->param_type_end();
8311 if (I != E) {
8312 do {
8313 if (!appendType(Enc, *I, CGM, TSC))
8314 return false;
8315 ++I;
8316 if (I != E)
8317 Enc += ',';
8318 } while (I != E);
8319 if (FPT->isVariadic())
8320 Enc += ",va";
8321 } else {
8322 if (FPT->isVariadic())
8323 Enc += "va";
8324 else
8325 Enc += '0';
8326 }
8327 }
8328 Enc += ')';
8329 return true;
8330}
8331
8332/// Handles the type's qualifier before dispatching a call to handle specific
8333/// type encodings.
8334static bool appendType(SmallStringEnc &Enc, QualType QType,
8335 const CodeGen::CodeGenModule &CGM,
8336 TypeStringCache &TSC) {
8337
8338 QualType QT = QType.getCanonicalType();
8339
Robert Lytton6adb20f2014-06-05 09:06:21 +00008340 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8341 // The Qualifiers should be attached to the type rather than the array.
8342 // Thus we don't call appendQualifier() here.
8343 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8344
Robert Lytton844aeeb2014-05-02 09:33:20 +00008345 appendQualifier(Enc, QT);
8346
8347 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8348 return appendBuiltinType(Enc, BT);
8349
Robert Lytton844aeeb2014-05-02 09:33:20 +00008350 if (const PointerType *PT = QT->getAs<PointerType>())
8351 return appendPointerType(Enc, PT, CGM, TSC);
8352
8353 if (const EnumType *ET = QT->getAs<EnumType>())
8354 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8355
8356 if (const RecordType *RT = QT->getAsStructureType())
8357 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8358
8359 if (const RecordType *RT = QT->getAsUnionType())
8360 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8361
8362 if (const FunctionType *FT = QT->getAs<FunctionType>())
8363 return appendFunctionType(Enc, FT, CGM, TSC);
8364
8365 return false;
8366}
8367
8368static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8369 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8370 if (!D)
8371 return false;
8372
8373 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8374 if (FD->getLanguageLinkage() != CLanguageLinkage)
8375 return false;
8376 return appendType(Enc, FD->getType(), CGM, TSC);
8377 }
8378
8379 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8380 if (VD->getLanguageLinkage() != CLanguageLinkage)
8381 return false;
8382 QualType QT = VD->getType().getCanonicalType();
8383 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8384 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00008385 // The Qualifiers should be attached to the type rather than the array.
8386 // Thus we don't call appendQualifier() here.
8387 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00008388 }
8389 return appendType(Enc, QT, CGM, TSC);
8390 }
8391 return false;
8392}
8393
8394
Robert Lytton0e076492013-08-13 09:43:10 +00008395//===----------------------------------------------------------------------===//
8396// Driver code
8397//===----------------------------------------------------------------------===//
8398
Rafael Espindola9f834732014-09-19 01:54:22 +00008399bool CodeGenModule::supportsCOMDAT() const {
Xinliang David Li865cfdd2016-05-25 17:25:57 +00008400 return getTriple().supportsCOMDAT();
Rafael Espindola9f834732014-09-19 01:54:22 +00008401}
8402
Chris Lattner2b037972010-07-29 02:01:43 +00008403const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008404 if (TheTargetCodeGenInfo)
8405 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008406
Reid Kleckner9305fd12016-04-13 23:37:17 +00008407 // Helper to set the unique_ptr while still keeping the return value.
8408 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
8409 this->TheTargetCodeGenInfo.reset(P);
8410 return *P;
8411 };
8412
John McCallc8e01702013-04-16 22:48:15 +00008413 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00008414 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00008415 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008416 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00008417
Derek Schuff09338a22012-09-06 17:37:28 +00008418 case llvm::Triple::le32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008419 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00008420 case llvm::Triple::mips:
8421 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00008422 if (Triple.getOS() == llvm::Triple::NaCl)
Reid Kleckner9305fd12016-04-13 23:37:17 +00008423 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
8424 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008425
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00008426 case llvm::Triple::mips64:
8427 case llvm::Triple::mips64el:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008428 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00008429
Dylan McKaye8232d72017-02-08 05:09:26 +00008430 case llvm::Triple::avr:
8431 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
8432
Tim Northover25e8a672014-05-24 12:51:25 +00008433 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00008434 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00008435 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00008436 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00008437 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00008438
Reid Kleckner9305fd12016-04-13 23:37:17 +00008439 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00008440 }
8441
Dan Gohmanc2853072015-09-03 22:51:53 +00008442 case llvm::Triple::wasm32:
8443 case llvm::Triple::wasm64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008444 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
Dan Gohmanc2853072015-09-03 22:51:53 +00008445
Daniel Dunbard59655c2009-09-12 00:59:49 +00008446 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00008447 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00008448 case llvm::Triple::thumb:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008449 case llvm::Triple::thumbeb: {
8450 if (Triple.getOS() == llvm::Triple::Win32) {
8451 return SetCGInfo(
8452 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00008453 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00008454
Reid Kleckner9305fd12016-04-13 23:37:17 +00008455 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
8456 StringRef ABIStr = getTarget().getABI();
8457 if (ABIStr == "apcs-gnu")
8458 Kind = ARMABIInfo::APCS;
8459 else if (ABIStr == "aapcs16")
8460 Kind = ARMABIInfo::AAPCS16_VFP;
8461 else if (CodeGenOpts.FloatABI == "hard" ||
8462 (CodeGenOpts.FloatABI != "soft" &&
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008463 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
Rafael Espindola0fa66802016-06-24 21:35:06 +00008464 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
Oleg Ranevskyy7232f662016-05-13 14:45:57 +00008465 Triple.getEnvironment() == llvm::Triple::EABIHF)))
Reid Kleckner9305fd12016-04-13 23:37:17 +00008466 Kind = ARMABIInfo::AAPCS_VFP;
8467
8468 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
8469 }
8470
John McCallea8d8bb2010-03-11 00:10:12 +00008471 case llvm::Triple::ppc:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008472 return SetCGInfo(
8473 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00008474 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00008475 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00008476 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00008477 if (getTarget().getABI() == "elfv2")
8478 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008479 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008480 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008481
Hal Finkel415c2a32016-10-02 02:10:45 +00008482 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8483 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008484 } else
Reid Kleckner9305fd12016-04-13 23:37:17 +00008485 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008486 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00008487 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00008488 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008489 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00008490 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00008491 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Hal Finkel415c2a32016-10-02 02:10:45 +00008492 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
Ulrich Weigand8afad612014-07-28 13:17:52 +00008493
Hal Finkel415c2a32016-10-02 02:10:45 +00008494 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
8495 IsSoftFloat));
Ulrich Weigandb7122372014-07-21 00:48:09 +00008496 }
John McCallea8d8bb2010-03-11 00:10:12 +00008497
Peter Collingbournec947aae2012-05-20 23:28:41 +00008498 case llvm::Triple::nvptx:
8499 case llvm::Triple::nvptx64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008500 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00008501
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00008502 case llvm::Triple::msp430:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008503 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00008504
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008505 case llvm::Triple::systemz: {
8506 bool HasVector = getTarget().getABI() == "vector";
Reid Kleckner9305fd12016-04-13 23:37:17 +00008507 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00008508 }
Ulrich Weigand47445072013-05-06 16:26:41 +00008509
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008510 case llvm::Triple::tce:
Pekka Jaaskelainen67354482016-11-16 15:22:31 +00008511 case llvm::Triple::tcele:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008512 return SetCGInfo(new TCETargetCodeGenInfo(Types));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00008513
Eli Friedman33465822011-07-08 23:31:17 +00008514 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00008515 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00008516 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00008517 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00008518 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00008519
John McCall1fe2a8c2013-06-18 02:46:29 +00008520 if (Triple.getOS() == llvm::Triple::Win32) {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008521 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
8522 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8523 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00008524 } else {
Reid Kleckner9305fd12016-04-13 23:37:17 +00008525 return SetCGInfo(new X86_32TargetCodeGenInfo(
8526 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
8527 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
8528 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008529 }
Eli Friedman33465822011-07-08 23:31:17 +00008530 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008531
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008532 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008533 StringRef ABI = getTarget().getABI();
Reid Kleckner9305fd12016-04-13 23:37:17 +00008534 X86AVXABILevel AVXLevel =
8535 (ABI == "avx512"
8536 ? X86AVXABILevel::AVX512
8537 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00008538
Chris Lattner04dc9572010-08-31 16:44:54 +00008539 switch (Triple.getOS()) {
8540 case llvm::Triple::Win32:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008541 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00008542 case llvm::Triple::PS4:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008543 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008544 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008545 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00008546 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00008547 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00008548 case llvm::Triple::hexagon:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008549 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
Jacques Pienaard964cc22016-03-28 21:02:54 +00008550 case llvm::Triple::lanai:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008551 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00008552 case llvm::Triple::r600:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008553 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00008554 case llvm::Triple::amdgcn:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008555 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
Chris Dewhurst7e7ee962016-06-08 14:47:25 +00008556 case llvm::Triple::sparc:
8557 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00008558 case llvm::Triple::sparcv9:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008559 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00008560 case llvm::Triple::xcore:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008561 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
Xiuli Pan972bea82016-03-24 03:57:17 +00008562 case llvm::Triple::spir:
8563 case llvm::Triple::spir64:
Reid Kleckner9305fd12016-04-13 23:37:17 +00008564 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00008565 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00008566}